我使用jest.spyOn模拟了一个独立的类方法,但实际的方法不是模拟的实现,而是调用的



类文件

//Consumer class
class Consumer {
constructor(){
}
getConsumerData(){
//does something and does not return anything
}
}

点击内部反应组件按钮这种方法被称为

//ReactComponent.tsx

handleButtonClick() {
Consumer.getConsumerData();
}

测试文件

const methodSpy = jest.spyOn(Consumer.prototype, "getConsumer").mockImplementation(()=>{});
expect(methodSpy).toHaveBeenCalled();

您可以模拟整个消费者

  1. 确保Consumer是其文件的默认导出
import Consumer from './consumer';
///...
jest.mock('./consumer'); // SoundPlayer is now a mock constructor

beforeEach(() => {
// Clear all instances and calls to the constructor and all methods:
Consumer.mockClear();
});
/// Your tests

更多详细信息:https://jestjs.io/docs/es6-class-mocks

最新更新