gpt4 book ai didi

node.js - 使用 supertest 在快速服务器上开 Jest 超时

转载 作者:行者123 更新时间:2023-12-04 17:12:06 25 4
gpt4 key购买 nike

我正在尝试使用 jest 测试快速应用程序的端点和 supertest .这是我的文件:

// backend/tests/integration.test.ts
const server = require('../server');
const supertest = require('supertest');
const appTest = supertest(server);

describe('Integration tests', () => {
it('GET /api/ping', async () => {
const expected = { status: 200, body: { success: true } }
const res = await appTest.get('/api/ping');
expect(res.status).toEqual(expected.status);
expect(res.body).toEqual(expected.body);
});
});
// backend/server.ts
import app from './src/app';

const PORT = 3000;

const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

export default server;
// backend/src/app.ts
const express = require('express');
const app = express();

app.get('/api/ping', (req, res) => {
res.status(200).json({
'success': true
});
});

export default app;
我不断收到错误:
TypeError: app.address is not a function
堆栈跟踪说错误就行了:
       8 |   it('GET /api/ping', async () => {
9 | const expected = { status: 200, body: { success: true } }
> 10 | const res = await appTest.get('/api/ping');
| ^
11 | expect(res.status).toEqual(expected.status);
12 | expect(res.body).toEqual(expected.body);
13 | });

我的配置看起来像:
// package.json
...
"scripts": {
"test": "jest"
}
// jest.config.js
module.exports = {
preset: 'ts-jest',
modulePathIgnorePatterns: ["<rootDir>/dist/"],
transform: {
'^.+\/*.(ts|tsx)?$': 'ts-jest'
}
};
// babel.config.js
module.exports = {
presets: ['@babel/preset-env']
};
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"],
"exclude": [
"../node_modules"
],
"include": [
"./**/*.ts"
]
}
我不知道为什么会这样。曾尝试谷歌搜索和阅读有关堆栈溢出超时错误的信息,但无济于事。

最佳答案

后端/测试/integration.test.ts 只使用服务器而不使用 http.createServer 应该进行更改:

  • 相反 const appTest = supertest(http.createServer(server));使用 const appTest = supertest(server);
  • 如果使用 async-await ,则从不需要的签名中删除 done ,将测试签名更改为 it('GET /api/ping', async () => {...}
  • 删除规范末尾的 done 调用
  • 添加到 jest.config allowJs: true ,
  • 比较依赖项的版本

  • 包.json
    {
    "name": "node",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "jest"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
    "babel": "^6.23.0",
    "express": "^4.17.1",
    "jest": "^27.2.0",
    "supertest": "^6.1.6",
    "ts-jest": "^27.0.5"
    },
    "devDependencies": {
    "@types/jest": "^27.0.1"
    }
    }

    关于node.js - 使用 supertest 在快速服务器上开 Jest 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69237694/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com