亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

強制模擬模塊在測試中拋出錯誤

強制模擬模塊在測試中拋出錯誤

婷婷同學_ 2023-05-19 17:47:13
我想測試的函數中有一個 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)    })  })})
查看完整描述

1 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

jest.mockinshould execute six commands不影響../src/execute模塊,因為它已經在頂層導入。


jest.mock在頂層已經execute用 Jest 間諜進行了嘲笑。最好使用Once實現來不影響其他測試:


it('should execute six commands', async () => {

     execute.mockImplementationOnce(() => {

       throw new Error('throwing here so. I can ensure the error parsed properly');

     });

     ...

此外,模擬應該被強制為 ES 模塊,因為execute它被命名為 import:


jest.mock('../src/execute', () => ({

  __esModule: true,

  execute: jest.fn()

}))


查看完整回答
反對 回復 2023-05-19
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號