beforeEach Scope in Jasmine Unit Tests

Last modified: 
Tuesday, March 7th, 2017

Understanding the scope of beforeEach() in Jasmine describe() blocks.

describe('Testing the scope of beforeEach()', function() {
  var myGlobalVar,
      couldBeTrouble = false;

  beforeEach(function() {
    myGlobalVar = {
      a: 'Alpha',
      b: 'Beta',
      g: 'Gamma'
    };
  });

  it('maps the g key to the word Gamma', function() {
    expect(myGlobalVar.g).toEqual('Gamma');
  });

  describe('overwriting g in beforeEach', function() {
    beforeEach(function() {
      myGlobalVar.g = 'Not Gamma!';
      myGlobalVar.d = 'Delta';
      couldBeTrouble = true;
    });

    it('now maps the g key to the prhase \'Not Gamma!\'', function() {
      expect(myGlobalVar.g).toEqual('Not Gamma!');
    });
  });

  describe('using a another describe block', function() {
    it('once more maps the g key back to the word Gamma', function() {
      expect(myGlobalVar.g).toEqual('Gamma');
      expect(myGlobalVar.d).not.toBeDefined();
    });
  });

  it('set the value of couldBeTrouble earliers, but we didn\'t clean it up', function() {
    expect(couldBeTrouble).toBe(true);
  });
});


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.