Express中执行的功能顺序使测试陷入混乱 [英] Order of functions being executed in Express messed with tests

查看:176
本文介绍了Express中执行的功能顺序使测试陷入混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图集成Jest和Supertest以在某些中间件上构建集成测试.

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) => {
    ...
  };
}

在我的Jest测试中,在文件的顶部,我对Middleware1进行了如下模拟:

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);

当我通过使用supertest来调用我的API来调用此函数时,它肯定会使用此模拟实现.它打印出您好世界和一切!但是,当我在自己的it语句中expect(mockedMiddlewareUtils.middleware1).toHaveBeenCalled();时,它失败了.当我独立于API调用运行middlewareUtils.middleware1时,期望会正确解析.为何模拟不能正确解释函数调用?

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?

推荐答案

事实证明,这是因为Express在应用程序创建时执行了中间件生成功能,这是在整个应用程序中不断调用的结果函数.生成函数被调用一次,其结果被调用多次.

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.

您必须模拟中间件生成函数生成的函数(即middleware1的结果),而不是生成函数本身.

You have to mock the function that your middleware generating function produces, (i.e. the result of middleware1), not the generating function itself.

这篇关于Express中执行的功能顺序使测试陷入混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆