为了账号安全,请及时绑定邮箱和手机立即绑定

强制模拟模块在测试中抛出错误

强制模拟模块在测试中抛出错误

婷婷同学_ 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 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信