Skip to content
Advertisement

What is the difference between import and cy.fixture in Cypress tests?

I’m learning cypress and I don’t understand what differs from import file from '../fixtures/filepath/file.json' a fixture file and calling cy.fixture(file), and when should I use each one.

Advertisement

Answer

Basically when you say import file from '../fixtures/filepath/file.json' you can use the imported file in any of methods in the particular javascript file. Whereas if you say cy.fixture(file.json), then the fixture context will remain within that cy.fixture block and you cannot access anywhere/outside of that cy.fixture block. Please go through the below code and you will understand the significance of it.

I recommend to use import file from '../fixtures/filepath/file.json'

For example. Run the below code to understand.

import fixtureFile from './../fixtures/userData.json';
describe('$ suite', () => {
  it('Filedata prints only in cy.fixture block', () => {
    cy.fixture('userData.json').then(fileData => {
      cy.log(JSON.stringify(fileData)); // You can access fileData only in this block.
    })
    cy.log(JSON.stringify(fileData)); //This says error because you are accessing out of cypress fixture context
  })

  it('This will print file data with import', () => {
    cy.log(JSON.stringify(fixtureFile));
  })

  it('This will also print file data with import', () => {
    cy.log(JSON.stringify(fixtureFile));
  })
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement