使用超级测试在快速服务器上开玩笑超时

jest timeout on express server using supertest

我正在尝试使用 jestsupertest 测试 Express 应用程序的端点。这是我的文件:

// 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"
  ]
}

我不知道为什么会这样。已尝试谷歌搜索并阅读有关堆栈溢出超时错误的信息,但无济于事。

at backend/tests/integration.test.ts 只使用没有 http.createServer

的服务器

应进行更改:

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

package.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"
  }
}