1

I want to pass some test using mocks and stubs on sinon. controler.js:

const User = require('./models/user');
module.exports.userRead = function userRead(req, res) {
 User
 .query()
 .then(users => {
    res.render('results', {data: users});
  })
 .catch((err) => {
    res.render('error');
 });

user.test.js:

const sinon = require('sinon');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   test('should returns users', () => {
       controler.userRead(req, res);

       appStub.restore();
       appStub.verify();
   });
});

The test can't pass and I got this error:

ReferenceError: req is not defined

How can I fix that?

1 Answer 1

2

In your code, there's nothing called req

In your particular instance, just pass in {} (empty object) since your controller isn't yet doing anything with req

const sinon = require('sinon');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   test('should returns users', () => {
       controler.userRead({}, res);

       appStub.restore();
       appStub.verify();
   });
});

Another (better) alternative is to use https://github.com/howardabrams/node-mocks-http

const sinon = require('sinon');
const httpMocks = require('node-mocks-http');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   const req = httpMocks.createRequest();
   //can setup req here

   test('should returns users', () => {
       controler.userRead(req, res);

       appStub.restore();
       appStub.verify();
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and now I got this error TypeError: Cannot read property 'then' of undefined
That's actually a separate issue. User will also need to be mocked. That particular q has been answered many times - search for mocking mongoose with sinon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.