首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Sinon-Chai时,测试失败显示"Error: timeout of 2000ms exceeded“(错误:超过2000ms超时)

使用Sinon-Chai时,测试失败显示"Error: timeout of 2000ms exceeded“(错误:超过2000ms超时)
EN

Stack Overflow用户
提问于 2014-01-24 22:55:47
回答 1查看 17.5K关注 0票数 9

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

代码如下:

代码语言:javascript
复制
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作为测试跑步者。

下面是测试代码:

代码语言:javascript
复制
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)匹配,则测试通过ok。问题是,当测试失败时,失败消息是:

“错误:超过2000ms的超时时间”

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

如何使此代码显示正确的测试名称和失败原因?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-24 23:09:13

这个问题看起来像是某个地方的异常被吞噬了。我想到的第一件事就是在你的promise链的末尾添加done

代码语言:javascript
复制
exports.getProducts = function (request, response) {
    getProducts()
        .then(function (data) {
            response.write(JSON.stringify(data));
            response.end();
        })
        .done(); /// <<< Add this!
};

通常情况下,当使用promises时,您希望通过调用下面这样的方法来结束链。一些实现称其为done,一些实现称其为end

如何使此代码显示正确的测试名称和失败原因?

如果Mocha永远看不到异常,那么它就无法给您一个漂亮的错误消息。诊断可能被吞噬的异常的一种方法是添加一个try...在违规代码周围捕获块,并将某些内容转储到控制台。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21335702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档