在promise中声明函数调用 [英] Asserting function calls inside a promise

查看:304
本文介绍了在promise中声明函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为async node.js函数编写一些测试,它使用Mocha,Chai和Sinon库返回一个promise。

假设这是我的函数:

I'm writing some tests for an async node.js function which returns a promise using the Mocha, Chai and Sinon libraries.
Let's say this is my function:

function foo(params) {
  return (
    mkdir(params)
    .then(dir => writeFile(dir))
  )
}

mkdir & writeFile 都是返回promises的异步函数。

我需要测试 mkdir 正在使用 params 调用一次 foo

mkdir & writeFile are both async functions which return promises.
I need to test that mkdir is being called once with the params given to foo.

我怎么能这样做?

我见过很多关于如何断言 foo 的整体回报值的例子( sinon-as-promised 对此非常有帮助)但不是关于如何确保个别功能正在在承诺内部打电话。

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.

也许我忽视了一些东西,这不是正确的方法吗?

Maybe I'm overlooking something and this is not the right way to go?

推荐答案

mkdir 在这里不是异步调用的,所以它相当琐碎测试:

mkdir isn't called asynchronously here, so it's rather trivial to test:

mkdir = sinon.stub().resolves("test/dir")
foo(testparams)
assert(mkdir.calledOnce)
assert(mkdir.calledWith(testparams))
…

如果你想测试 writeFile 被调用,那只是稍微复杂一点 - 我们必须等待<$ c $返回的承诺在断言之前c> foo :

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:

… // 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"))
    …
})

这篇关于在promise中声明函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆