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)
CodePudding user response:
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)
...
})
})
CodePudding user response:
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')
})
CodePudding user response:
You can use beforeEach()
to store your access to the fixture so that it is available for all your tests. But you have to take take care of one thing instead of =>
you have to use function () { ... }
callbacks.
describe('Test Suite', () => {
beforeEach(function () {
// "this" points at the test context object
cy.fixture('login_creds.json').then((loginCreds) => {
// "this" is still the test context object
this.loginCreds = loginCreds
})
})
// the test callback is in "function () { ... }" form
it('Some test', function () {
// this.loginCreds exists
cy.get(inputEmail).type(this.loginCreds.email)
})
it('Another test', function () {
// this.loginCreds exists
cy.get(inputEmail2).type(this.loginCreds.email)
})
})
You can read more about it from the fixtures docs.