typescript - 测试时出现 Typescript、Express、Mocha 和 Chai 错误
问题描述
我在 typescript 中使用 express 制作了我的第一台服务器,它运行良好
import app from './Server'
const server = app.listen(8080, '0.0.0.0', () => {
console.log("Server is listening on standard port 80...");
});
export default server;
现在我尝试测试存储在应用程序中的路线:
import express from 'express';
import * as bodyParser from "body-parser";
const app = express();
app.use(bodyParser.json());
app.get("/", (req: express.Request, res: express.Response) => {
res.status(200).send("SUCCESS");
});
export default app;
使用此测试:
import * as chai from 'chai';
import chaiHttp = require('chai-http');
chai.use(chaiHttp);
import server from '../src';
describe("LogAPI", () => {
describe('Base express tests', () => {
it("Should return 'SUCCESS' if GET /", async () => {
return chai.request(server).get("/").then(res => {
chai.expect(res.body).to.equal("SUCCESS");
})
});
it("Should return status-code 200 by calling GET /", async () => {
return chai.request(server).get("/").then(res => {
chai.expect(res.status).to.equal(200);
})
});
});
});
但即使在运行服务器本身工作时,用
mocha --require ts-node/register ./../test/**/*.ts
向我抛出此错误:
/Users/.../NotificationService/src/Server/index.js:5 var app = express_1.default(); ^ TypeError: express_1.default 不是 Object 的函数。(/Users/.../NotificationService/src/Server/inde> x.js:5:28)
我正在使用 es6 目标和 commonjs 模块。如何正确测试我的服务器?
更新 1
我现在摆弄了一下,结果发现default()
从编译的代码中删除该方法解决了一些问题。
现在,我明白了
/Users/.../NotificationService/test/node_modules/@types/chai-http/index.d.ts:13 import * as request from 'superagent'; SyntaxError:意外的令牌导入
更新 2 我的 ts-config.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./../out“,
"strict": true,
"esModuleInterop": true
}
}
解决方案
express相关的错误是因为express没有使用默认导出,所以正确的方法是
// src.js
import * as express from 'express'
不要忘记安装类型定义,以便 Typescript 可以顺利编译它,例如
npm install @types/express --save-dev
npm install @types/body-parser --save-dev
npm install @types/chai-http --save-dev
更新:
我用这个在本地尝试过tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"types": [
"node",
"mocha",
"express"
],
"target": "es5",
"lib": [
"es2015"
],
...
},
}
使用默认导出有一些警告,如 https://basarat.gitbooks.io/typescript/docs/tips/defaultIsBad.html中所述
希望能帮助到你
推荐阅读
- python - 在 Python 中解析以空格结尾的字符串
- google-colaboratory - 无法在 Google Colab 中解压缩
- reactjs - 组件中的反应组件
- python - scapy 代码: srp(Ether()/ARP(pdst="192.168.0.100"), timeout=1, inter=0.2) 有时可以收到答案,通常不能
- excel - 如何按数组中的元素求和?
- zsh - ZSH如何绑定unicode字符?
- html - 在 div 的另一侧覆盖一个 div
- graphql - 无法理解此错误的含义
- c# - Razor Core 安装 jquery.unobtrusive.ajax 缺少 js 文件
- arrays - 在 Unix 中减少多个 IF ELSE 条件,实现数组