【问题标题】:Failing test displays "Error: timeout of 2000ms exceeded" when using Sinon-Chai使用 Sinon-Chai 时测试失败显示“错误:超过 2000 毫秒的超时”
【发布时间】:2014-02-15 15:01:28
【问题描述】:

我正在为以下路线(快递)编写集成测试。

代码如下:

var q = require("q"),
    request = require("request");

/*
    Example of service wrapper that makes HTTP request.
*/
function getProducts() {

    var deferred = q.defer();

    request.get({uri : "http://localhost/some-service" }, function (e, r, body) {
        deferred.resolve(JSON.parse(body));
    });

    return deferred.promise;
}

/*
    The route
*/
exports.getProducts = function (request, response) {
    getProducts()
        .then(function (data) {
            response.write(JSON.stringify(data));
            response.end();
        });
};

我想测试所有组件是否一起工作,但使用虚假的 HTTP 响应,因此我正在为请求/http 交互创建一个存根。

我正在使用 Chai、Sinon 和 Sinon-Chai 和 Mocha 作为测试运行器。

这是测试代码:

var chai = require("chai"),
    should = chai.should(),
    sinon = require("sinon"),
    sinonChai = require("sinon-chai"),
    route = require("../routes"),
    request = require("request");

chai.use(sinonChai);

describe("product service", function () {
    before(function(done){
        sinon
        .stub(request, "get")
        // change the text of product name to cause test failure.
        .yields(null, null, JSON.stringify({ products: [{ name : "product name" }] }));
        done();
    });

    after(function(done){
        request.get.restore();
        done();
    });

    it("should call product route and return expected resonse", function (done) {

        var writeSpy = {},
            response = {
            write : function () { 
                writeSpy.should.have.been.calledWith("{\"products\":[{\"name\":\"product name\"}]}");
                done();
            }
        };

        writeSpy = sinon.spy(response, "write");

        route.getProducts(null, response);
    });
}); 

如果写入响应 (response.write) 的参数匹配,则测试通过。问题是,当测试失败时,失败消息是:

“错误:超过 2000 毫秒”

我引用了this answer,但它并不能解决问题。

我怎样才能让这个代码显示正确的测试名称和失败的原因?

NB 第二个问题可能是,响应对象的断言方式是否可以改进?

【问题讨论】:

    标签: node.js unit-testing mocha.js sinon chai


    【解决方案1】:

    这个问题看起来像是一个异常被某个地方吞没了。我首先想到的是在你的承诺链末尾添加done

    exports.getProducts = function (request, response) {
        getProducts()
            .then(function (data) {
                response.write(JSON.stringify(data));
                response.end();
            })
            .done(); /// <<< Add this!
    };
    

    当你想要通过调用这样的方法来结束你的链时,通常会出现这种情况。有些实现称之为done,有些称之为end

    我怎样才能让这个代码显示正确的测试名称和失败的原因?

    如果 Mocha 从来没有看到异常,那么它就无法给你一个很好的错误消息。诊断可能被吞下的异常的一种方法是在有问题的代码周围添加一个 try...catch 块并将某些内容转储到控制台。

    【讨论】:

    • 在运行 500 多个规格时遇到此错误的情况有什么想法吗?
    • > 一个异常被某个地方吞没了
    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 2017-06-11
    • 2018-11-13
    • 2017-09-13
    • 1970-01-01
    • 2015-02-05
    • 2015-12-16
    • 1970-01-01
    相关资源
    最近更新 更多