node.js - Mocha 测试未达到第 2 次 Express 回调并返回第 1 次
问题描述
我需要以下代码中的帮助。我正在测试一个向特定端点发送请求的服务,我需要捕获请求的主体(为此使用 node express)。跑步者是 mocha 测试并且有超过 1 个它阻止。当我调试测试时,首先它块按预期工作(断言通过),但是当控件到达第二块时它阻塞,一旦发布请求,控件又回到第一个块,第二块中的断言永远不会到达。我在这里做错了什么?
{
var express = require("express");
var bodyPaser = require('body-parser');
var expressObj = new express();
expressObj.use(bodyPaser.json());
describe('describe', function () {
before('describe', function () {
expressObj.listen(8080);
});
it('first It', function (done) {
expressObj.post('/mytest/first', function (req, res) {
res.send("Hello");
// assert.equal(JSON.stringify(req.body), JSON.stringify('first":test'));
done();
});
});
it('second it', function (done) {
expressObj.post('/mytest/first', function (req, res) {
res.send("Hello");
// assert.equal(JSON.stringify(req.body), JSON.stringify('first":test'));
done();
});
});
});
解决方案
第一个和第二个测试只是设置路由,但您实际上并没有向您描述的任何一个路由发送请求。所以测试开始了,但第一个实际上并没有做任何事情,所以从不调用 done,这就是为什么第二个测试根本没有开始运行的原因。要测试这些路由,您需要在定义它们后为每个路由创建一个请求。这是您的代码的工作演示:
var express = require("express");
var bodyPaser = require('body-parser');
var expressObj = new express();
expressObj.use(bodyPaser.json());
const request = require('request');
describe('describe', function () {
before('describe', function (done) {
expressObj.listen(8080, function(err) {
if(err) {
console.error(err);
done(err);
return;
}
console.log('listening on localhost:8080');
done();
});
});
it('first It', function (done) {
expressObj.post('/mytest/first', function (req, res) {
res.send("Hello");
// assert.equal(JSON.stringify(req.body), JSON.stringify('first":test'));
done();
});
request.post('http://localhost:8080/mytest/first');
});
it('second it', function (done) {
expressObj.post('/mytest/second', function (req, res) {
res.send("Hello");
// assert.equal(JSON.stringify(req.body), JSON.stringify('first":test'));
done();
});
request.post('http://localhost:8080/mytest/second');
});
});
推荐阅读
- javascript - Node.js - TypeError: res.json is not a function(在某些路由中工作而不在其他路由中工作)
- javascript - 如何打开一个新窗口(音乐播放器)并将其托管在 Shopify 环境中
- python - 使用 API 进行身份验证扫描的有效 OWASP Zap 脚本示例
- tabs - 带有子选项卡的 Flutter Appbar(操作)
- android - 打开特定的文件扩展名
- javascript - 将类添加到引导轮播项目
- amazon-web-services - 我可以使用 Rancher HA 设置执行滚动升级吗
- swift - 如何找到字符串中重复的确切单词的范围(区分大小写)
- git - 本地回购提交不更新 Github - Github 页面上的 Jekyll 站点
- sql - 如何将此 ER 图转换为表格?