我有以下形式的代码:
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 block 中return
断言,例如使用 chai
:
return toTest.someFunction().then((result) => {
return expect(result).to.equal(expected);
});
如果您有任何其他问题,请发表评论。
关于javascript - 测试调用返回 promise 的函数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592897/