Question

I have the following code to test using sinon:

var req = new MultiPartUpload({
    client: client,
    objectName: "/" + obj.func.destPath(),
    stream: obj.outStream,
    headers: headers
  }, function (err, body) {
    obj.debug('uploaded' + body);
  });

I have to test the creation of this object. How can I do it? I have tried with:

var MultiPartUpload = require('knox-mpu');
var stub = sinon.createStubInstance(MultiPartUpload);
instance(obj, function () {
  expect(stub).to.have.been.called;
  done();
});

But it doesn't work as expected. Any suggestion? Thank you :)

EDIT:

instance is the istance of the object that creates the MultiPartUpload object. The problem is that the instance signature cannot be changed and that the MultiPartUpload library is required in the file where instance is created.

In short: I have to spy the MultiPartUpload library, and the problem is that is not possible to communicate in any way with istance, where the library is used.

Was it helpful?

Solution 2

The only way to make it work that I found was this: instead of having:

 var MultiPartUpload = require('knox-mpu');

In the instance code. I changed it to:

MultiPartUpload = require('know-mpu');

Then in the test-case I simply put:

MultiPartUpload = sinon.spy();

instance(obj, function () {
  expect(MultiPartUpload).to.have.been.called;
  done();
});

Any way to do it better than this? (I don't like global vars). Thanks :)

OTHER TIPS

From the docs:

Creates a new object with the given function as the protoype and stubs all implemented functions. The given constructor function is not invoked

This mean that sinon.createStubInstance(MultiPartUpload); will return a new stub with all prototype functions as stubs. I think you looking for a way to spy if the MultiPartUpload function was called, so one way could be to overwrite MultiPartUpload with the stub:

var MultiPartUpload = require('knox-mpu');
var stub = sinon.stub().returns(sinon.createStubInstance(MultiPartUpload));
MultiPartUpload = stub;
instance(obj, function () {
  expect(stub).to.have.been.called;
  done();
});

Have you looked into something like https://github.com/felixge/node-sandboxed-module ? When you require the instance module, you could use SandboxedModule to substitute a spy for knox-mpu.

Edit: I can't give a complete working example, because you haven't given us all your code. But sandboxed-module works something like this:

var SandboxedModule = require('sandboxed-module')
  , MultiPartUploadSpy = sinon.spy()
  , expect = chai.expect
  , YourInstanceModule = SandboxedModule.require('your-instance-module', {
      requires: {'knox-mpu': MultiPartUploadSpy}
    })

instance(obj, function () {
  expect(MultiPartUploadSpy).to.have.been.called;
  done();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top