In the previous post here we saw how to read external files in Cypress using cy.readFile. Cypress also provides another way to read files. In this post, I will show how to Fixtures to do data driven testing in Cypress.
According to documentation, syntax is as below.
1 2 3 4
Comparison with cy.readFile
Main difference between cy.readFile and cy.Fixture is that former one starts looking for the files from project root folder and later looks for files under Fixture folder. cy.Fixture supports a wide range of file types/extensions like json, txt, html,jpeg,gif,png etc. If file name is not specified it looks for all supported filetypes in specific order starting with JSON. We can even assign alias to this , which will help to reuse this later on.
To demonstrate this, let’s revisit old example of logging into SauceDemo website. This time, instead of using hardcoded values in feature file, I will move credentials into a separate JSON file and keep it inside Fixtures\TestDataFiles folder . File should look like below. This has two set of login credentials.
1 2 3 4 5 6 7 8 9 10 11 12 13
Create a new scenario to login to ECommerce site by using Fixtures. In below scenario we just specify type of User which we need to use for this scenario. I am specifying a user type here since there are different types of users and we can have different scenarios for them.
1 2 3 4 5
Step definition file for this will look like below. In Step definition files, below steps are performed.
- Reading test data file by using cy.fixture() by passing relative path from Fixture folder and then alias it into a variable loginCredentials. The hierarchy is separated by forward slashes.
- Get the JSON object ( which is an array of objects) from above step and identify the specific object which we need to use for this step based on the UserType specified in feature file. This is achieved by using filter method. This is mostly like LINQ in C# . More details can be found here . This filter will return an array of object which satisfy filter criteria specified. In this case, there will be only one object in array.
- Login to the demo website by using first user in the above array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
Now it is time to run above scenario. Open Cypress by running command npx cypress open
Run the scenario on cypress UI and result will look like below. We can clearly see that assertions are passed.