[英]Asserting function calls inside a promise
I'm writing some tests for an async node.js function which returns a promise using the Mocha, Chai and Sinon libraries. 我正在为async node.js函数编写一些测试,它使用Mocha,Chai和Sinon库返回一个promise。
Let's say this is my function: 让我们说这是我的功能:
function foo(params) {
return (
mkdir(params)
.then(dir => writeFile(dir))
)
}
mkdir
& writeFile
are both async functions which return promises. mkdir
和writeFile
都是返回promise的异步函数。
I need to test that mkdir
is being called once with the params
given to foo
. 我需要测试mkdir
被赋予foo
的params
调用一次。
How can I do this? 我怎样才能做到这一点?
I've seen quite a few examples on how to assert the overall return value of foo
( sinon-as-promised is super helpful for that) but non about how to make sure individual functions are being called inside the promise. 我已经看到了很多关于如何断言foo
的整体返回值的例子( sinon-as-promised对此非常有帮助),但不是关于如何确保在promise中调用各个函数。
Maybe I'm overlooking something and this is not the right way to go? 也许我忽视了一些东西,这不是正确的方法吗?
mkdir
isn't called asynchronously here, so it's rather trivial to test: mkdir
在这里不是异步调用的,因此测试它是相当简单的:
mkdir = sinon.stub().resolves("test/dir")
foo(testparams)
assert(mkdir.calledOnce)
assert(mkdir.calledWith(testparams))
…
If you want to test that writeFile
was called, that's only slightly more complicated - we have to wait for the promise returned by foo
before asserting: 如果你想测试writeFile
被调用,那只是稍微复杂一点 - 我们必须在断言之前等待foo
返回的promise:
… // mdir like above
writeFile = sinon.stub().resolves("result")
return foo(testparams).then(r => {
assert.strictEqual(r, "result")
assert(writeFile.calledOnce)
assert(writeFile.calledWith("test/dir"))
…
})
You can mock the mkdir
function then use setTimeout
to check whether or not this function is called. 您可以模拟mkdir
函数,然后使用setTimeout
检查是否调用了此函数。
describe('foo', () => {
it('should call mkdir', () => {
return new Promise((resolve, reject) => {
let originalFunction = mkdir;
let timer = setTimeout(() => {
reject(`mkdir has not been called`);
});
mkdir = (...params) => new Promise(mkdirResolve => {
//restore the original method as soon as it is invoked
mkdir = originalMethod;
clearTimeout(timer);
mkdirResolve(someExpectedData);
resolve();
});
foo(params);
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.