Unit testing
The Strapi blog has a tutorial on how to implement API testing with Jest and Supertest and how to add unit tests to your Strapi plugin.
In this guide we will see how you can run basic unit tests for a Strapi application using a testing framework.
In this example we will use Jest Testing Framework with a focus on simplicity and Supertest Super-agent driven library for testing node.js HTTP servers using a fluent API.
Please note that this guide will not work if you are on Windows using the SQLite database due to how windows locks the SQLite file.
Install test toolsβ
Jest
contains a set of guidelines or rules used for creating and designing test cases - a combination of practices and tools that are designed to help testers test more efficiently.
Supertest
allows you to test all the api
routes as they were instances of http.Server.
sqlite3
is used to create an on-disk database that is created and deleted between tests.
- yarn
- npm
yarn add --dev jest supertest sqlite3
npm install jest supertest sqlite3 --save-dev
Once this is done add this to package.json
file
add test
command to scripts
section
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi",
"test": "jest --forceExit --detectOpenHandles"
},
and add those lines at the bottom of file
"jest": {
"testPathIgnorePatterns": [
"/node_modules/",
".tmp",
".cache"
],
"testEnvironment": "node"
}
Those will inform Jest
not to look for test inside the folder where it shouldn't.
Set up a testing environmentβ
Test framework must have a clean empty environment to perform valid test and also not to interfere with current database.
Once jest
is running it uses the test
environment (switching NODE_ENV
to test
)
so we need to create a special environment setting for this purpose.
Create a new config for test env ./config/env/test/database.js
and add the following value "filename": ".tmp/test.db"