乐闻世界logo
搜索文章和话题

How to read JSON file from cypress project?

1个答案

1

In Cypress, reading JSON files is a straightforward process, typically used for configuration data or static test data. Below are the detailed steps along with a practical example:

Steps

  1. Place the JSON file in the appropriate directory:
    Typically, JSON files should be placed in the cypress/fixtures directory. This is Cypress's default location for storing test data files.

  2. Use the cy.fixture() method to read JSON files:
    Cypress provides the cy.fixture() method specifically for loading files located in the fixtures directory.

  3. Use this data within your tests:
    The JSON data read can be used anywhere in the test script, such as as input data for the test.

Example

Suppose we have a file named userData.json located in the cypress/fixtures directory, with the following content:

json
{ "username": "testuser", "password": "testpassword" }

We can read and use this file in a Cypress test like this:

javascript
describe('Login Test', () => { it('should login using credentials from JSON file', () => { // Read the JSON file cy.fixture('userData').then((user) => { // user now contains the content of userData.json cy.visit('/login') // Visit the login page // Use the data from userData.json to fill the login form cy.get('#username').type(user.username) cy.get('#password').type(user.password) cy.get('#login-button').click() // Verify successful login cy.url().should('include', '/dashboard') }) }) })

This test script first reads the data from userData.json, then uses it to fill the login form and submit. Finally, it verifies a successful navigation to the dashboard page.

Through this approach, we can separate test data from test scripts, making maintenance and management more convenient, and tests more flexible and configurable.

2024年6月29日 12:07 回复

你的答案