A practice application designed to help you learn and master unit testing using Jest. This project provides sample functions and clear instructions to get you started with Test-Driven Development (TDD).
This repository contains a complete learning environment for practicing Jest unit testing. It includes:
- Sample functions to test in
dataProcessor.js - Visual instruction guide in
index.html - Step-by-step setup process
- Best practices and tips
Follow these steps to set up your Jest testing environment:
npm init -yThis creates a package.json file with default configuration.
npm install --save-dev jestmkdir __tests__Jest automatically looks for test files in the __tests__ directory.
Create test files like __tests__/dataProcessor.test.js to test the functions in dataProcessor.js.
Add the test script to your package.json:
{
"scripts": {
"test": "jest"
}
}npm testunit-testing-demo/
├── README.md (this file)
├── index.html (visual instruction guide)
├── style.css (styling for instruction page)
├── dataProcessor.js (functions to test)
├── package.json (created after npm init)
└── __tests__/ (your test files go here)
└── dataProcessor.test.js
The dataProcessor.js file contains two functions to test:
- Purpose: Counts the number of words in a given text string
- Test scenarios: Normal text, empty strings, strings with extra spaces, null/undefined inputs
- Example:
countWords("hello world")returns2
- Purpose: Finds the maximum number in an array of numbers
- Test scenarios: Arrays with positive numbers, negative numbers, mixed arrays, single element arrays
- Example:
findMax([1, 5, 3, 9, 2])returns9
- Use
describe()blocks to group related tests - Write descriptive test names that explain what is being tested
- Follow the AAA pattern: Arrange, Act, Assert
- Happy Path: Test with valid, expected inputs
- Edge Cases: Test with boundary values (empty arrays, zero, etc.)
- Error Cases: Test invalid inputs and error handling
- Null/Undefined: Test with null and undefined values
Common Jest matchers you'll use:
toBe()- Exact equalitytoEqual()- Deep equalitytoThrow()- Function throws an errortoBeTruthy()/toBeFalsy()- Boolean testingtoBeNull()/toBeUndefined()- Null/undefined testing
describe('FunctionName', () => {
test('should handle normal case', () => {
// Test implementation
});
test('should handle edge case', () => {
// Test implementation
});
test('should throw error for invalid input', () => {
// Test implementation
});
});Need help? Open index.html in your browser for a visual guide, or refer to the Jest documentation for more advanced features.