mercredi 19 avril 2017

How to mock a function using rewirejs and chai-spies in order to test it?

tl;dr

I am trying to test an express app using mocha, chai, chai-spies and rewire.

In particular, what I am trying to do is to mock a function that exists in a module and use a chai spy instead.

My set-up

I have a module called db.js which exports a saveUser() method

db.js

module.exports.saveUser = (user) => {
  // saves user to database
};

The db module is required by app.js module

app.js

const db = require('./db');

module.exports.handleSignUp = (email, password) => {
  // create user object
  let user = {
    email: email,
    password: password
  };
  // save user to database
  db.saveUser(user); // <-- I want want to mock this in my test !!
};

Finally in my test file app.test.js I have the following

app.test.js

const chai = require('chai')
  , spies = require('chai-spies')
  , rewire = require('rewire');

chai.use(spies);
const expect = chai.expect;

// Mock the db.saveUser method within app.js
let app = rewire('./app');
let dbMock = {
  saveUser: chai.spy()
};
app.__set__('db', dbMock);

// Perform the test
it('should call saveUser', () => {
  let email = 'someone@example.com'
    , password = '123456';

  // run the method we want to test
  app.handleSignUp(email, password);

  // assert that the spy is called
  expect(dbMock.saveUser).to.be.spy; // <--- this test passes
  expect(dbMock.saveUser).to.have.been.called(); // <--- this test fails
});

My problem

My problem is that my test for ensuring that the spy is called by app.handleSignUp fails as follows

AssertionError: expected { Spy } to have been called at Context.it (spies/app.test.js:25:40)

I sense that I am doing something wrong but I am stuck at the moment. Any help is appreciated, thank you

Aucun commentaire:

Enregistrer un commentaire