Below is an example of a utilities file that simply exposes an object with some functions. This is the easiest example of a module to test because all functions are public.
We simply require the file and write tests that the
add function works as expected.
Building on our example from above, here is the same module, but with a private helper function.
When we require the
utils module, we can’t access
Utils.add. We want to make it visible in the test environment in order to test that function, but not visible to the rest of our code base.
Here at Wealthfront we have built
privatestate lets us expose the private functions like this:
Allowing us to write tests against
Similarly to exposing a function on objects, we can expose helper functions on functions the same way.
Sometimes we want to replace our private state and dependencies when we are in test to help make testing higher level functionality easier. We will use sinon in these examples.
We’ve seen how to properly expose a private function when in a testing environment, but what if we want to stub that function and replace it with something else?
Expose it as we did previously:
And stub it out in our test:
Proxyquire lets you pass your
require call an object of stubs to use instead of module dependencies.
If we are testing
utils.js and we want to verify that
helper1.msg, we want to stub out
Helper so that we can specify
msg. Using Proxyquire, we pass the
require statement for
Utils our stub for
privatestate and Proxyquire enable us to test all of those hard-to-reach places.
Go forth and test all of the things!