Thalatta
Thalatta

Reputation: 4578

How to successfully instantiate a db model in a Sails test

I have been following the Sails.js documentation for testing, here: http://sailsjs.org/documentation/concepts/testing

I have successfully been able to implement Controller tests that hit different paths of my app, and check the responses of different Express requests.

My trouble is knowing A) How to instantiate a Model, specifically from my User model B) How I can guarantee that the model is successfully created.

I currently have a test in which, in a before hook, I create new user with all the required attributes:

before(function(){
    User.create({firstName:"Bob", lastName: "Balaban", password:"12345", email:"[email protected]"}) 
   });

The problem is that, I do not know how to verify if this record has been added to my tests database, or if a validation error or some other error is thrown upon the call to create.

NOTE: I ask this, because a test which is dependent upon the before() hook successfully functioning fails, and the only reason it could possible fail is if the User wasn't actually added to the db

Upvotes: 1

Views: 627

Answers (1)

Fissio
Fissio

Reputation: 3758

You need to wait for the User to be created in before by using the done callback function argument, and calling it after you're done with setting up the test environment. Also, you're not lifting sails here for some reason despite the docs urging you to do so. I'd also recommend using a test database instead of your normal database so your test data is independent of your production / development data.

Example code below. The addition of done and the exec callback are probably the most vital parts.

var Sails = require('sails'), sails;

// ...

before(function(done) {

  // Increase the Mocha timeout so that Sails has enough time to lift.
  this.timeout(10000);

  Sails.lift({
    // If you want to use a different DB for testing, uncomment these and replace with your own DB info.
    /*connections: {
      // Replace the following with whatever suits you.
      testMysql: {
        adapter   : 'sails-mysql',
        host      : 'localhost',
        port      : 3306,
        user      : 'mySQLUser',
        password  : 'MyAwesomePassword',
        database  : 'testDB'
      }
    },

    models: {
      connection: 'testMysql',
      migrate: 'drop'
    }
    */
  }, function(err, server) {
    sails = server;
    if (err) return done(err);
    User.create({firstName:"Bob", lastName: "Balaban", password:"12345", email:"[email protected]"})
    .exec(function(err, createdUser) {
      if (err) {
        console.log("Failed to create user! Error below:");
        console.log(err);
      }
      else {
        console.log("User created successfully:");
        console.log(user);
      }
      done(err, sails);
    })
  });
});

Upvotes: 2

Related Questions