问题
I was trying to integrate Jest and Supertest to build integration tests on some middleware.
I generated my middleware functions dynamically as they varied route to route, and the look like this:
export function middleware1(param: paramType) {
return async (req: Request, res: Response, next: NextFunction) => {
...
};
}
In my Jest tests, at the top of the file, I mock middleware1 as so:
jest.mock('../middleware_path', () => ({
middleware1: jest.fn(
_ => {
return (req, res, next) => {
return new Promise((resolve, reject) => {
console.log('Hello World');
resolve(next());
});
};
}),
}));
import * as middlewareUtils from 'middleware'
// This next line is necessary for TypeScript compilation
const mockedMiddlewareUtils = mocked(middlewareUtils);
When I call this function by using supertest to hit my API, it definitely uses this mock implementation. It prints hello world and everything! However, when I expect(mockedMiddlewareUtils.middleware1).toHaveBeenCalled();
in my it statement, it fails. When I run middlewareUtils.middleware1
independent of the API call, the expect resolves correctly. Why doesn't the mock correctly interpret the function call?
回答1:
It turns out this is because Express executes the middleware generating function at app creation time It's the resulting function that's continuously called throughout the app. The generating function is called once, its result is called many times.
You have to mock the function that your middleware generating function produces, (i.e. the result of middleware1
), not the generating function itself.
来源:https://stackoverflow.com/questions/60194157/remock-functions-in-jest-and-supertest