How to stub SOAP client request with sinon in Node JS?

左心房为你撑大大i 提交于 2019-12-25 17:03:26

问题


I am using strong-soap module to get data from SOAP request.

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

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

I am getting the required data. Now I want to write unit test case to mock the SOAP request using sinon stub, but didn't get any success. Any help would be appreciated.


回答1:


What you want is controlling the soap object's createClient. You can do that using techniques that fall into one of two categories:

  1. Dependency injection - expose a setter through which you can inject a fake module you control yourself for testing
  2. Using link seams - hook into the import/require mechanism and override what the module is getting.

The Sinon project has a nice page on using link seams through proxyquire, and I have also detailed how to do DI on the issue tracker.

To achieve the first, all you need is to do something like this in the module:

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

Then in your test code:

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

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



回答2:


Hi i have solved my problem with the following code :

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


来源:https://stackoverflow.com/questions/44257933/how-to-stub-soap-client-request-with-sinon-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!