使用supertest测试Express NodeJS端点

问题描述 投票:0回答:1

我正在尝试建立一个测试环境来测试我的打字稿表达nodejs端点,但是我似乎无法使其正常工作。我已经安装:

  1. 笑话
  2. ts-jest
  3. 笑话
  4. supertest
  5. @ types / supertest
  6. @ types / jest

这是spec文件的外观:

import * as request from 'supertest';
import seed from '../../modules/contract/seed'; //empty seed function
import app from '../../index'; // export default app which is an express()

beforeAll(seed);

describe('contractService', () => {
  it('getContracts ', async () => {
    const res = await request(app).get('/getContracts');
    console.log(res.body);
  });
  it('makeContract makes and returns a new contract', async () => {
    const res = await request(app)
      .post('/makeContract')
      .send({
        name: 'testContract',
        startDate: '2019-10-3',
        challenges: []
      });
    expect(res.statusCode).toEqual(200);
    expect(res.body.challenges).toEqual([]);
    expect(res.body.name).toEqual('testContract');
    expect(res.body.startDate).toContain('2019-10-3');
  });
});

我在请求(应用程序)说到错误

此表达式不可调用。类型'typeof supertest'没有呼叫签名

contractService.spec.ts(1,1):类型起源于此导入。不能调用或构造名称空间样式的导入,并且将在运行时导致失败。考虑改为使用默认导入或导入要求。

我不知道该怎么办,因为如果我使用require而不是import,则会出现下一个错误

TypeError:无法读取未定义的属性'address'

it('getContracts ', async () => {
     const res = await request(app)
       .get('/')
        ^
       .expect(200);
});

index.ts

import './config/environment';
import http, { Server } from 'http';
import express, { Express, Router } from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import connect from './database/index';
import patientRouter from './services/patientService';
import challengeRouter from './services/challengeService';
import contractRouter from './services/contractService';

let app: Express;

const startServer = async () => {
  try {
    await connect();
    app = express();
    const routes = Router();
    app.use(bodyParser.json());
    app.use(routes);
    // app.get('/', (req: Request, res: Response) => res.sendStatus(200));
    routes.get('/', (req, res) => res.send('OK'));
    // use routers from services
    routes.use('/', patientRouter);
    routes.use('/', challengeRouter);
    routes.use('/', contractRouter);
    const httpServer: Server = http.createServer(app);
    httpServer.listen(process.env.PORT, async () => {
      console.log(`🚀 Server ready at http://localhost:${process.env.PORT}`);
    });
    const shutdown = async () => {
      await new Promise(resolve => httpServer.close(() => resolve()));
      await mongoose.disconnect();
      if (process.env.NODE_ENV === 'test') return;
      process.exit(0);
    };
    process.on('SIGTERM', shutdown);
    process.on('SIGINT', shutdown);
    process.on('SIGQUIT', shutdown);
  } catch (e) {
    console.log(e);
  }
};

startServer();

export default app;

笑话配置:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['<rootDir>/**/__tests__/**/*.spec.ts'],
  testPathIgnorePatterns: ['/node_modules/'],
  coverageDirectory: './test-reports',
  coveragePathIgnorePatterns: ['node_modules', 'src/database', 'src/test', 'src/types'],
  reporters: ['default', 'jest-junit'],
  globals: { 'ts-jest': { diagnostics: false } }
};
node.js typescript express jestjs supertest
1个回答
0
投票

在异步测试中,您需要像这样调用done()函数:

还必须通过require导入。

您可以尝试使用此代码吗?

const seed = require("../../modules/contract/seed"); //empty seed function
const app = require("../../index"); // export default app which is an express()

const request = require("supertest");

beforeAll(seed);

describe("contractService", () => {
  it("getContracts ", async done => {
    const res = await request(app).get("/getContracts");
    expect(res.status).toBe(200);
    done();
  });

  it("makeContract makes and returns a new contract", async done => {
    const res = await request(app)
      .post("/makeContract")
      .send({
        name: "testContract",
        startDate: "2019-10-3",
        challenges: []
      });
    expect(res.statusCode).toEqual(200);
    expect(res.body.challenges).toEqual([]);
    expect(res.body.name).toEqual("testContract");
    expect(res.body.startDate).toContain("2019-10-3");
    done();
  });
});

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.