Skip to content
This repository

beforeEach

A suite can have a beforeEach() declaration. It takes a function that is run before each spec. For example:

describe('some suite', function () {
  var suiteWideFoo;

  beforeEach(function () {
    suiteWideFoo = 1;
  });

  it('should equal bar', function () {
    expect(suiteWideFoo).toEqual(1);
  });
});

A runner can also have beforeEach() declarations. Runner beforeEach() functions are executed before every spec in all suites, and execute BEFORE suite beforeEach() functions. For example:

var runnerWideFoo = [];

beforeEach(function () {
  runnerWideFoo.push('runner');
});

describe('some suite', function () {
  beforeEach(function () {
    runnerWideFoo.push('suite');
  });

  it('should equal bar', function () {
    expect(runnerWideFoo).toEqual(['runner', 'suite']);
  });
});

afterEach

Similarly, there is an afterEach() declaration. It takes a function that is run after each spec. For example:

describe('some suite', function () {
  var suiteWideFoo = 1;
  afterEach(function () {
    suiteWideFoo = 0;
  });

  it('should equal 1', function () {
    expect(suiteWideFoo).toEqual(1);
  });

  it('should equal 0 after', function () {
    expect(suiteWideFoo).toEqual(0);
  });
});

A runner can also have an afterEach() declarations. Runner afterEach() functions are executed after every spec in all suites, and execute AFTER suite afterEach() functions. For example:

var runnerWideFoo = [];

afterEach(function () {
  runnerWideFoo.push('runner');
});

describe('some suite', function () {
  afterEach(function () {
    runnerWideFoo.push('suite');
  });

  it('should be empty', function () {
    expect(runnerWideFoo).toEqual([]);
  });

  it('should be populated after', function () {
    expect(runnerWideFoo).toEqual(['suite', 'runner']);
  });
});

Single-spec After functions

A spec may ask Jasmine to execute some code after the spec has finished running; the code will run whether the spec finishes successfully or not. Multiple after functions may be given.

describe('single-spec after functionality', function () {
  var myPage = {
    title: "old title"
  };
  it('should change the title back and forth', function () {    
    var originalTitle = myPage.title;
    this.after(function() { myPage.title = originalTitle; });
    myPage.title = "new title";
    expect(myPage.title).toEqual("new title");  
  });
  it('should be the original title after running after', function() {    
    expect(myPage.title).toEqual("old title");
  });
Something went wrong with that request. Please try again.