【发布时间】:2020-06-23 08:21:39
【问题描述】:
我在我的测试用例文件中模拟了一个函数。
MyService.getConfigsForEntity = jest.fn().mockReturnValue(
new Promise(resolve => {
let response = [];
resolve(response);
})
);
现在我希望该文件中的所有测试用例都使用这个模拟
describe('Should render Component Page', () => {
it('should call the API', async () => {
const {container} = render(<MyComp entityName='entity1'/>);
await wait(() => expect(MyService.getConfigsForEntity).toHaveBeenCalled());
});
});
唯一的问题是只有一个测试用例我想以不同的方式模拟返回值。
但是之前和之后的所有其他测试用例都可以使用全局模拟。
describe('Should call API on link click', () => {
it('should call the API on link click', async () => {
const spy = jest.spyOn(MyService, 'getConfigsForEntity ').mockReturnValue(
new Promise(resolve => {
let response = [{
"itemName": "Dummy"
}];
resolve(response);
});
const {container} = render(<MyComp entityName='entity1'/>);
await wait(() => expect(spy).toHaveBeenCalled());
spy.mockClear();
});
});
问题是,一旦我在一个测试用例中以不同方式模拟函数,该测试用例之后使用全局模拟的所有其他测试用例都失败了,
但它只有在我将测试用例放在所有其他测试用例之后才有效。
我做错了什么?
【问题讨论】:
标签: reactjs unit-testing jestjs react-testing-library spy