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.
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.
2 Answers
Reset to default 4Basically 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 remend 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));
})
});
Review the documentation for cy.fixture
- http://on.cypress.io/api/fixture
In short, using cy.fixture
works with the asynchronous nature of Cypress, works with many encoding types and may be aliased for use throughout tests in a spec (https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Aliases)
In addition, fixtures may also be used as responses to cy.route
- https://docs.cypress.io/api/mands/route.html#Fixtures