Reuse Data with Cypress Fixtures

Brett Cassette
InstructorBrett Cassette
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

We can reuse our stubbed responses between tests by using Cypress fixtures. In this lesson, learn how to share data between tests.

Instructor: [00:00] Thus far, whenever we've stubbed out a network request, we've written our to-dos in the body of the test and then passed them into cy.route. What if we created another test, as we have in this example, and we want to share the same starting state between the two examples?

[00:17] Let's go ahead and move our data into a fixture file. Let's go ahead and create a new folder under Cypress/fixtures/newfolder/todos/newfile/all.json, and go ahead and paste in your fixture. Make sure to remove the variable assignment since we just need to return the raw data.

[00:40] Now we can reference our fixture by returning to our test and using cy.fixture, and then the path that's relative to the fixtures folder, todos/all.json. Then we can use then, which will asynchronously load our JSON.

[00:59] Since the JSON is going to be loaded asynchronously, we can take the rest of our test and place it inside the callback. Anywhere we had previously used our variable to-dos, we should update it to use the fixture data.

[01:18] We can also share data between our tests without using callbacks at all. It starts with a beforeEach block, which we will run before each of our tests. Next, call cy.fixture, passing in the same path as before. Then we'll add an alias to it, so it can be referenced from other locations in our file. Let's call it todos-preload.

[01:46] Now we can go ahead and remove our fixture, and inside cy.route, we're capable of referencing todos-preload as @todos-preload, because cypress.route is the special method that actually recognizes that.

[02:02] Otherwise, we have to use this.todos-preload, and we get todos-preload attached to this if we use cy.fixture with an alias inside a beforeEach function, but not if we just do it in the body of our test.

[02:17] We can go ahead and save this out. Let's open up Cypress. We'll see that Cypress doesn't actually log out any information about our fixture file, but it had no problem with using it.

[02:31] One gotcha that I do want to make you aware of is that if you're going to reference any of your aliases using this, for instance this.todos-preload, don't use a fat arrow function for your test, because fat arrow functions don't have a this context. This may be assigned in your beforeEach, but it's not going to be available here.

[02:53] If we reopen our test, we'll see that we can read the property todos-preload of undefined. That's because we're not using a standard function. That's because of the fat arrow function.

[03:05] That's how you can use fixtures in your tests.