I find that when using jest.doMock
instead of jest.mock
to mock a function (I will need to create multiple mock implementations for the same function in different it
blocks), I find that the test fails with
Error
expect(jest.fn()).toBeCalled()
Expected mock function to have been called.
Also, if I require the module at the top of the test instead of doing it within the same it block, it gives me a different error:
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function headObject]
Code
headObject(Collaborator being mocked)
// NOT IMPLEMENTED YET module.exports = function() {}
Test code
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() })
Source Code
const headObject = require('../s3/headObject') module.exports = async function(event, context, callback) { headObject() }
Previously
I used environment variables to change the mock implementation using mocks within __mocks__
like this:
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
and in my test, I would:
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
})