DEV Community

Cover image for How to use fixtures with Cypress to isolate the frontend tests
Walmyr
Walmyr

Posted on • Edited on

How to use fixtures with Cypress to isolate the frontend tests

Today in the “Pinches of Cypress” series, learn how to use fixtures in automated frontend tests

Today's post is based on yesterday's content example (in which you learned how to intercept requests), with a brief change.

That's right, let's go straight to a practical example.

The example application is the same. That is, it allows the creation, reading, updating, and deletion of notes.

After logging into the application, the user is directed to their personal list of notes.

The scenario, however, will be a little different. This time, I want to simulate that when the user already has a certain number of notes, they are rendered in the list.

The test code would look like this.

// cypress/integration/listOfNotes.spec.js

describe('Notes list', () => {
  beforeEach(() => {
    cy.intercept('GET', '**/notes', { fixture: 'notes' })
      .as('getNotes')
    cy.login()
    cy.wait('@getNotes')
  })

  it('renders 6 ".list-group-item"s, being the first one a button to create a new note', () => {
    cy.get('.list-group-item')
      .should('have.length', 6)
      .first()
      .should('contain', 'Create new note')
  })
})
Enter fullscreen mode Exit fullscreen mode

And in the cypress/fixtures/ directory, there would be a file called notes.json, which would contain the following content.

[
  { "content": "Sample content 1"},
  { "content": "Sample content 2"},
  { "content": "Sample content 3"},
  { "content": "Sample content 4"},
  { "content": "Sample content 5"}
]
Enter fullscreen mode Exit fullscreen mode

Note: It is worth remembering that this is the data structure that such a frontend application would normally receive from the backend via API.

That's it.

The test now intercepts a GET request to the '**/notes' route, and the frontend then renders the contents of the cypress/fixtures/notes.json file.

Since in this file we have 5 notes, our assertions (that 6 'list-group-item's are rendered, and that the first item in the list is the button for creating a new note) pass.

See a screenshot of the test run.

Alt Text


Are you enjoying the series?

I'm looking forward to hearing your feedback!


This post was originally published in Portuguese on the Talking About Testing blog.


Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Top comments (0)