我正在尝试使用 Node/Express 设置服务器并希望能够编写 ES6,所以我使用了 babel。
现在,服务器正在运行,我能够发出我需要的请求,但我正在尝试为它设置一个测试,以防我想进行任何修改。测试失败的原因我还不能确定。
这是我的代码,
应用程序.js:
import express from 'express';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import router from './routes/router';
// App Setup
const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' }));
router(app);
export default app;
索引.js:
import app from './app';
// Server Setup
const port = process.env.PORT || 3090;
app.listen(port, () => {
console.log(`Server listening on: ${port}`);
});
路由器.js:
const router = (app) => {
app.get('/', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
};
export default router;
test.js:
import assert from 'assert';
import request from 'supertest';
import app from '../app';
describe('The express App', () => {
it('should return 200', done => {
request(app)
.get('/')
.end((res) => {
assert.equal(200, res.statusCode);
done();
});
});
});
这是 npm 脚本:
"test": "mocha --compilers js:babel-register",
你能告诉我我做错了什么吗?谢谢!
最佳答案
因为 end callback
的第一个参数是 err
,在你的例子中是 undefined
并导致
assert.equal(200, undefined.statusCode)
正确的方法
.end((err, res) => {
if (err) return done(err);
assert.equal(200, res.statusCode);
done();
})
更好的方法是直接使用 .expect(200)
正如@R 所回答的那样。古尔布兰森。
关于javascript - 为什么我的快速测试没有通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878793/