EDIT 2: See the below comments
I am trying to write some tests for a middleware function, but cannot figure out how to write it so that .toHaveBeenCalled() matches the expected number of calls (in this case 1) instead of 0 calls. I currently create a variable within the test to mock an Express Response object, and pass that into the function I am testing:
index.ts
const doSomething = async (req, res) => {
....
axios(options)
.then((response) => {
const data = response.data;
...
res.status(200);
res.send();
....
}
index.test.ts
const sampleResponse = {
status: jest.fn(),
send: jest.fn(),
json: jest.fn(),
} as unknown as Response;
...
await doSomething(sampleRequest, sampleResponse);
expect(sampleResponse.status).toHaveBeenCalled();
Jest shows the lines with res.status(200) and res.send() as covered in the coverage report.
I have read some threads where this error has to do with different/distinct instances of mock functions being created when executing the test; is that the case here? Should I perhaps be testing for something entirely different (the function currently does not return anything)?
Edit:
I have pivoted to trying to test a side effect; I feel like I am close but am still getting 0 calls for this test too. I suspect it is the same issue regarding references/instances.
index.ts
import Foo from './foo.ts';
const doSomething = async (req, res) => {
....
axios(options)
.then((response) => {
const data = response.data;
...
// getInstance() looks for an instance and creates one if not defined
Foo.getInstance().doFooThings();
})
....
}
index.test.ts
import Foo from './foo.ts'
...
const fooMock = jest.spyOn(foo.prototype,'doFooThings').mockImplementation(() => Promise.resolve(console.log('hi')));
await doSomething(req, res);
expect(fooMock).toHaveBeenCalled(); // still says 0 calls, but 'hi' is getting console logged...
...