How to Write Unit Tests in JavaScript: Simple Guide
To write a unit test in JavaScript, use a testing framework like
Jest. Define test cases with test() or it() functions, and check expected results using expect() assertions.Syntax
A basic unit test in JavaScript with Jest uses the test() function which takes two arguments: a description string and a callback function containing the test code. Inside the callback, use expect() to check if a value matches the expected result.
- test(description, callback): Defines a test case.
- expect(value): Wraps the value to be tested.
- matcher: Methods like
toBe()check if the value meets the condition.
javascript
test('adds 1 + 2 to equal 3', () => { expect(1 + 2).toBe(3); });
Example
This example shows a simple function sum and a unit test that checks if it returns the correct result when adding two numbers.
javascript
function sum(a, b) { return a + b; } test('sum adds two numbers correctly', () => { expect(sum(2, 3)).toBe(5); });
Output
PASS ./sum.test.js
✓ sum adds two numbers correctly (5 ms)
Common Pitfalls
Common mistakes when writing unit tests include:
- Not importing or defining the function to test.
- Forgetting to use
expect()for assertions. - Using asynchronous code without handling promises or callbacks properly.
- Writing tests that depend on external state or side effects.
Always keep tests isolated and simple.
javascript
/* Wrong: Missing expect() */ test('wrong test', () => { sum(1, 2); }); /* Right: Using expect() to check result */ test('correct test', () => { expect(sum(1, 2)).toBe(3); });
Quick Reference
| Function | Purpose |
|---|---|
| test(description, callback) | Defines a unit test case |
| expect(value) | Wraps the value to test |
| toBe(expected) | Checks if value equals expected |
| toEqual(expected) | Checks deep equality for objects/arrays |
| beforeEach(callback) | Runs setup code before each test |
| afterEach(callback) | Runs cleanup code after each test |
Key Takeaways
Use a testing framework like Jest to write unit tests in JavaScript.
Define tests with test() and check results with expect() and matchers.
Keep tests simple, isolated, and focused on one behavior.
Avoid missing assertions or asynchronous handling mistakes.
Use quick reference functions to organize and write effective tests.