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:
- Create JSON File
In your Cypress project, you can create a file named
testData.jsonin thecypress/fixtures/directory. This file may contain the following content:
json[ {"email": "test1@example.com", "password": "password1"}, {"email": "test2@example.com", "password": "password2"} ]
- Write Tests Using This Data
In the test file, you can use the
cy.fixture()method to load this data and use JavaScript'sforEachmethod to iterate through all data sets.
javascriptdescribe('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:
javascriptdescribe('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:
bashCYPRESS_EMAIL=test@example.com CYPRESS_PASSWORD=password1 npx cypress run
Using Environment Variables in Tests:
javascriptit('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 回复