In the following code I have a function that is looking for a file in the file system based on a provided configuration.
const fs = require('fs');
const { promisify } = require('util');
const lstat = promisify(fs.lstat);
async function doSomething(someFilePath) {
try {
const stats = await lstat(someFilePath);
} catch (err) {
throw err;
}
// do something with the file stats
}
module.exports = doSomething;
From here I'm trying to test the doSomething
function but it fails because the file paths I'm providing don't actually exist. The below code was working when I was using lstatSync
without promisify
.
const fs = require('fs');
const sinon = require('sinon');
const doSomething = require('./doSomething');
describe('The test', function() {
let lstatStub;
beforeEach(function() {
lstatStub = sinon.stub(fs, 'lstatSync');
});
afterEach(function() { sinon.restore() });
it('should pass', async function() {
lstatStub.withArgs('image.jpg').returns({
isFile: () => true,
isDirectory: () => false,
});
assert(await doSomething('image.jpg')).ok();
});
})
It now fails because Error: ENOENT: no such file or directory, lstat 'image.jpg'
. I've tried wrapping the stub in promisify
or exporting the promisify
ed functions into the test to stub. Both didn't work.
How do I stub a promisify
ed fs
method?