Unit and integration testing guide
Page summary:
Testing relies on Jest and Supertest with an in-memory SQLite database, a patched Strapi test harness that also supports TypeScript configuration files, and helpers that automatically register the
/helloroute and authenticated role during setup.
The present guide provides a hands-on approach to configuring Jest in a Strapi 5 application, mocking the Strapi object for unit testing plugin code, and using Supertest to test REST endpoints end to end.
The guide aims to recreate the minimal test suite available in the strapi-unit-testing-examples CodeSandbox link.
The present guide will not work if you are on Windows using the SQLite database due to how Windows locks the SQLite file.
Install tools
We'll first install test tools, add a command to run our tests, and configure Jest.
-
Install Jest and Supertest by running the following command in a terminal:
- Yarn
- NPM
yarn add jest supertest --devnpm install jest supertest --save-devJestprovides the test runner and assertion utilities.Supertestallows you to test all theapiroutes as they were instances of http.Server.
-
Update the
package.jsonfile of your Strapi project with the following:-
Add a
testcommand to thescriptssection so it looks as follows:"scripts": {
"build": "strapi build",
"console": "strapi console",
"deploy": "strapi deploy",
"dev": "strapi develop",
"develop": "strapi develop",
"seed:example": "node ./scripts/seed.js",
"start": "strapi start",
"strapi": "strapi",
"upgrade": "npx @strapi/upgrade latest",
"upgrade:dry": "npx @strapi/upgrade latest --dry",
"test": "jest --forceExit --detectOpenHandles"
}, -
Configure Jest at the bottom of the file to ignore Strapi build artifacts and to map any root-level modules you import from tests:
"jest": {
"testPathIgnorePatterns": [
"/node_modules/",
".tmp",
".cache"
],
"testEnvironment": "node",
"moduleNameMapper": {
"^/create-service$": "<rootDir>/create-service"
}
}
-
Mock Strapi for plugin unit tests
Pure unit tests are ideal for Strapi plugins because they let you validate controller and service logic without starting a Strapi server. Use Jest's mocking utilities to recreate just the parts of the Strapi object and any request context that your code relies on.