![](/img/trans.png)
[英]Jest Unit Testing function that calls a second one that returns a promise
[英]Testing a function that calls a function that returns a promise
我有以下形式的代码:
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() {
});
});
});
我像这样使用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 }); }); });
您应该在then块中return
断言,例如,使用chai
:
return toTest.someFunction().then((result) => {
return expect(result).to.equal(expected);
});
如有其他问题,请发表评论。
我正在使用茉莉花间谍来实现此目的:
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*/);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.