Fixtures and Integration
Learn the purpose of the fixture and integration folders, and how they can help us write more stable and organized tests.
When creating a test suite for a web application, we have to consider network connection fails. Any function that relies on fetching data from a server or requires sending data to the server has side effects. And side effects can easily break tests.
Our network request can come back either successfully or with a failure, or anything in between. There are just too many status codes to keep in mind. To work around this, Cypress introduces a folder called “fixtures”.
What are fixtures?
Fixtures are pieces of static data that can be used inside our test cases whenever we need to stub a network request.
This way, we can eliminate any side effects, and ensure that our test cases are deterministic. We can also use them to match our data against a fixed set without cluttering the actual test cases.
Configuring fixtures
Let’s take the example of a user login. We have a test user behind the login screen for testing the whole application. We want to login in first, but we also want to ensure that the server always responds with a 200 status code. Take the successful response we get, and create a new file inside our “fixtures” folder called login.json
:
{
"userId": 1,
"token": "qrViFRJuHepMpvneaKJvdyGfsdmBW6"
}
We can configure fixtures this way:
- Take the successful (or unsuccessful in case we want to test a failure path) response from the server.
- Create a new json file with the response under the “fixtures” folder.
In case we don’t want to use the default “fixtures” folder, we also have the option to configure the location of fixtures inside cypress.json
:
{
// Customize the folder location with the `fixturesFolder` flag
"fixturesFolder": "cypress/fixtures"
}
Using fixtures
In order to use these static data inside our test cases, we use the cy.fixture
command like so:
cy.fixture(filePath); // Load the static data from the location
cy.fixture('login'); // Loads data from "fixtures/login.json"
Note that we can omit both the fixtures folder and the json extension as well.
This will return the contents of the file:
Get hands-on with 1200+ tech skills courses.