我想測試的函數中有一個 try/catch 塊。這兩個函數調用同一個execute函數,如果它拋出錯誤,它們將被捕獲。我的測試是在頂部附近模擬模塊的地方設置的,然后我可以驗證該 jest 函數被調用了多少次。我似乎無法弄清楚的是如何強制 execute在第二次測試中拋出錯誤,然后返回到默認的模擬實現。我試過在個人測試中重新分配 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) }) })})
強制模擬模塊在測試中拋出錯誤
婷婷同學_
2023-05-19 17:47:13