Skip to content

Making Server side Tests

ADSKLowenthal edited this page Nov 24, 2015 · 11 revisions

Server Side Tests

Unit Tests

Mocking

Sinon

http://sinonjs.org/

Mocking Modules

Using Proxyquire allows you to mock just part of a module. Anything unmocked will behave as normal. However, it only works if you're directly require the file you want to mock for.

Testing with a request through SuperTest, it may not be possible to mock because it's communicating with a different instance of the code.

Mocking Models

An implementation of this has not been used with MEAN yet, so this is theoretical still. Please share any experiences.

Mongoose-Mock https://www.npmjs.com/package/mongoose-mock

This should make it possible to mock mongoose models.

Currently, testing for MEAN requires running an instance of the server. This is because the models are not mocked and require a live connection to a database to run. Transitioning to mocking can making running tests easier, and possibly improve quality of the tests.

Integration Tests

Routes and Controllers

To test routes and controllers together it's necessary to issue requests and read the responses.

Currently using SuperTest, some examples will follow soon.

Database

If your tests interact with the database, it may be necessary to return your collections to a zero state.

This can remove all entries from an existing collection:

describe('tests', function(){
    beforeEach(function(){
        return Model.remove({}).exec();
    });
});

But be careful, if you've made changes to the schema (specifically to indexes), then that will not recreate indexes. So in most cases it will be better to drop the collection first:

describe('tests', function(){
    before(function(done){
        Model.collection
            .drop(function (err) {
                //'ns not found' means the collection wasn't there to drop, same result
                if (err && err.message !== 'ns not found') {
                    done(err);
                }
                done();
            });
    });

    beforeEach(function(){
        return Model.remove({}).exec();
    });
});
Clone this wiki locally