Tell about your experience with testing in projects.
sobes.tech AI
Answer from AI
In projects, I have used several types of testing to ensure frontend quality:
-
Unit testing: Using Jest and React Testing Library to isolate and verify individual components, functions, and modules. This helps quickly identify logical errors in small, independent parts of the code.
// Example of a unit test for a Button component with Jest and React Testing Library import { render, screen } from '@testing-library/react'; import Button from './Button'; test('renders button with correct text', () => { render(<Button>Click Me</Button>); const buttonElement = screen.getByText(/Click Me/i); expect(buttonElement).toBeInTheDocument(); }); -
Integration testing: To verify interaction between multiple components or modules. This helps ensure that different parts of the system work correctly together. I also used React Testing Library for this.
// Example of an integration test for a form and submit button import { render, screen, fireEvent } from '@testing-library/react'; import Form from './Form'; test('submitting form calls onSubmit with correct data', () => { const mockSubmit = jest.fn(); render(<Form onSubmit={mockSubmit} />); const input = screen.getByLabelText(/Username:/i); const submitButton = screen.getByRole('button', { name: /Submit/i }); fireEvent.change(input, { target: { value: 'testuser' } }); fireEvent.click(submitButton); expect(mockSubmit).toHaveBeenCalledWith({ username: 'testuser' }); }); -
E2E testing: In some projects, I used Cypress or Playwright for end-to-end testing of user scenarios in a real browser. This helps verify that the application as a whole works as expected for the end user.
// Example of an E2E test in Cypress // cypress/integration/todo.spec.js describe('Todo App', () => { it('should add a new todo item', () => { cy.visit('/'); // Navigate to the application page cy.get('.new-todo').type('Buy milk{enter}'); // Enter text and press Enter cy.get('.todo-list li') .should('have.length', 1) // Check the number of items .first() .should('have.text', 'Buy milk'); // Check the text of the first item }); }); -
Snapshot testing: Using Jest to capture the component's structure and detect unintentional changes in the markup (e.g., after refactoring).
// Example of a snapshot test for a Card component with Jest import renderer from 'react-test-renderer'; import Card from './Card'; test('Card renders correctly', () => { const tree = renderer .create(<Card title="Test Title">Test Content</Card>) .toJSON(); expect(tree).toMatchSnapshot(); // Compare with the saved snapshot });
I believe testing is an important part of the development process, as it helps maintain code quality, facilitates refactoring, and reduces the likelihood of errors in production. I practice writing tests alongside new functionality or before fixing bugs (TDD approach, where applicable).