Search
⌘K
    to navigateEnterto select Escto close

    Fixtures in Cypress

    • Cypress provides us with a feature to drive the data from external sources. We can draw a comparison to the Data-Driven Frameworks, which are one of the popular automation testing framework types. Cypress has provided the same functionality in its architecture, where we can read the data from external files known as fixture files.
    • Fixtures are basically files which contains some data that we would like to use in our test.
    • These files could be of any type (i.e .json, .js, .txt, .csv, .jpg, .html and so on). The default location to store these files is in fixtures folder which is already present under cypress.
    • When no extension is passed to cy.fixture(), Cypress will search for files with the specified file name within the fixtures folder and resolve the first one in the following order:
    1fileName.json
    2fileName.js
    3fileName.txt
    4fileName.csv
    5fileName.png
    6fileName.jpg
    7fileName.jpeg
    
    • So, whenever we want to store an object in fixtures and use it in our test cases, we can create a json file.

    For example, consider a json file under cypress folder which holds credentials for login into the application.

    1// credentials/admin.json
    2
    3{
    4  email: "admin@example.com",
    5  password: "admin123"
    6}

    This is how we will use the fixture file in our test:

    1describe("Login", () => {
    2  it("should be able to login", () => {
    3    cy.visit("/");
    4    cy.fixture("credentials/admin").then((user) => {
    5      cy.get("[data-cy='login-email-field']").type(user.email);
    6      cy.get("[data-cy='login-password-field']").type(user.password);
    7    });
    8    cy.get("[data-cy='submit-button']").click();
    9  });
    10})
    • This approach is fine when we want to use data from fixture file at a single place.
    • But if we want to use file data multiple times, then the better approach would be to initialize the variable to use fixture:
    1describe("Admin login", () => {
    2  let userDetails;
    3
    4  beforeEach(() => {
    5    cy.fixture("credentials/admin").then((user) => {
    6      userDetails = user;
    7    });
    8  });
    9
    10  it("should be able to login", () => {
    11    cy.get("[data-cy='login-email-field']").type(userDetails.email);
    12    cy.get("[data-cy='login-password-field']").type(userDetails.password);
    13    cy.get("[data-cy='submit-button']").click();
    14  });
    15});

    So now if we want to use fixture data in multiple tests, we can simply do that by using the variable declared at the top.

    Previous
    Next