Express 中执行的函数顺序与测试混淆 [英] Order of functions being executed in Express messed with tests

查看:15
本文介绍了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 来调用这个函数时,它肯定使用了这个模拟实现.它打印 hello world 和所有内容!但是,当我在我的 it 语句中 expect(mockedMiddlewareUtils.middleware1).toHaveBeenCalled(); 时,它失败了.当我独立于 API 调用运行 middlewareUtils.middleware1 时,expect 正确解析.为什么模拟不能正确解释函数调用?

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天全站免登陆