【问题标题】:How to stub SOAP client request with sinon in Node JS?如何在 Node JS 中使用 sinon 存根 SOAP 客户端请求?
【发布时间】:2017-05-30 09:06:06
【问题描述】:

我正在使用strong-soap 模块从 SOAP 请求中获取数据。

var soap = require('strong-soap').soap;

soap.createClient(url, options, function (err, client) {
     var method = client.GetInfoSOAP;
     method(requestQuery, function (err, info) {
      // bla bla
     }
}

我正在获取所需的数据。现在 我想编写单元测试用例来模拟使用sinon 存根的SOAP 请求,但没有取得任何成功。任何帮助,将不胜感激。

【问题讨论】:

  • 我的回答对你有帮助吗?

标签: node.js unit-testing soap sinon strong-soap


【解决方案1】:

您想要控制soap 对象的createClient。您可以使用以下两种技术之一来做到这一点:

  1. 依赖注入 - 公开一个 setter,您可以通过它注入一个您自己控制的假模块进行测试
  2. 使用链接接缝 - 挂钩到导入/要求机制并覆盖模块获取的内容。

Sinon项目有a nice page通过proxyquire使用链接接缝,我也有详细的how to do DI on the issue tracker。

要实现第一个,您只需在模块中执行以下操作:

module.exports._injectSoap = (fake) => soap = fake;

然后在你的测试代码中:

const fakeSoap = { createClient : sinon.stub().returns(/* ? */) }
myModule._injectSoap(fakeSoap);

...
assert(fakeSoap.createClient.calledOnce);
assert(...)

【讨论】:

    【解决方案2】:

    您好,我用以下代码解决了我的问题:

    sinon.stub(soap, 'createClient').yields(null, {
            GetInfoSOAP: function (request, cb) {
                return cb(null, myDesiredData);
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多