Loopback testing with supertest, mocha and models

user465342 picture user465342 · Jan 26, 2016 · Viewed 7.6k times · Source

On the Google groups post on deprecating loopback-testing there is a question that asks about providing a proper example of how testing can be achieved without loopback-testing. That thread talks about using supertest instead.

Below is an attempt that I made to combine Mocha, supertest along with models (from app.js). The result works really well when I run the file by itself. But if I had another test file (say test-teacher.js) then the first test file (call it test-student.js) starts to fail in weird ways I can't describe.

Am I missing something or can models not be used like I am using them below?

describe('/Student', function () {

    var server = require('../server/server')
    var loopback = require('loopback')
    var supertest = require('supertest')
    var request = require('supertest')(server)

    var dataSource = server.dataSource('db', {adapter: 'memory'})

    var Student = dataSource.define('Student', {
        'id': Number,
        'points': Number
    });

    beforeEach(function () {
        Student.updateOrCreate({id: 1, points: 5000});
    })


    it('Post a new student', function (done) {
        request.post('/api/Students').send({points: 5000}).expect(200, done)

    })


})

Answer

user465342 picture user465342 · Feb 7, 2016

Based on feedback from jakerella on the previous answer, I changed the code above so that I don't have to redefine the models from scratch in the code (thanks jakerella!)

With the code below, I am able to run all the tests from multiple different models as a single suite using npm test without any failures.

Since I am interested in only individual orders ... listen and close were not necessary. I suspect that if I was testing overall instances of models that were created it would become required.

describe('/Student', function () {

    var server = require('../server/server')
    var request = require('supertest')(server)
    var expect = require('expect.js')

    var Student 

    before(function() {
        Student = server.models.Student    
    })

    beforeEach(function (done) {
        Student.upsert({id: 1, points: 5000}, function() { done() })
    })    

    it('Post a new student', function (done) {
        request.post('/api/Students').send({points: 5000}).expect(200, done)
     })
})