【问题标题】:Attempting to run Jest/Supertest in my nodejs api but keep getting a TypeError : "app.address is not a function"尝试在我的 nodejs api 中运行 Jest/Supertest 但不断收到 TypeError :“app.address 不是函数”
【发布时间】:2021-08-14 04:10:32
【问题描述】:

我正在尝试开始对我的 nodejs api 进行集成/单元测试,但我无法通过 supertest 正确连接到我的 app.js 文件。

下面的代码写在我的 main.test.js 文件中

const app = require('../app')
const supertest = require('supertest');
const request = supertest(app)

it('posts color', async () => {
    await request.post('/postColor')
    .send({
        "Color": "Green",
}).expect(201)
})

下面是我的 app.js 文件

import express from 'express';
const app = express();

export default app;

我将 index.js 文件拆分为 app.js 和 index.js 文件。

我的 index.js 从 app.js 导入应用程序并将其设置为监听我需要的任何端口。 我的main.test.js文件从app.js中导入app,按照supertest如上图使用。

我不断收到以下错误

TypeError: app.address 不是函数

  4 |
  5 | it('posts color', async () => {
> 6 |     await request.post('/postColor')
    |                   ^

【问题讨论】:

  • 您正在混合 export 和 require,您可能需要 require('../app').default。但是调试以找出 app 当前在测试中的会有所帮助。
  • 这有帮助,但它让我回到了上一个问题,我的 api 端点返回 404 而不是 201。我觉得整个结构中缺少一些东西。 @jonrsharpe
  • 嗯,这是您对服务器的期望和实际实现之间的一个单独问题。您必须提供 minimal reproducible example,因为现在您的示例应用程序没有 any 端点,所以它总是 404。
  • 嘿@jonrsharpe 看看我对这个问题的回答。让我知道你的想法。

标签: javascript node.js jestjs supertest


【解决方案1】:

我通过将以下内容添加到我的 main.test.js 文件解决了这个问题:

const app = require('../app').default

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2022-06-10
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多