我编写了一个函数,可以在 componentDidMount 触发时成功测试。但是由于某种原因,使用相同的逻辑来测试其相邻方法是否已被触发不起作用。不知道为什么?谁能告诉我我在误解什么?
// Account.js
...
componentDidMount() {
this.checkData();
}
checkData = () => {
console.log('i am a check data method that needs testing');
}
...
// 是
// this works
it('should call the CDM function', () => {
const instance = mountedComponent.instance();
jest.spyOn(instance, 'componentDidMount');
instance.componentDidMount();
expect(instance.componentDidMount).toHaveBeenCalledTimes(1);
})
// Attempt 1 - this fails "Cannot spy the checkData property because it is not a function; undefined given instead"
it('should call the `checkData` function', () => {
const instance = mountedComponent.instance();
jest.spyOn(instance, 'checkData');
instance.componentDidMount();
expect(instance.checkData).toBeCalledTimes(1);
})
// Attempt 2 - also fails "Received number of calls: 0"
it('should call the `checkData` function', () => {
const instance = mountedComponent.instance();
instance.checkData = jest.fn();
instance.componentDidMount();
expect(instance.checkData).toBeCalledTimes(1);
})
为什么 CDM 会出现在实例中而不是checkData?>
慕森卡
相关分类