I am testing a function which, inside it, calls a static method from a (es6 class) controller which returns the result of an API fetch. Since I'm writing a unit test and the controller has its own tests, I want to mock (technically fake) the static method from the class to give me different types of responses.
// Controller.js
class Controller {
static async fetchResults() {} // the method I want to fake
}
// func.js - the function I am writing the test for
const func = async (ctx) => {
const data = await Controller.fetchResults(ctx.req.url)
if (containsErrors(data)) ... // do some logic
return { ...data, ...otherStuff }
}
This attempt to fake the static async fetchResults() does nothing and the test attempts to call the original controller's fetchResults method.
// func.test.js
describe('when data is successfuly fetched', () => {
jest.mock('./Controller.js', () => jest.fn().mockImplementation(() => ({
fetchResults: jest.fn(() => mockResponse),
});
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});
This next attempt appears like the mock is working to some degree, but the returned value is undefined rather than { ...mockResponse, ...otherStuff } which suggests that the entire class is being mocked out but fetchResults isn't found due to it being a static method rather than an instance method.
import Controller from './Controller.js'
describe('when data is successfuly fetched', () => {
Controller.mockImplementation(jest.fn(() => ({
fetchHotel: () => { ...mockResponse, ...otherStuff }
})
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});