...
Code Block | ||
---|---|---|
| ||
// code for adding a custom Cypress command // @Params: [test-id]: string // usecase: cy.assertByTestId("<test-id>"); // result: gives assertion for element existance Cypress.Commands.add('assertByTestId', (testId) => { cy.get(`[data-cy=${testId}]`).should('exist'); }); |
Running Tests
Open tests in GUI by using the command
Code Block language bash npx cypress open --config-file={env}.config.js
To open tests in headless mode (run in terminal without the GUI) run the following command
Code Block language bash npx cypress run --config-file dev.config.js // runs e2e tests npx cypress run --component --config-file=dev.config.js // runs component tests
Debugging and Troubleshooting
Use
cy.debug()
: To pause and inspect the state.View Cypress Logs: Check the logs in the Cypress Test Runner for errors and issues.
Check Network Requests: Use Cypress commands like
cy.intercept()
to monitor network requests.
Code Block |
---|
cy.intercept('GET', '/api/data', { fixture: 'data.json' }).as('getData'); |
Best Practices
Keep Tests Independent: Ensure each test runs in isolation.
Use Fixtures for Test Data: Load static data from files. Avoid making API calls from tests, as this will additional load on the servers. Use
cy.intercept
to intercept any type of HTTP call and send back dummy data.Clean Up: Use hooks like
beforeEach
andafterEach
to set up and tear down test states.Write Descriptive Tests: Use clear and descriptive names for test cases and assertions. Begin all test descriptions with
should
.Custom Commands: For repeated DOM queries, use aliases to make tests more readable.
BeforeEach: Use before each for all the repetitive commands within a describe block that is common to all the it blocks
Only assertions in It Blocks: Goal is to keep the It blocks as lean as possible, hence, avoid writing anything other than state management blocks and assertions in the It Blocks. Use the describe block to write all the component mounting and data initialization logic.
...