代码之家  ›  专栏  ›  技术社区  ›  James Ives

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

  •  1
  • James Ives  · 技术社区  · 5 年前

    我想测试的函数中有一个try/catch块。两个函数调用相同的函数 execute 函数,并在抛出错误时进行捕获。我的测试是在顶部附近模拟模块的地方设置的,然后我可以验证jest函数被调用了多少次。

    我似乎不知道该怎么做 武力 处决 在第二个测试中抛出错误,然后返回默认的模拟实现。我试着重新分配笑话。模拟个人测试,但它似乎不起作用。

    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)
        })
      })
    })
    

    任何帮助都将不胜感激!

    0 回复  |  直到 5 年前
        1
  •  2
  •   Estus Flask    5 年前

    jest.mock 在里面 should execute six commands 不影响 ../src/execute 模块,因为它已在顶层导入。

    开玩笑嘲弄 最高层已经开始嘲笑了 execute 开玩笑的间谍。最好使用 Once 不影响其他测试的实施:

    it('should execute six commands', async () => {
         execute.mockImplementationOnce(() => {
           throw new Error('throwing here so. I can ensure the error parsed properly');
         });
         ...
    

    此外,模拟应该被强制为ES模块,因为 处决 名为导入:

    jest.mock('../src/execute', () => ({
      __esModule: true,
      execute: jest.fn()
    }))
    
    推荐文章