'then'函数并非永远不会被 Mocha 调用以进行断言检查



我在摩卡中编写了以下测试用例,其中我的代码使用Q模块。

var expect = require("chai").expect;
var utils = require("../Utils.js");
var utils1 = require("../a.js");
var sinon = require('sinon');
var request = require('requestretry');
var querySys = require('../b.js');
var Q = require("q");
describe("Sample", function () {
    var results;
    describe("#get()", function () {
        before(function (done) {
            done();
        });
        it("equal", function () {
            var deferred = Q.defer();
            var responseData = {};
            responseData.code = 200;
            responseData.data = [{a:1,b:2}];
            deferred.resolve(responseData);
            //querySys1 method uses Q promises. That is how I stubbed the response.
            sinon.stub(querySys, 'querySys1').returns(deferred.promise);
            //get function internally calls querySys1. Hence I have stubbed that.
            results = utils1.get(specification);
            results.then(function (data) {
                //Here I do see data coming as {in:1, out:1}. But still the test case is passing when compare it with {}.
                console.log(data);
                //Ideally, it should have failed. But it is passing.
                expect(data).to.be.equal({});
            });
        });
        after(function (done) {
            done();
        })
    });
});

所以,如果你看到,我正在尝试results.then部分进行断言检查。我已经打印了我正在收到的答复。这如预期的那样到来。但我故意尝试与错误的值匹配,但测试用例仍在通过。

由于您的测试不包含回调,因此执行通过主块运行,并将测试声明为通过,而无需等待 then 函数的结果。您需要让摩卡知道等待回调:

it("equal", function (done) {
    ...
    results.then(function (data) {
        console.log(data);
        expect(data).to.be.equal({});
        return done();
    });
});

当我将results.then更改为results.done时,测试开始按预期失败。有人可以说这是否是正确的方法。

相关内容

  • 没有找到相关文章

最新更新