Summary
When testing my functions, I think I am having trouble properly stubbing a third party library function used within it.
My Code
I am writing a test suite for this bit of code in the file myCustomFunctions.js:
function myFunc(resource) {
const thirdPartyFunc = require('third-party-lib')
try {
let thirdPartyFuncOutput = thirdPartyFunc(path);
return;
}
catch (e) {
vscode.window.showErrorMessage(`Something went wrong: ${e}`);
return;
}
My Test
I set up my test like this:
const myFunc = require('../../myCustomFunctions.js');
suite('testing myCustomFunctions.js', function () {
setup(function () {
sandbox = sinon.createSandbox();
mockedInput = {
path: 'something',
options: {}
};
});
teardown(function () {
sandbox.restore();
});
test('Should generate expected output for valid resource', async function () {
const expectedOutput = 'Hi Mom';
const thirdPartyFuncStub = sandbox.stub().returns(expectedOutput);
// !!! Replace the response from the third party method here !!!
myCustomFunctions.thirdPartyFunc = thirdPartyFuncStub
await myCustomFunctions.myFunc(mockedInput);
// bunch of asserts go here
});
})
Issue
I verify that my test runner is getting to and invoking let thirdPartyFuncOutput = thirdPartyFunc(path); BUT instead of getting the mocked response it actually throws an error.
Error: ENOENT: no such file or directory, lstat 'something'
There is a 'path' property in the mockedInput that is eventually passed to the third party function, but since I stub (at least I think that's what I am doing) the whole third party function, how is the third party function actually processing that input at all? Shouldn't it behave as if it has been replaced by the stub created in the test?
Environment
- node v18.16.1
- mocha v10.2.0
- sinon v15.2.0
Try to create a new file js to handle the third-party library, then export it with define the identifier in module.exports like:
Then called it in your myCustomFunctions.js. So you can stub the third-party function by calling it the file js that you already called in myCustomFunctions.js. Maybe like this:
You can check the calledOnce method in Chai documentation.
Regards