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 });
});
});
You can use jest.spyOn(object, methodName) to do this.
Eg
controller.js
:
export class Controller {
static async fetchResults(url) {
return { result: 'real result' };
}
}
func.js
:
import { Controller } from './controller';
const func = async (ctx) => {
const data = await Controller.fetchResults(ctx.req.url);
// do some logic
return { ...data };
};
export { func };
func.test.js
:
import { Controller } from './controller';
import { func } from './func';
describe('60776211', () => {
it('should pass', async () => {
const fetchResultsSpy = jest.spyOn(Controller, 'fetchResults').mockResolvedValueOnce({ result: 'fake data' });
const ctx = { req: { url: 'example.com' } };
const actual = await func(ctx);
expect(actual).toEqual({ result: 'fake data' });
fetchResultsSpy.mockRestore();
});
});
unit test results with coverage report:
PASS stackoverflow/60776211/func.test.ts
60776211
✓ should pass (5ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 91.67 | 100 | 75 | 88.89 |
controller.ts | 80 | 100 | 50 | 75 | 3
func.ts | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.922s, estimated 11s
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.