node.js - 使用 supertest 测试 Express NodeJS 端点

标签 node.js typescript express jestjs supertest

我正在尝试设置一个测试环境来测试我的 typescript express nodejs 端点,但我似乎无法让它工作。我已经安装:

  • 开 Jest
  • ts-jest
  • jest-junit
  • super 测试
  • @types/supertest
  • @types/jest

  • 这是规范文件的样子:
    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');
      });
    });
    

    我在请求(应用程序)上收到一个错误说

    This expression is not callable. Type 'typeof supertest' has no call signatures

    contractService.spec.ts(1, 1): Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.



    我不知道该怎么做,因为如果我使用 require 而不是 import,我会收到下一个错误

    TypeError: Cannot read property 'address' of undefined


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

    索引.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;
    

    Jest 配置:
    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 } }
    };
    

    最佳答案

    比赛迟到了,但是:

    import request from 'supertest';
    

    关于node.js - 使用 supertest 测试 Express NodeJS 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449508/

    相关文章:

    node.js - 如何在 Microsoft Bot Builder 中使用电子邮件 channel

    node.js - 按关联模型排序时,Sequelize 抛出错误 "Unable to find a valid association for model x"

    typescript - React Navigation TypeScript : Argument of type . .. 不可分配给类型为 'BottomTabNavigatorConfig' 的参数

    javascript - 在一个文件中要求express并在另一个文件中使用express.static

    node.js - Express/Node 是否需要 View 引擎?

    mysql - NodeJS/Sequelize/MySQL - 为什么需要 postgres 依赖项?

    web-services - 如何使用 Restify 增加服务器端的套接字超时?

    angular - 使用 Typescript 在 Angular 中忽略 GET 请求中未定义的属性集

    typescript - 我在哪里可以看到 deno 下载的软件包?

    javascript - 验证错误: "g-recaptcha-response" is not allowed