user4547691
user4547691

Reputation:

Sails.js and Mocha, res.view testing

I write test for my sails application, but have some problem in controller. When user signup I check for duplication, if yes - render form with error, if no - render form with success message. So can anyone know how to test it right? Or maybe you can suggest better code structure, thanks a lot.

Controller :

User.findOne({ email: req.body.email }, function(err, user) {
  if(err) return res.json(err)
  if(!user) { 
    User.create({email:req.body.email, password:req.body.password}).exec(function createCB(err, user){
      if(err) return res.json(err);
      res.view('signup', { message: 'Done, user created'})
    })
  } else 
    res.view('signup', { message: 'User already exist'})
})

Test :

it('should show error if duplicated user - TODO', function (done) {
  request(sails.hooks.http.app)
    .post('/signup')
    .send({ email: '[email protected]', password: 'test' })
    .expect(200)
    .end(done)
})

So question is, how can I test res.view?

Upvotes: 1

Views: 425

Answers (2)

Andi N. Dirgantara
Andi N. Dirgantara

Reputation: 2051

I usually use simple request at my test if I want to test my view. Like this:

it('able to test view', function(done) {
  require('request-promise')('http://localhost:1337/')
    .then(function(res) {
      res.should.contains('Done, user created');
      done();
    })
    .catch(done);
});

It will check the whole body, is there any match string that we provide. Remember to do npm install request-promise --save-dev first (or any relevant library that can make request).

Or you can use supertest library as mentioned by @Yann like this

it('should be able to test view', function(done) {
  require('supertest')
    .agent(sails.hooks.http.app)
    .post('/signup')
    .send({ email: '[email protected]', password: 'test' })
    .expect(200)
    .end(function(err, res) {
      should.not.exist(err);
      res.should.contains('Done, user created');
      return done();
    });
});

Upvotes: 2

Yann Bertrand
Yann Bertrand

Reputation: 3114

You can use a library like supertest to do an HTTP request:

it('should be able to test view', function(done) {
  require('supertest')
    .agent(sails.hooks.http.app)
    .post('/signup')
    .send({ email: '[email protected]', password: 'test' })
    .expect(200)
    .end(function(err, res) {
      should.not.exist(err);
      res.should.contains('Done, user created');
      return done();
    });
});

Upvotes: 1

Related Questions