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

标签 javascript jestjs

我要测试的函数中有一个 try/catch block 。两个函数调用相同的 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)
    })
  })
})
任何帮助,将不胜感激!

最佳答案

jest.mockshould execute six commands不影响 ../src/execute模块,因为它已经在顶层导入。jest.mock在顶层已经 mock execute与 Jest spy 。最好使用 Once实现不影响其他测试:

it('should execute six commands', async () => {
     execute.mockImplementationOnce(() => {
       throw new Error('throwing here so. I can ensure the error parsed properly');
     });
     ...
也应该强制模拟为 ES 模块,因为 execute被命名为进口:
jest.mock('../src/execute', () => ({
  __esModule: true,
  execute: jest.fn()
}))

关于javascript - 强制模块模拟在测试中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64391077/

相关文章:

reactjs - Jest 文件夹结构

javascript - 如何向 PhotoSwipe 添加按钮?

javascript - 带有 JSX 和类的 ReactJS 'Hello World' 不向浏览器打印任何内容

windows-7 - Jest 不显示颜色或接受命令

javascript - 使用 Jest 进行 React 组件测试

javascript - 如何使用 Jest 和 Enzyme 测试组件的条件渲染

typescript - Typescript 的 Jest 测试显示错误的错误行

javascript - Bootstrap 工具提示隐藏选择器/切换元素

javascript - Internet Explorer 给出的网页总高度为 "0"

javascript - 调用 React 渲染的 api 时 $_SESSION 为空