david_adler
david_adler

Reputation: 10942

How to mock an import express.js supertest?

I have some controller / route which handles a user signing up:

controllers/user.js

const User = require('../models/User');       // What I want to mock!
...
/**
 * POST /signup
 * Create a new local account.
 */
exports.postSignup = (req, res, next) => {
  ...
  const user = new User({
    email: req.body.email,
    password: req.body.password
  });
  ...

I want to test that User is called with the right args.

test/userIntegrationTest.js

const request = require('supertest');
const app = require('../app.js');
const sinon = require('sinon');
const User = require('../models/User');

describe('POST /signup', () => {
  it('should create user with valid email', (done) => {
    const formdata = {email: '[email protected]', password: 'asdf'};

    const UserMock = sinon.mock(User);      // This mock doesn't do what I want!

    request(app)
      .post('/signup')
      .send(formdata)
      .expect(200)
      .end(function(res) {
        expect(UserMock.calledOnce).to.be.true;
        expect(UserMock.calledWith(formdata));
      })
  });
});

I expect the UserMock to be called from the controller however this mock seems to only mock the User model imported in the userIntegrationTest.js.

How do I mock the User imported in controllers/user.js.

Upvotes: 0

Views: 793

Answers (1)

hya
hya

Reputation: 1738

You could use for this proxyquire lib (https://github.com/thlorenz/proxyquire).

Example of usage:

var apiCallsMock = require('./apiCallsMock');
var messageParser  = proxyquire('../messageParser', {'./apiCalls': apiCallsMock});
var app = proxyquire('../index', {'./messageParser': messageParser});

Upvotes: 1

Related Questions