I am trying to stub npm package phin but not having much luck. Any suggestions please?
Below is a simplied version of the code.
requestHelper.js
const phin = require('phin');
async function request(req) {
return await phin(req);
}
module.exports = {request}
requestHelper.test.js
const requestHelper = require('./requestHelper.js');
const phin = require('./node_modules/phin');
sinon.stub(phin.prototype, 'constructor').returns(true);
const result = await requestHelper.request({"something":"something"})
expect(result).to.eql(true);
sinon.stub(phin.prototype, 'constructor').returns(true) =>
Error: Trying to stub property 'constructor' of undefined
Since sinon does not support stub standalone function import from a module, Possible to stub a standalone utility function?. You can use proxyquire to do this.
Besides, I create a demo without installing the phin package, so I disabled callThru for proxyquire.
If callThru is disabled, you can stub out modules that don't even exist on the machine that your tests are running on
requestHelper.js:
const phin = require('phin');
async function request(req) {
return await phin(req);
}
module.exports = { request };
requestHelper.test.js:
const proxyquire = require('proxyquire').noCallThru();
const sinon = require('sinon');
describe('69852777', () => {
it('should pass', async () => {
const phinStub = sinon.stub().resolves(true);
const requestHelper = proxyquire('./requestHelper', {
phin: phinStub,
});
const result = await requestHelper.request({ something: 'something' });
sinon.assert.match(result, true);
sinon.assert.calledWithExactly(phinStub, { something: 'something' });
});
});
test result:
69852777
✓ should pass (1581ms)
1 passing (2s)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
requestHelper.js | 100 | 100 | 100 | 100 |
------------------|---------|----------|---------|---------|-------------------