๐งช Testing JavaScript with Jest
Jest is a modern testing framework by Facebook that's great for testing JavaScript applications. It supports assertions, mocking, snapshot testing, and more.
๐ฆ Step 1: Install Jest
# Initialize project
npm init -y
# Install Jest
npm install --save-dev jest
Add this to your package.json
to run tests using the npm test
command:
"scripts": {
"test": "jest"
}
๐งฎ Step 2: Write a Function to Test
// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
๐งช Step 3: Create a Test File
// math.test.js
const add = require('./math');
test('adds 2 + 3 to equal 5', () => {
expect(add(2, 3)).toBe(5);
});
๐ Step 4: Run the Tests
npm test
Youโll see a green success message if everything is correct โ
๐ Common Matchers
.toBe(value)
โ Exact match.toEqual(object)
โ For objects/arrays.toContain(item)
โ Check if array includes value.toBeTruthy()
,.toBeFalsy()
โ Booleans.toThrow()
โ Expect error to be thrown
๐ง Mocking Example
Simulate a functionโs behavior without calling the real implementation:
const fetchData = jest.fn(() => 'mocked data');
test('fetchData returns mocked data', () => {
expect(fetchData()).toBe('mocked data');
});
โ
Pro Tip: Place tests in a
__tests__
folder or name them *.test.js
for automatic discovery.