Module 4 Project - Introduction to Testing
Project Overview
In this project, you will learn the fundamentals of testing React applications. You will write unit tests, integration tests, and learn how to test React components effectively.
Project Requirements
Testing Requirements
- Write unit tests for React components
- Test component rendering
- Test user interactions with components
- Test asynchronous operations
- Achieve at least 80% test coverage
Component Requirements
- Create testable React components
- Implement proper component separation
- Use props and state effectively
- Handle user events properly
Code Quality Requirements
- Write clean and maintainable tests
- Follow testing best practices
- Use mocking and stubbing where appropriate
- Document your testing approach
Project Setup
# Create a new React project
npx create-react-app testing-project
# Install testing dependencies
cd testing-project
npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event
# Start the development server
npm start
# Run tests
npm test
Project Structure
src/
├── components/
│ ├── Counter/
│ │ ├── Counter.js
│ │ └── Counter.test.js
│ ├── Form/
│ │ ├── Form.js
│ │ └── Form.test.js
│ └── TodoList/
│ ├── TodoList.js
│ └── TodoList.test.js
├── hooks/
│ ├── useFetch.js
│ └── useFetch.test.js
├── utils/
│ ├── api.js
│ └── api.test.js
└── App.js
Example Test Implementation
// Counter.js
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
// Counter.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('renders counter with initial value of 0', () => {
render(<Counter />);
const counterElement = screen.getByText(/Counter: 0/i);
expect(counterElement).toBeInTheDocument();
});
test('increments counter when increment button is clicked', () => {
render(<Counter />);
const incrementButton = screen.getByText(/increment/i);
fireEvent.click(incrementButton);
const counterElement = screen.getByText(/Counter: 1/i);
expect(counterElement).toBeInTheDocument();
});
test('decrements counter when decrement button is clicked', () => {
render(<Counter />);
const decrementButton = screen.getByText(/decrement/i);
fireEvent.click(decrementButton);
const counterElement = screen.getByText(/Counter: -1/i);
expect(counterElement).toBeInTheDocument();
});
Additional Resources
Submission Guidelines
Complete and submit your project according to the following guidelines:
- Submit your code to GitHub
- Include a README.md with setup instructions
- Document your testing strategy
- Include screenshots of test coverage reports