Str*_*der 1 unit-testing spy reactjs jestjs react-testing-library
我在测试用例文件中模拟了一个函数。
MyService.getConfigsForEntity = jest.fn().mockReturnValue(
new Promise(resolve => {
let response = [];
resolve(response);
})
);
Run Code Online (Sandbox Code Playgroud)
现在我希望该文件中的所有测试用例都使用这个模拟
describe('Should render Component Page', () => {
it('should call the API', async () => {
const {container} = render(<MyComp entityName='entity1'/>);
await wait(() => expect(MyService.getConfigsForEntity).toHaveBeenCalled());
});
});
Run Code Online (Sandbox Code Playgroud)
唯一的问题是只有一个测试用例我想以不同的方式模拟返回值。
但之前和之后的所有其他测试用例都可以使用全局模拟。
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();
});
});
Run Code Online (Sandbox Code Playgroud)
问题是,一旦我在一个测试用例中以不同方式模拟该函数,该测试用例之后使用全局模拟的所有其他测试用例都会失败,
但只有当我将测试用例放在所有其他测试用例之后时,它才有效。
我究竟做错了什么?
小智 9
您可以尝试使用mockRestore():
beforeEach(() => {
spy.mockRestore();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7521 次 |
| 最近记录: |