首页 > 解决方案 > 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();
            });
        });
    });

标签: node.jsexpressmocha.js

解决方案


第一个和第二个测试只是设置路由,但您实际上并没有向您描述的任何一个路由发送请求。所以测试开始了,但第一个实际上并没有做任何事情,所以从不调用 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');
    });
});

推荐阅读