node.js - 使用 supertest 测试 Express NodeJS 端点
问题描述
我正在尝试建立一个测试环境来测试我的 typescript express nodejs 端点,但我似乎无法让它工作。我已经安装了:
- 笑话
- 开玩笑
- 开玩笑的
- 超测
- @types/超级测试
- @types/开玩笑
这是规范文件的外观:
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:无法读取未定义的属性“地址”
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;
笑话配置:
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 } }
};
解决方案
Late to the game, but:
import request from 'supertest';
推荐阅读
- java - 如果 Java 中的超类方法已经被子类覆盖,如何访问它?
- xaml - Xamarin 绑定不适用于生成的可观察集合
- python - Google Colab - pandas/pyplot 将只接受列引用而不是标题
- scala - 如何将地图列表传递给 Gatling 中的卵石模板?
- javascript - Bootstrap 的 Javascript 在 Rails 6 webpacker 设置中不起作用
- swift - 了解 SHA1-UPDATE 和 SHA1-FINAL 函数
- c++ - 检查所有相邻点的算法
- html - 如何使用 css 在一行中对齐和居中图像?
- python - 存储过程 - 游标状态无效
- javascript - HERE api,如何在所有计算中忽略流量