0

I have a controller with method:

registration(req, res) {
  if (!req.user) return res.status(401).send('Registration failed');

  const { user } = req;
  return res.status(201).json({ user });
},

I want to test the registration method which sends the json with my fake data.

const { expect } = require('chai');
const sinon = require('sinon');
const authController = require(...);

describe('authController', () => {
  const USER = {
  email: 'test@test.com',
  password: 'Test12345',
  confirm: 'Test12345',
  username: 'Test',
};

it('it should send user data with email: test@test.com', () => {
  const req = { user: USER };
  const res = {
    status: sinon.stub().returnsThis(),
    json: sinon.spy(),
  };

  console.log('RES: ', res); // I can't see the json data
  authController.registration(req, res);
  expect(res.json).to.equal(USER);
});

I checked that my USER's data go into controller (req.user). I tried to look what contains res with spy, but didn't find my USER data I don't understand how to use sinon in my situation?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Sergei R
  • 701
  • 4
  • 10
  • 24

1 Answers1

1

You almost made it with the test. For this kind of test, we can use calledWith from Sinon to check functions and arguments being called properly.

describe('authController', () => {
  const USER = {
    email: 'test@test.com',
    password: 'Test12345',
    confirm: 'Test12345',
    username: 'Test',
  };

  it('it should send user data with email: test@test.com', () => {
    const req = { user: USER };
    const res = {
      status: sinon.stub().returnsThis(),
      json: sinon.spy(),
    };

    authController.registration(req, res);

    // this is how we check that the res is being called with correct arguments
    expect(res.status.calledWith(201)).to.be.ok;
    expect(res.json.calledWith({ user: USER })).to.be.ok;
  });
});

Hope it helps.

deerawan
  • 8,002
  • 5
  • 42
  • 51
  • Thanks. I was try res.json.calledWith(USER).to.equal(true); and got false. – Sergei R Jul 17 '18 at 09:24
  • @SergeiR it is because `res.json` is called with `{ user: USER }` not just `USER`. If you try this, it might work `res.json.calledWith({ user: USER })).to.equal(true)` – deerawan Jul 18 '18 at 02:23