'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.
Solution 1:[1]
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));
})
});
Solution 2:[2]
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/commands/route.html#Fixtures
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mate Mrše |
Solution 2 | Kevin Old |