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

How to run a test multiple times with different sets of data in cypress?

1个答案

1

When using Cypress for end-to-end testing, you often encounter scenarios where you need to run the same test script against different data sets. In such cases, you can leverage Cypress's features to implement parameterized testing, which involves executing the same test multiple times with different data sets. Below, I will detail how to achieve this.

Using Static Data

Example Steps:

  1. Create JSON File In your Cypress project, you can create a file named testData.json in the cypress/fixtures/ directory. This file may contain the following content:
json
[ {"email": "test1@example.com", "password": "password1"}, {"email": "test2@example.com", "password": "password2"} ]
  1. Write Tests Using This Data In the test file, you can use the cy.fixture() method to load this data and use JavaScript's forEach method to iterate through all data sets.
javascript
describe('Login Functionality Test', () => { beforeEach(() => { cy.visit('/login'); }); cy.fixture('testData').then((users) => { users.forEach((user) => { it(`Using email ${user.email} to log in`, () => { cy.get('[data-cy=email]').type(user.email); cy.get('[data-cy=password]').type(user.password); cy.get('[data-cy=submit]').click(); cy.contains('Login successful'); }); }); }); });

Using Dynamically Generated Data

Example Code:

javascript
describe('Login Test with Dynamically Generated Data', () => { beforeEach(() => { cy.visit('/login'); }); const users = Array.from({ length: 5 }, (v, k) => { return { email: `user${k + 1}@example.com`, password: `password${k + 1}` }; }); users.forEach((user) => { it(`Using email ${user.email} to log in`, () => { cy.get('[data-cy=email]').type(user.email); cy.get('[data-cy=password]').type(user.password); cy.get('[data-cy=submit]').click(); cy.contains('Login successful'); }); }); });

In this example, we generate 5 user data sets, each with unique email and password values, and then execute the login test.

Using Environment Variables

Command Line Example:

bash
CYPRESS_EMAIL=test@example.com CYPRESS_PASSWORD=password1 npx cypress run

Using Environment Variables in Tests:

javascript
it('Login using environment variables', () => { cy.visit('/login'); cy.get('[data-cy=email]').type(Cypress.env('EMAIL')); cy.get('[data-cy=password]').type(Cypress.env('PASSWORD')); cy.get('[data-cy=submit]').click(); cy.contains('Login successful'); });

Using these methods, you can flexibly control test data and easily adjust and execute various test scenarios as needed.

2024年6月29日 12:07 回复

你的答案