简体   繁体   English

测试Promise中带有参数的函数

[英]Testing that function is called with parameter in a Promise

Given these 2 functions 鉴于这两个功能

function func1() {
  return new Promise((resolve, reject) => {
    return resolve({
      method: function(variable) {
        return variable
      }
    })
  })
}

function func2() {
  return new Promise((resolve, reject) => {
    func1()
    .then(obj => {
      return resolve(obj.method('stuff'))
    })
  })
}

Note: They are each in a separate module, with func2 require'ing/importing func1 注意:它们每个都在单独的模块中,其中func2输入/导入func1

I'm wondering how I should go about asserting that func2 resolves obj.method() with stuff as the argument. 我想知道应该如何断言func2stuff作为参数来解析obj.method() I was thinking about stubbing it using sinonJS, but I'm not sure how to go about stubbing it (As I can't really require/import the obj method to stub in my unit-test file). 我当时正在考虑使用sinonJS进行存根,但是我不确定如何进行存根(因为我不能真正要求/将obj方法导入存入我的单元测试文件中)。

My available test-suite is Mocha/Chai/Sinon, however if it's doable in some other way, those aren't a strict requirement. 我可以使用的测试套件是Mocha / Chai / Sinon,但是,如果可以通过其他方式实现,那么这些并不是严格的要求。

Slight workaround, but you should be able to do something like the following. 解决方法不大,但是您应该可以执行以下操作。

import * as functions from './func1';

const obj = {
  method: sinon.spy()
};

sinon.stub(functions, 'func1')
  .returns(new Promise(obj));

expect(obj.method).to.have.been.calledWith('stuff'); // sinon-chai expectation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM