On the Cypress docs they recommend to use fixtures this way
cy.fixture('logo.png').then((logo) => { // load data from logo.png })
but I found it messy, and limiting because I can't reach this info outside a running test
so I'm using
import cred from "../fixtures/login_creds.json"
Is there a downside to using import? of course I'm using it inside a cy method
cy.get(inputEmail).type(cred.email)
There's nothing wrong with importing a fixture.
It can be useful for data-driven tests.
import sites from '../fixtures/sites.json'
sites.forEach(site => {
it(`test ${site}`, () => {
cy.visit(site)
...
})
})
Pretty much every method of using fixtures is described here Load Fixtures from Cypress Custom Commands, including using import (last example)
/// <reference types="cypress" />
import { users } from '../fixtures/data.json'
// note that Cypress._ is available outside of any test.
// the index k will be from 0 to users.length - 1
const k = Cypress._.random(users.length - 1)
expect(k, 'random user index').to.be.within(0, users.length - 1)
const testUser = users[k]
A lot of them use a "common variable" to store the fixture.
This works without any need to modify the test structure.
// use a common variable to store the random user
let testUser
before(() => {
cy.fixture('data.json').then(({ users }) => {
// the index k will be from 0 to users.length - 1
const k = Cypress._.random(users.length - 1)
expect(k, 'random user index').to.be.within(0, users.length - 1)
testUser = users[k]
// we need to send the entire database object
cy.request('POST', '/reset', {
users: [testUser],
})
})
})
it('sets the random user from the fixture list', () => {
cy.visit('/')
const name = testUser.name
cy.contains('#user', `${name.first} ${name.last}`)
})
it('has the test user', () => {
expect(testUser).to.be.an('object')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With