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

Jam*_*ves 7 javascript jestjs

我想要测试的函数中有一个 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)
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

Est*_*ask 4

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');
     });
     ...
Run Code Online (Sandbox Code Playgroud)

此外,模拟应该强制为 ES 模块,因为execute名为 import:

jest.mock('../src/execute', () => ({
  __esModule: true,
  execute: jest.fn()
}))
Run Code Online (Sandbox Code Playgroud)