'How to distinguish between two calls of the same method based on the argumetns?
I'm using sinon
to stub functions of the Google Drive in my NodeJS application. I do two different calls of the create
method under the same test (I can't do restore between calls):
// Call 1:
drive.files.create({ 'requestBody': requestBody, 'media': media });
// Call 2:
drive.files.create({ 'resource': resource });
In order to stub, I could do something like:
const stub = sinon.stub(drive.files, 'create').returns({
'status': 200,
'data': {
'files': [{ 'id': id }]
}
});
This stub, actually stubs both calls but what if I want to have a successful first call and fail on the second call? How do I distinguish between the two calls (maybe) based on the arguments?
Solution 1:[1]
You can use stub.withArgs(arg1[, arg2, ...]);
API.
It is also useful to create a stub that can act differently in response to different arguments.
E.g.
const sinon = require('sinon');
describe('72234931', () => {
it('should pass', () => {
const drive = {
files: {
create(opts) {},
},
};
const stub = sinon.stub(drive.files, 'create');
stub.withArgs({ requestBody: 'requestBody', media: 'media' }).returns({
status: 200,
data: {
files: [{ id: 1 }],
},
});
stub.withArgs({ resource: 'resource' }).returns({ status: 500 });
const r1 = drive.files.create({ requestBody: 'requestBody', media: 'media' });
sinon.assert.match(r1, { status: 200, data: { files: [{ id: 1 }] } });
const r2 = drive.files.create({ resource: 'resource' });
sinon.assert.match(r2, { status: 500 });
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | slideshowp2 |