How do you write unit tests for JavaScript code?
TL;DR
To write unit tests for JavaScript code, you typically use a testing framework like Jest or Mocha. First, you set up your testing environment by installing the necessary libraries. Then, you write test cases using functions like describe
, it
, or test
to define your tests. Each test case should focus on a small, isolated piece of functionality. You use assertions to check if the output of your code matches the expected result.
Example using Jest:
Setting up the testing environment
Installing Jest
To get started with Jest, you need to install it via npm:
Configuring Jest
Add a script to your package.json
to run Jest:
Writing test cases
Basic structure
A test file typically contains one or more describe
blocks, which group related tests, and it
or test
blocks, which define individual test cases.
Example:
Using assertions
Assertions are used to check if the output of your code matches the expected result. Jest provides various assertion methods like toBe
, toEqual
, toBeNull
, etc.
Example:
Mocking dependencies
Sometimes, you need to mock dependencies to isolate the unit of code you are testing. Jest provides functions like jest.fn()
and jest.mock()
for this purpose.
Example:
Running the tests
To run your tests, use the following command: