![](/img/trans.png)
[英]How to make Jest mocked function toHaveBeenCalledTimes has a fresh count for each test suite?
[英]How to overwrite the mocked data for a module in different test suite in Jest
我有一個場景,我必須用Jest編寫的一個單元測試用例中的一個,在不同的測試套件中更新具有不同值集的模塊的模擬響應。 這是我的測試文件,看起來像:
// test.spec.js
jest.mock('../../Service', () => ({
getState: jest.fn().mockReturnValue({
x: 'x',
y: 'y',
z: 'z'
})
})
describe('Test suite 1 - with same mocked data for Service', () => ({
// expected Service.getState() --> { x: 'x', y: 'y', z: 'z' }
})
describe('Test suite 2 - with different mocked data for Service', () => ({
// expected Service.getState() --> { a: 'a', b: 'b' }
})
如何在第二個測試套件中使用另一組值更新以下模塊的模擬值,如下所示?
jest.mock('../../Service', () => ({
getState: jest.fn().mockReturnValue ({
a: 'a',
b: 'b'
})
})
是否可以在第二個測試套件中使用beforeEach()方法覆蓋模擬值? 有人可以讓我以正確的方式處理這種情況嗎?
任何幫助,將不勝感激。
假設您有一個測試文件SomeComponent.jsx
,其中涉及../../Service
依賴項,那么您可以執行以下操作:
import { Service } from "../../Service";
jest.mock("../../Service", ({
getState: jest.fn(),
}));
describe("SomeComponent", () => {
describe('Test suite 1 - with same mocked data for Service', () => {
it('should expect mock response 1', () => {
getState.mockImplementation(() => {
return {
x: 'x',
y: 'y',
z: 'z'
}
})
expect(Service.getState()).toEqual({x: 'x', y: 'y', z: 'z'});
});
});
describe('Test suite 2 - with different mocked data for Service', () => {
it('should expect mock response 2', () => {
getState.mockImplementation(() => {
return {a: 'a', b: 'b'}
})
expect(Service.getState()).toEqual({a: 'a', b: 'b'});
});
});
});
您要測試getState的兩個對象,因此可以使用mockReturnValueOnce使模擬函數在第一次調用中返回object1,在第二次調用中返回object2。
在這種情況下,可以import {Service} from "../../Service"
。 獲得對模擬功能的訪問。 然后,您可以使用不同的測試服在測試體內調用mockImplementation來設置正確的返回值。
describe('Test suite 1 - with same mocked data for Service', () => ({ // expected Service.getState() --> { x: 'x', y: 'y', z: 'z' } jest.mock('../../Service', () => ({ getState: jest.fn().mockReturnValue({ x: 'x', y: 'y', z: 'z' }) }) }) describe('Test suite 2 - with different mocked data for Service', () => ({ // expected Service.getState() --> { a: 'a', b: 'b' } jest.mock('../../Service', () => ({ getState: jest.fn().mockReturnValue({ a: 'a', b: 'b', }) }) })
您必須在每個測試案例中分別模擬服務。 而不是全局地在describe塊中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.