nodejs mocha - 无法使用存根测试promises

时间:2018-05-02 08:44:15

标签: javascript node.js mocha es6-promise sinon

我正在尝试使用mocha对承诺进行单元测试,但是,在测试承诺时我遇到了两个问题。

1)我有Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

2)我的requestStub行为在第一次测试后没有恢复或清除,这意味着第二次测试仍取决于第一次行为。

handler.js

"use strict";

var request = require('request');

class Handler {
    constructor() {};

    getMarketData(symbol) {
        return new Promise(function(resolve, reject) {
            request("https://api.binance.com/api/v1/klines?symbol=" + symbol + "BTC&interval=1h", 
                function(err, res, body) {
                    if (err) {
                        return reject(err);
                    }
                    return resolve(JSON.parse(body));
            });
        });
    }
}

module.exports = Handler;

处理机-test.js

"use strict";

var assert = require('assert');
var sinon = require('sinon');
var proxyquire = require('proxyquire').noCallThru();

describe("Handler", function() {
    var handlerInstance;
    var requestStub;

    before(function() {
        requestStub = sinon.stub();
        var Handler = proxyquire("./handler.js", {"request": requestStub});
        handlerInstance = new Handler();
    });

    afterEach(function() {
        requestStub.restore;
    });

    describe("#getMarketData", function() {
        it("test 1", function() {
            var promise = handlerInstance.getMarketData("VTC");
            requestStub.withArgs(sinon.match.any, sinon.match.any).yields(null, null, JSON.stringify({symbol: "VTC"}));
            return promise.then(function(data) {
                assert.equals(data.symbol, "VTC");
            });
        });

        it("test 2", function() {
            var promise = handlerInstance.getMarketData("STRAT");
            requestStub.withArgs(sinon.match.any, sinon.match.any).yields(null, null, JSON.stringify({symbol: "STRAT"}));
            return promise.then(function(data) {
                assert.equal(data.symbol, "STRAT");
            });
        });
    });
});

1 个答案:

答案 0 :(得分:1)

在致电requestStub之前,您需要设置getMarketData()的行为。

当你在request()内拨打getMarketData()时,它没有任何事情要做。所以你的回调永远不会被调用,测试超时。