Wednesday, 24 May 2017

Mocking request object with Jasmine and Express

I have a very simple method:

module.exports = {
  login: function (username, password, req, res) {
    authModule.check_login({login: username, pass: password}).then(function (user) {
      req.session.regenerate(function () {
        req.session.user = username
        req.session.userID = user.id
        req.session.fullName = user.fullName
        req.session.email = user.email

        res.redirect('/user')
      })
    }).catch(function (err) {
      res.render('login', {
        unsuccessful: true
      })
    })
  }
}

In my unit tests I'm trying to verify that this method actually sets the session vars correctly. I've been trying to mock the request object by using jasmine.createSpy, but it doesn't seem to work, for example:

describe('user_login.login', function () {
  it('sets the session vars', function (done) {
    let req = jasmine.createSpy('req')
    const res = {
      render: function (renderTemplate, renderValues) {
        let template = renderTemplate
        let values = renderValues
      }
    }
    const userLogin = require('../helpers/user_login')
    userLogin.login(process.env.USER, process.env.PASSWORD, req, res)
    expect(req.session.regenerate).toHaveBeenCalled()
    done()
  })
})

returns:

Failures:
1) user_login.login sets the session vars
  Message:
    TypeError: Cannot read property 'regenerate' of undefined

Is there any way for me to get access to the session variables without making a request to the server? I'm trying to test the function itself, and not the server. What is the correct way of mocking the request object?

Thank you for you time.



via finferflu

No comments:

Post a Comment