Jest is a JavaScript testing framework that is primarily used with React Testing Library for unit testing and Snapshot testing.
To use Jest in Modern.js, you need to install the dependencies first. You can run the following commands:
Next, you can run the following commands to automatically initialize Jest in your project and generate a basic jest.config.[jt]s
configuration:
This section will use .ts
files for Jest testing.
Compared to other testing frameworks, Jest requires more configuration at the build level, such as handling JSX and ESM syntax. Therefore, you need to install some additional dependencies:
You need to further configure the jest.config.ts
file to allow Jest to correctly compile and run test cases. Here is a basic configuration:
In the configuration, the transformIgnorePatterns
is set to an empty array, meaning that all files will be compiled. If you want to speed up the test run, you can configure it as needed.
The setupFilesAfterEnv
will be executed at startup. In jest.setup.ts
, you can import @testing-library/jest-dom
, which includes a set of convenient custom matchers, such as .toBeInTheDocument()
, to make writing tests easier:
You need to configure Babel to allow Jest to automatically compile JSX and other syntax. Here is a basic configuration:
Now, you can start writing tests. First, add a test
command in package.json
:
Create a simple page for testing:
Add a test case to check if the page has the expected text:
In the above test case, we imported the <Router>
component from @modern-js/runtime/router
because React Router requires the corresponding context when rendering some route-related components.
When running directly in the Modern.js application, the <Router>
component will be automatically injected.
Execute the above test
command to run the test cases: