Testing on the Filesystem
Testing Javascript modules that use the filesystem can be a little annoying
to test sometimes, especially when using awesome parallel test runners like
Ava. While developing
MARSS, my Markdown blogging system, I
tried to find a good way of running the tests, so they could effectively
have their own environment (read folder) to test in. I came accrossmemfs, which implements thefs module in a virtual filesystem in memory.
The author also createdfs-monkey, which allows you to
patch the fs module with a given fs-like implementation.
With these, you are able to make the code you are testing use your own
specially crafted filesystem. Woot. (Un)fortunately, the require function
also uses the fs module to read files, so when you patch the fs module,
you also restrict importing any more modules. Luckily, the author hasunionfs which allows you to
patch two file systems together - phew.
Wiring it all together it allows you to create a test file system that you
can then use to test Javascript that does operations on the file system. Below
is the module I created for doing such a thing and how I used it in my
tests.
Test file system module
The below module sets up the virtual test file system and patches the fs
module for the tests.
Test that uses the test file system module
The test loads above module, loads tests files into is using thememfs .fromJson() function into a folder based on the test process id.
|
|