Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress fixtures best practice

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)
like image 422
NadavT Avatar asked Oct 22 '25 03:10

NadavT


2 Answers

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)
    ...
  })
})
like image 196
SuchAnIgnorantThingToDo-UKR Avatar answered Oct 25 '25 02:10

SuchAnIgnorantThingToDo-UKR


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')
})
like image 21
Fody Avatar answered Oct 25 '25 02:10

Fody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!