Order of functions being executed in Express messed with tests

时光总嘲笑我的痴心妄想 提交于 2020-04-18 03:47:06

问题


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/60877150/order-of-functions-being-executed-in-express-messed-with-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!