如何在开玩笑中使用doMock?

时间:2018-03-14 00:42:22

标签: javascript node.js mocking environment-variables jest

我发现当使用jest.doMock代替jest.mock来模拟一个函数时(我需要为不同的it块中的相同函数创建多个模拟实现),我发现

测试失败

错误

expect(jest.fn()).toBeCalled()

Expected mock function to have been called.

另外,如果我需要测试顶部的模块而不是在相同的块中执行它,它会给我一个不同的错误:

expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function headObject]

代码

  1. headObject(合作者被模拟)

    // NOT IMPLEMENTED YET
    module.exports = function() {}
    
  2. 测试代码

    it('checks to see if a resource exists when given a threshold', () => {
      jest.doMock('../s3/headObject', () => {
        return jest.fn(() => {})
      })
      const headObject = require('../s3/headObject')
      handler(event.correct_uses_propertyId_withExplicitThreshold, {}, () => {})
      expect(headObject).toBeCalled()
    })
    
  3. 源代码

    const headObject  = require('../s3/headObject')
      module.exports = async function(event, context, callback) {
       headObject()
    }
    
  4. 以前

    我使用环境变量来改变模拟实现,使用__mocks__内的模拟,如下所示:

    const result = jest.genMockFromModule('../realModule.js')
    const mockResponse = require('../../eventMocks/realModuleName/fixture.json')
    
    function mock (bearerToken, address) {
      if (process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE) {
        return {
          history: []
        }
      }
      return mockResponse
    }
    
    result.mockImplementation(mock)
    
    module.exports = result
    

    在我的测试中,我会:

    it('does not store empty results in S3', () => {
      process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = true
      const res = LambdaTester(handler)
      .event(event.correct_uses_address)
      .expectResult(r => {
        expect(r.statusCode).toEqual(404)
        const body = JSON.parse(r.body)
        expect(body.message).toEqual(NO_ESTIMATE)
      })
    
      process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = false
      return res
    })
    

1 个答案:

答案 0 :(得分:0)

迟到了聚会。...doMock很痛苦。 我们在测试中使用以下设置:

// import function from module you want to mock
import getClientVersion from '../api/clientVersion';

// mock the whole module
jest.mock('../api/clientVersion');


// within a test, overwrite that specific function
getClientVersion.mockResolvedValueOnce(1);

这样做的好处是,您可以在每次测试中轻松更改设置。

希望这可以帮助那些偶然发现此问题的人