【问题标题】:TypeError: Cannot read property 'apply' of undefined in NodeJS using JEST unit testingTypeError:无法使用 JEST 单元测试读取 NodeJS 中未定义的属性“应用”
【发布时间】:2020-06-28 07:35:34
【问题描述】:

我是 jest 单元测试以及 NodeJS 的新手,我正在尝试使用以下代码测试我的 API。

const request = require('supertest');
const quick_registration = require('../../../routes/register/quick_registration_of_user')

describe('Quick Registration of users', () => {
    beforeAll(() => {
        con.connect();
    });

    describe("GET / ", () => {
        test("It should respond with an array of students", async () => {
          const response = await request(quick_registration).get("/api/quickregistration");
          expect(response.status).toBe(200);
        });
      });
})

但是测试一直失败并给我一个错误

 FAIL  tests/routes/register/quick_registration_of_user.test.js
  Quick Registration of users
    GET /
      × It should respond with an array of students (20ms)

  ● Quick Registration of users › GET /  › It should respond with an array of students

    TypeError: Cannot read property 'apply' of undefined

      at node_modules/express/lib/router/index.js:635:15
      at next (node_modules/express/lib/router/index.js:260:14)
      at Function.handle (node_modules/express/lib/router/index.js:174:3)
      at Server.router (node_modules/express/lib/router/index.js:47:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.649s, estimated 2s
Ran all test suites.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

【问题讨论】:

  • 我认为你应该模拟 get 请求
  • con.connect(); 是什么。请提供被测的最小可重现代码。

标签: node.js api unit-testing jestjs


【解决方案1】:

我假设这条线

const quick_registration = require('../../../routes/register/quick_registration_of_user')

需要您定义路由器的文件。您需要改为要求您定义应用程序的文件。

【讨论】:

  • 谢谢,我被困了几个小时!我原以为 Express 应用程序和路由器是可以互换的。
猜你喜欢
  • 2020-06-04
  • 2018-11-27
  • 2019-05-05
  • 2020-01-17
  • 2019-09-16
  • 2019-08-30
  • 2018-11-11
  • 1970-01-01
  • 2021-06-19
相关资源
最近更新 更多