1 回答

TA貢獻1806條經驗 獲得超8個贊
所以最好的方法是檢查結果而不是專門檢查函數調用。
實際在做什么checkData(您尚未顯示)。它是否在另一個文件中調用某些內容?
如果是這樣,請在另一個文件中模擬該函數以返回一些數據并驗證在您掛載組件時是否調用了模擬函數。
例如:
// component file
import { someMethod } from 'someModule';
export class MyComponent extends React.Component {
async checkData() {
await someMethod();
}
componentDidMount() {
this.checkData();
}
render() {
}
}
// in your spec file
import { someMethod } from 'someModule';
jest.mock('someModule');
someMethod.mockImplementation(() => {
// do whatever you want here
});
// do your all your normal setup, probably something like this
let mountedComponent;
beforeEach(() => {
mountedComponent = mount(...);
});
// clear the mock after each mount
afterEach(() => someMethod.mockClear());
it('should do things',() => {
expect(someMethod).toHaveBeenCalled();
});
添加回答
舉報