最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the difference between import and cy.fixture in Cypress tests? - Stack Overflow

programmeradmin5浏览0评论

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.

Share Improve this question edited May 8, 2022 at 22:33 bad_coder 13k20 gold badges56 silver badges88 bronze badges asked Jun 30, 2020 at 17:31 nicolasLimanicolasLima 551 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 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

发布评论

评论列表(0)

  1. 暂无评论