cy.wrap() - difference between passing a string or object

Viewed 5995

After working with Cypress for a short time i've noticed a strange behavior with cy.wrap(). While wrapping string inside before hook said string is available across all further tests but object would only be available in first test, while yielding undefined in rest of them.

I've tried wrapping tests with context(), which worked, but unnecessarily clogged the cypress test tree UI.

Without context:

describe('Wrap test', function () {
  before(function () {
    console.log('Before');

    cy.wrap('string').as('string');
    cy.wrap({ object: true }).as('object');
  });

  it('Test 1', function () {
    console.log('Test 1');
    console.log(this.string); // 'string'
    console.log(this.object); // { object: true }
  });

  it('Test 2', function () {
    console.log('Test 2');
    console.log(this.string); // 'string'
    console.log(this.object); // undefined
  });
});

With context:

describe('Wrap test', function () {
  before(function () {
    console.log('Before');

    cy.wrap('string').as('string');
    cy.wrap({ object: true }).as('object');
  });

  context('Context', function () {
    it('Test 1', function () {
      console.log('Test 1');
      console.log(this.string); // 'string'
      console.log(this.object); // { object: true }
    });

    it('Test 2', function () {
      console.log('Test 2');
      console.log(this.string); // 'string'
      console.log(this.object); // { object: true }
    });
  })
});

I'd like to mock an object in before hook and afterwards use it in few tests. I thought about converting said object into JSON format, as it would be available for all the tests. Looking forward to hearing opinions from more experienced people about presented scenario.

1 Answers

Turns out that clearing context between tests is actually Cypress' intentional behavior, as described in docs here.

When you wrap your individual test cases in another test suite (describe/context), it won't clear the context (as you're seeing) for that suite if the context was created a level above --- this is intentional, too.

The fact that it only clears primitives, and not objects, is a bug, though, and I've created a bug report for this: mocha context cleared between tests only for primitives.

Related