Search code examples
javascriptjasminegrunt-contrib-jasmine

before- and afterEach leaking in to other tests


I'm using grunt-contrib-jasmine to test my AMD modules. Out of the box it seems like the tests are affecting eachother.

The output doesn't separate tests by file. This can be verified by logging something in a tests beforeEach. The same callback is executed for all test files, in all tests.

How can I make the tests isolated from eachother i.e. separated by test spec files? Is the only solution to add another level of nesting?

grunt config

options: {
    specs: 'test/specs/unit/**/*spec.js',
    keepRunner: true,
    template: require('grunt-template-jasmine-requirejs'),
    templateOptions: {
        requireConfig: requireConfig
    }
}

sample1.spec.js:

define(['Squire', 'sinon'], function(Squire, sinon){
    'use strict';

    var sut,
        injector,
        fakeServer;

    beforeEach(function(done){
        fakeServer = sinon.fakeServer.create();
        console.log('create fake server'); // this is logged for all test files
        injector = new Squire(); 
        injector.require(['core/http-service'], function(httpService) {
             sut = httpService; 
             done();  
        });  
    }); 

    afterEach(function(){
        fakeServer.restore();
        injector.remove(); 
    }); 

    it('', function(){
        expect(1).toBe(1);
    });
});

Solution

  • The problem is that you have a beforeEach and an afterEach outside of a describe. That means they will be called before and after each and every test that grunt-contrib-jasmine finds.

    If you want them to be used only for the it inside your define-ed module, you need to put them inside a describe:

    define(['Squire', 'sinon'], function(Squire, sinon){
        'use strict';
    
        describe('some description', function(){
    
            var sut,
                injector,
                fakeServer;
    
            beforeEach(function(done){
                fakeServer = sinon.fakeServer.create();
                console.log('create fake server'); // this is logged for all test files
                injector = new Squire(); 
                injector.require(['core/http-service'], function(httpService) {
                     sut = httpService; 
                     done();  
                });  
            }); 
    
            afterEach(function(){
                fakeServer.restore();
                injector.remove(); 
            }); 
    
            it('', function(){
                expect(1).toBe(1);
            });
        });
    });