【发布时间】: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={() => {exampleMethod2()}}
测试突然通过了。这整件事暗示了一些奇怪的绑定恶作剧(我认为?)。任何关于发生了什么的解释将不胜感激!
【问题讨论】:
标签: reactjs unit-testing react-native enzyme jestjs