vam*_*olu 7 javascript mocking environment-variables node.js jestjs
我发现当使用jest.doMock而不是jest.mock模拟一个函数时(我需要在不同的it块中为同一个函数创建多个模拟实现),我发现测试失败了
错误
expect(jest.fn()).toBeCalled()
Expected mock function to have been called.
Run Code Online (Sandbox Code Playgroud)
此外,如果我需要在测试顶部的模块而不是在同一个 it 块中执行它,它会给我一个不同的错误:
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function headObject]
Run Code Online (Sandbox Code Playgroud)
代码
headObject(协作者被嘲笑)
// NOT IMPLEMENTED YET
module.exports = function() {}
Run Code Online (Sandbox Code Playgroud)测试代码
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()
})
Run Code Online (Sandbox Code Playgroud)源代码
const headObject = require('../s3/headObject')
module.exports = async function(event, context, callback) {
headObject()
}
Run Code Online (Sandbox Code Playgroud)之前
我使用环境变量来更改使用模拟的模拟实现,__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
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我会:
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
})
Run Code Online (Sandbox Code Playgroud)
聚会迟到......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);
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,您可以轻松地更改每个测试中的设置。
希望这对偶然发现这个问题的人有帮助
| 归档时间: |
|
| 查看次数: |
8547 次 |
| 最近记录: |