Unable to access instance of Sails.js application in integration tests

I am trying to write some integration tests in sailsjs. I have a bootstrap.test.js file that raises my server globally before docs suggests .

In my integration test, when I try to transfer the application for my sails, I get an error message:

app is not defined
agent = request.agent(app.hooks.http.app);
                      ^

bootstrap.test.js

var Sails = require('sails'),
  Barrels = require('barrels'),
  app;

before(function(done) {
  console.log('Global before hook'); // Never called?
  this.timeout(5000);

  Sails.lift({

    log: {
      level: 'error'
    },
    models: {
      connection: 'test',
      migrate: 'drop'
    }
  }, function(err, sails) {
    app = sails;
    if (err) return done(err);

    var barrels = new Barrels();
    fixtures = barrels.data;

    barrels.populate(function(err) {
      done(err, sails);
    });
  });
});

// Global after hook
after(function (done) {
  console.log(); // Skip a line before displaying Sails lowering logs
  Sails.lower(done);
});

integration test

var chai = require('chai'),
  expect = chai.expect,
  request = require('supertest'),
  agent = request.agent(app.hooks.http.app);

describe('Species CRUD test', function() {

  it('should not allow an unauthenticated user create a species', function(done){
    var species = {
      scientificName: 'Latin name',
      commonName: 'Common name',
      taxon: 'Amphibian',
      leadOffice: 'Vero Beach',
      range: ['Florida', 'Georgia']
    };

    agent.post('species')
      .send(species)
      .end(function(err, species) {
        expect(err).to.exist;
        expect(species).to.not.exist;
        done();
      });
  });
});
+4
source share
2 answers

I have been trying to do integration work for more than a few days. This seems to work fine in my environment. Perhaps you can try.

bootstrap.test.js

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

before(function(done)
{
  Sails.lift({
    log: {
        level: 'error'
      },
    connections: {
      testDB: {
        adapter: 'sails-memory'
      }
    },
    connection: 'testDB',
  }, function(err, server)
  {
    sails = server;
    if (err) return done(err);
    done(err, sails);
  });
});

after(function(done)
{
  Sails.lower(done);
});

Test

 var request = require('supertest');
 it('should return all users', function(done){
   request(sails.hooks.http.app)
     .get('/user)
     .expect(200)
     .expect('Content-Type', /json/)
     .end(function(err, res){
        // check the response
        done();
     );
 }

I put bootstrap.test.js in the root of my test folder and then use mocha to run the test.

mocha test/bootstrap.test.js test/**/*.test.js

I hope for this help.

+4

, 3.x mocha, nodejs . , :

mocha --globals global test/bootstrap.test.js test/**/*.test.js

mocha.opts:

 #test/mocha.opts
 --globals global
0

All Articles