Reputation: 1597
I am currently unit testing a wrapper I've written around Chokidar, which is a file system watcher, which is itself a wrapper around native fs.watch functionality. I write my tests with mocha/chai.
I know there is this wonderful library mock-fs, the caveat however is that it says at the bottom
The following fs functions are not currently mocked (if your tests use these, they will work against the real file system): fs.FSWatcher, fs.unwatchFile, fs.watch, and fs.watchFile. Pull requests welcome.
So it will not help me unit testing my watcher.
Currently I have it set up with true read/writes to the fs, without mocking, but it's tedious and timing dependent (which makes it hardware dependent).
Would anybody be able to advise me on perhaps better approaches?
Upvotes: 0
Views: 1502
Reputation: 864
I have had this problem earlier today. There is another library for mocking node fs called fs-mock . This library allows you to mock fs.watch() . You can do the following :
const Fs = require("fs-mock")
const fsmock = new Fs({
'./mock-directory': {
'file9.txt': 'fileContent9',
'file8.txt': 'fileContent8',
'file7.txt': 'fileContent7',
'file6.txt': 'fileContent6',
'file5.txt': 'fileContent5',
'file4.txt': 'fileContent4',
'file3.txt': 'fileContent3',
'file2.txt': 'fileContent2',
}
})
fsmock.watch(directory, { recursive: false },
(eventType, filename) => {
//YOUR CODE GOES HERE
})
Upvotes: 1