婷婷同學(xué)_
2023-05-19 17:47:13
我想測試的函數(shù)中有一個 try/catch 塊。這兩個函數(shù)調(diào)用同一個execute函數(shù),如果它拋出錯誤,它們將被捕獲。我的測試是在頂部附近模擬模塊的地方設(shè)置的,然后我可以驗證該 jest 函數(shù)被調(diào)用了多少次。我似乎無法弄清楚的是如何強制 execute在第二次測試中拋出錯誤,然后返回到默認的模擬實現(xiàn)。我試過在個人測試中重新分配 jest.mock 但它似乎不起作用。import {execute} from '../src/execute'jest.mock('../src/execute', () => ({ execute: jest.fn()}))describe('git', () => { afterEach(() => { Object.assign(action, JSON.parse(originalAction)) }) describe('init', () => { it('should stash changes if preserve is true', async () => { Object.assign(action, { silent: false, accessToken: '123', branch: 'branch', folder: '.', preserve: true, isTest: true, pusher: { name: 'asd', email: 'as@cat' } }) await init(action) expect(execute).toBeCalledTimes(7) }) }) describe('generateBranch', () => { it('should execute six commands', async () => { jest.mock('../src/execute', () => ({ execute: jest.fn().mockImplementation(() => { throw new Error('throwing here so. I can ensure the error parsed properly'); }); })) Object.assign(action, { silent: false, accessToken: '123', branch: 'branch', folder: '.', pusher: { name: 'asd', email: 'as@cat' } }) // With how this is setup this should fail but its passing as execute is not throwing an error await generateBranch(action) expect(execute).toBeCalledTimes(6) }) })})
1 回答

HUWWW
TA貢獻1874條經(jīng)驗 獲得超12個贊
jest.mockinshould execute six commands不影響../src/execute模塊,因為它已經(jīng)在頂層導(dǎo)入。
jest.mock在頂層已經(jīng)execute用 Jest 間諜進行了嘲笑。最好使用Once實現(xiàn)來不影響其他測試:
it('should execute six commands', async () => {
execute.mockImplementationOnce(() => {
throw new Error('throwing here so. I can ensure the error parsed properly');
});
...
此外,模擬應(yīng)該被強制為 ES 模塊,因為execute它被命名為 import:
jest.mock('../src/execute', () => ({
__esModule: true,
execute: jest.fn()
}))
添加回答
舉報
0/150
提交
取消