mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

registerMock never mocks #40

Closed CodisRedding closed 8 years ago

CodisRedding commented 8 years ago

What is it that I'm missing?

test.js

  setup(function() {
    mock.enable();
  });

  teardown(function() {
    mock.disable();
  });

  ....

  test('should return bad request when provider id is unknown', function(done) {

    var db = Helpers.database();
    db.getItem = function() {
      return function(data, cb) {
        console.log('burp');
        cb(null, {one: 1});
      };
    };

    mock.registerMock('../database', function() {console.log('mocked');return db;});

    request(app).post('/link-players')
      .set('authorization', Helpers.fakeAuthorizationHeader())
      .send({provider: {id: 'test', metadata: {deviceID: '1', username: 'username'}}})
      .expect(400, err(status[400], 'Provider unknown'))
      .end(function(err) {
        mock.deregisterMock('../database');
        done(err);
      });
  });

file-requiring-module-i-want-to-mock.js

'use strict';
var database = require('../database'); // <-----
var xtend = require('xtend');

module.exports = function attachDatabase(options) {
  return function middleware(req, res, next) {
    options = options == null ? {} : options;
    var token = (req.player != null && req.player.accessToken != null) ? req.player.accessToken : null;
    if (token != null) {
      options = xtend(options, {sessionToken: token});
    }
    req.db = database(options);
    console.log(JSON.stringify(req.db)); // <---- is always the unmocked module
    next();
  };
};
ghost commented 8 years ago

+1

tangzero commented 8 years ago

@fourq How the app variable is initialised?

I had the same problem before. You can only do require("file-requiring-module-i-want-to-mock") after setting your mock with mock.registerMock('../database', ...).

If you app was initialised before the mocking, nothing will work!

pkyeck commented 8 years ago

@tangzero thanks for pointing me in the right direction ...