【问题标题】:How to use doMock in jest?如何在玩笑中使用 doMock?
【发布时间】:2018-08-22 09:55:13
【问题描述】:

我发现当使用jest.doMock 而不是jest.mock 模拟一个函数时(我需要在不同的it 块中为同一个函数创建多个模拟实现),我发现测试失败了

错误

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

Expected mock function to have been called.

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

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

以前

我使用环境变量在__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
})

【问题讨论】:

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


    【解决方案1】:

    聚会迟到了....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);
    
    

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

    希望这对偶然发现这个问题的人有所帮助

    【讨论】:

    • 我在搜索doMock 时感到困惑(因为我以前用过它)并且在开玩笑的文档中没有找到它? 这似乎是一个合理的策略!
    • 添加反对票,因为虽然这很有用,但它并不能回答所提出的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多