提问者:小点点

使用Sinon Chai时,失败测试显示“错误:超时超过2000ms”


我有以下路线(快速),我正在为此编写集成测试。

代码如下:

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 毫秒”

我已经引用了这个答案,但它并不能解决问题。

如何让这段代码显示正确的测试名称和失败的原因?

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


共1个答案

匿名用户

这个问题似乎有一个例外正在被吞噬。我想到的第一件事是在你的promise链末尾添加done

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

通常情况下,在使用promise时,您希望通过调用这样的方法来结束链。有些实现称它已完成,有些则称为结束

如何让这段代码显示正确的测试名称和失败的原因?

如果Mocha从未看到异常,它就无法为您提供一条漂亮的错误消息。诊断可能吞咽异常的一种方法是在违规代码周围添加一个try… catch块并将某些内容转储到控制台。