Andurit
Andurit

Reputation: 5762

Protractor - Run code before each test and after each test

I need to run some code before every single test. This could be a easy solution if I would have a single spec file e.g. main.e2e.ts but making one spec file for huge applications sounds too dirty.

I separated my tests to multiple spec files (e.g. login.e2e.ts & dashboard.e2e.ts) but I want to run some code before each and after each it no matter of spec file.

I found out that it is possible with beforeEach(() => {} and afterEach(() => {} and I'm doing it right now in every single file. But I believe there have to be some prettier solution for this approach.

Is there a way to run code before and after each it while using multiple spec files?

Upvotes: 2

Views: 3911

Answers (1)

craig
craig

Reputation: 5016

If you have common and shared before and after methods, you could write it to a common file. Then import those functions to the spec file and call them in your beforeEach, beforeAll, afterEach, and afterAll. I wrote the following in TypeScript.

common.ts

// import some protractor global objects
import { browser } from 'protractor';

export let beforeMethod = () => {
  // do some method
  browser.get('/');
}

export let beforeAsyncMethod = (done) => {
  // do something that is async
  done();
}

export let afterMethod = () => {
  // do some method
}

login.e2e-spec.ts

import { beforeMethod, beforeAsyncMethod, afterMethod } from './common';

describe('login', () => {
  // do some setup
  beforeEach( beforeMethod );
  beforeEach( beforeAsyncMethod );

  it('should do your test', () => {
    // your amazing test.
  });

  afterEach( afterMethod );
});

Upvotes: 2

Related Questions