测试调用返回promise的函数的函数

时间:2017-01-11 14:00:07

标签: javascript sinon chai chai-as-promised proxyquire

我的代码如下:

sut.methodtotest = param => {
    return dependency.methodcall(param)
        .then((results) => {
            return results;
        });
};

我想测试sut.methodtotest,但是当我使用chai,mocha,require,sinon以及Javascript社区可以使用的众多其他框架时,我收到错误消息:

dependency.methodcall(...).then is not a function

我的问题是:如何模拟dependency.methodcall以便它返回一些模拟数据,以便'then'函数可用?

我的测试代码如下所示

describe("my module", function() {
    describe("when calling my function", function() {

        var dependency =  require("dependency");

        var sut =  proxyquire("sut", {...});

        sut.methodtotest("");

        it("should pass", function() {

        });
    });
});

2 个答案:

答案 0 :(得分:1)

我使用sinon的沙箱,就像这样



var sandbox = sinon.sandbox.create();
var toTest = require('../src/somemodule');

describe('Some tests', function() {
  //Stub the function before each it block is run
  beforeEach(function() {
    sandbox.stub(toTest, 'someFunction', function() {
      //you can include something in the brackets to resolve a value 
      return Promise.resolve();  
    });
  });
  
  //reset the sandbox after each test
  afterEach(function() {
    sandbox.restore();  
  });
  
  it('should test', function() {
    return toTest.someFunction().then(() => {
      //assert some stuff                                  
    });
  });
});




你应该在{b}块中进行return断言,例如与chai

return toTest.someFunction().then((result) => {
    return expect(result).to.equal(expected);                
});

如果您有任何其他问题,请发表评论。

答案 1 :(得分:1)

我使用jasmine spies来实现这一目标:

beforeEach(function() {
    //stub dictionary service
    dictionaryService = {
        get: jasmine.createSpy().and.callFake(function() {
            return { then: function(callback) {
                return callback(/*mocked data*/);
            } };
        })
    };
});

it('should call dictionary service to get data', function () {
    expect(dictionaryService.get).toHaveBeenCalledWith(/*check mocked data*/);
});