【问题标题】:Mocking component methods with jest用笑话模拟组件方法
【发布时间】:2017-12-10 23:29:57
【问题描述】:

假设我有以下组件:

export class ExampleComponent extends Component {

    exampleMethod1 = () => {
      console.log('in example 1')
    }

    exampleMethod2 = () => {
      console.log('in example 2')
      this.exampleMethod1()
    }

    render() {
      return (
        <TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
      )
    }
}

这完全符合您的预期。按钮出现,并且可以按下。两种方法都会触发,并且控制台会记录它们的文本。

我现在试着用玩笑来测试这个:

describe('example tests', () => {
  let wrapper
  beforeEach(() => {
    wrapper = shallow(<ExampleComponent/>)
  })

  it('this test fails. Interestingly both messages still print', () => {
    const instance = wrapper.instance()
    instance.exampleMethod2 = jest.fn()
    wrapper.find('#touchable').simulate('press')
    //wrapper.update() uncommenting this line has no effect.
    expect(instance.exampleMethod2.mock.calls.length).toBe(1)
  })

  it('this test passes. Only the first message prints', () => {
    const instance = wrapper.instnace()
    instance.exampleMethod1 = jest.fn()
    wrapper.find('#touchable').simulate('press')
    expect(instance.exampleMethod1.mock.calls.length).toBe(1)
  })
})

如注释所示,第一个测试失败,并且打印出原始消息,就好像我从未模拟过该方法一样。无论wrapper.update() 是否运行,都会发生这种情况。

有趣的是,如果我们将 onPress 替换为看似相同的箭头函数,如下所示:

onPress={() =&gt; {exampleMethod2()}}

测试突然通过了。这整件事暗示了一些奇怪的绑定恶作剧(我认为?)。任何关于发生了什么的解释将不胜感激!

【问题讨论】:

    标签: reactjs unit-testing react-native enzyme jestjs


    【解决方案1】:

    如果您想在组件的原型对象上测试自定义方法,您应该使用酶中的mount 函数并使用spyOn 模拟和跟踪对该方法的调用。

    export class ExampleComponent extends Component {
    
      exampleMethod1 = () => {
        console.log('in example 1');
        this.setState({ example1: true });
      }
    
      exampleMethod2 = () => {
        console.log('in example 2')
        this.exampleMethod1()
      }
    
      render() {
        return (
          <TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
        )
      }
    

    }

    describe('example tests', () => {
      let wrapper
      beforeEach(() => {
        wrapper = mount(<ExampleComponent/>)
      })
    
      afterAll(() => { wrapper = null; })
    
      it('some desc here', () => {
        const instance = wrapper.instance();
        spyOn(instance, 'exampleMethod1').and.callThrough();
        expect(instance.setState).toHaveBeenCalled();
      });
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      相关资源
      最近更新 更多