...
Describe Blocks: Group related tests.
It Blocks: Define individual test cases.
Assertions: Validate expected outcomes.
For example,
Code Block | ||
---|---|---|
| ||
describe('My React App', () => {
it('should display the correct title', () => {
cy.visit('/');
cy.title().should('include', 'React App');
});
}); |
Selectors and Best Practices
Use Data Attributes: Prefer data attributes (
data-cy
) for selecting elements.Avoid Complex Selectors: Use simple selectors to avoid brittle tests.
Custom Cypress Commands
Use the cypress/support/< e2e/component >.js
file to write custom commands for either e2e or component testing.
For example to avoid writing repetitive code to assert an element by id use the custom created command cy.assertByTestId
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
Debugging and Troubleshooting
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.