【问题标题】:Mocha unit testing routes return 200 okMocha 单元测试路线返回 200 ok
【发布时间】:2015-01-06 18:00:01
【问题描述】:

我正在使用 mocha 测试我添加到服务器的某些路由是否返回 200 ok 以及响应是否包含字符串。我这样做的方式如下:

var testDBRoute = function(link, routeName) {
    it('should return 200 OK for ' + routeName, function (done) {
        http.get(link, function (res) {
            assert.equal(200, res.statusCode);
            done();
        })
    });

    it('should return the correct info',
        function(done) {
            http.get(link, function (res) {
                var body = '';

                res.on('data', function(chunk) {
                    body += chunk;
                });

                res.on('end', function() {
                    var response = JSON.parse(body);
                    assert.equal('abc', response.id);   
                    done();
                });
            });

        }
    )
    };

我以同样的方式调用了这个函数 6 次:

describe('/link1', function () {
            var link = HOST + '/api/link1/';
            testDBRoute(link, 'link1');
});

无论请求的顺序如何,它总是在第 8 次测试时失败,这意味着它正在发出 8 个 http get 请求,然后失败并出现以下错误:

错误:超过 2000 毫秒的超时 在空。 (\node_modules\mocha\lib\runnable.js:158:19) 在 Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

我必须指定我在 Windows 上运行测试。

【问题讨论】:

    标签: javascript node.js http mocha.js


    【解决方案1】:

    我已经解决了这个问题,使用superTest 来替换 http 像这样

    var request = require('supertest');
    var app = require('../server');
    // app is the express context from the server
        describe('GET /api', function () {
            it('test api', function (done) {
                request(app)
                    .get('/api')
                    .end (function (err, res) {
                         assert.equal(200, res.statusCode);
                         done();
                     });
            });
        });
    

    看来问题出在 http 模块上……

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2011-03-25
      • 2019-10-29
      相关资源
      最近更新 更多