jin
jin

Reputation: 11

How to implement reusable `describe()` or `it()` in Cypress

I currently wrote a set of specs to test on User Access Matrix (different user types with different Create/Edit/View rights on features).

Currently implemented like this

describe('Test Description', function() {
  before(function() {
    // before test implementation
  });
  beforeEach(function() {
    // beforeEach test implementation
  });
  describe('A', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
  describe('B', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
  describe('C', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
});

I m trying to "group"

it(`should display Hello`, function() {
  // test implementation
});

here to be reusable describe() or it() to current/different spec files instead of having the same code everywhere since I m just logging different types of user in each spec file and these specs will usually have the same describe() or it() blocks.

i tried

describe('Test Description', function() {
  before(function() {
    // before test implementation
  });
  beforeEach(function() {
    // beforeEach test implementation
  });
  describe('A', function() {
    itDisplayHello();
  });
  describe('B', function() {
    itDisplayHello();
  });
  describe('C', function() {
    itDisplayHello();
  });
});

const itDisplayHello = () => {
  it(`should display Hello`, function() {
      // test implementation
  });
};

and I got this error in runtime

The following error originated from your test code, not from Cypress.

  > Cannot access 'itDisplayHello' before initialization

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

Any one with tips or suggestion would be greatly appreciated here, Thanks!

Upvotes: 1

Views: 1718

Answers (1)

Michael Hines
Michael Hines

Reputation: 1108

That's not too hard. Maybe change from arrow function to normal function, because Javascript will "hoist" those (as if you put it at the top of the spec)

Ref Hoisting

function itDisplayHello() {
  it(`should display Hello`, function() {
      // test implementation
  });
}

Or put the arrow version at the top of the spec.

Upvotes: 2

Related Questions