Now, the way that rewire works is it requires you to use rewire instead of require when you're loading in the file that you want to mock out. For this example, we want to replace db with something else, so when we load an app we have to load it in in a special way. We'll make a variable called app, and we'll set it equal to rewire followed by what we would usually put inside of require. In this case it's a relative file, a file that we created ./app will get the job done:
const expect = require('expect');
const rewire = require('rewire');
var app = rewire('./app');
Now rewire loads your file through require, but it also adds two methods onto app. These methods are:
- app.__set__
- app.__get__
We can use these to mock out various data inside of app.js. That means we'll make a simulation of the db object, the one that comes back from db.js, but we'll swap out the function with a spy.
Inside our describe block, we can kick things off by making a variable. This variable is going to be called db, and we'll set it equal to an object:
describe('App', () => {
var db = {
}
The only thing we need to mock out in our case is saveUser. Inside the object, we'll define saveUser and then I'll set it equal to a spy by creating one using expect.createSpy, just like this:
describe('App', () => {
var db = {
saveUser: expect.createSpy()
};
Now we have this db variable, and the only thing left to do is replace it. We do that using app.__set__, and this is going to take two arguments:
describe('App', () => {
var db = {
saveUser: expect.createSpy()
};
app.__set__();
The first one is the thing you want to replace. We're trying to replace db, and we're trying to replace it with the db variable, which is our object that has the saveUser function:
describe('App', () => {
var db = {
saveUser: expect.createSpy()
};
app.__set__('db', db);
With that in place, we can now write a test that verifies that handleSignup does indeed call saveUser.