Sometimes when writing a unit test, you know that the module you're testing imports a module that you would like to observe, or at the very least mock to prevent side effects like network activity or file system operations.
For JavaScript unit tests that run in Node, we can hijack the built-in require
function by using the proxyquire
module, which allows us to mock one or more modules that are second-class dependencies in our unit test, replacing them with whatever we want.
This means we could replace functions with no-ops to prevent side effects, or replace them with Sinon spies to observe the inner workings of the module you're testing.
In this video, we'll demonstrate the basics of using Proxyquire to prevent and observe a file system operation.
Instructor: [00:00] Here we have a module that writes a string to a file on the file system. When running unit tests, we don't want that file system write to actually happen. So we create a file system mock as an empty object and use the proxyquire module as a stand-in for the normal require function, require our module, and then pass it a second argument where we tell it what module that that module requires that we want to mock.
[00:25] Now in our unit test, we can mock out the writeFileSync function that we don't want to actually get called using a sign-on spy. We can call our function, give it a file name and some contents. We can assert the arguments that were passed to writeFileSync by using our spy.
[00:45] Check the first call. Get its arguments, and assert that they were equal to the arguments that were passed.
[00:54] We can run our unit test and see that it passes. As you can see, we are able to use a mock and the proxyquire function to import our module and mock out a module that it requires, then mock out the function that is called by our function and assert what arguments were passed to it. This way, the actual fs.writeFileSync function never actually gets called.