Unit Testing with Jest for Strapi v4

System Information
  • Strapi Version: 4.0.6
  • Operating System: macOS
  • Database: SQLite
  • Node Version: v14
  • Yarn Version: 1.22

I am trying to perform unit tests with Jest for the new version of Strapi, v4 which was just released a couple of weeks ago. In accordance with their documentation, the old guide for unit testing no longer runs as expected. I have, however, modified the code to work to a certain extent. Currently I have the following:


const Strapi = require("@strapi/strapi");

let instance;

async function setupStrapi() {
  if (!instance) {
    /** the following code in copied from `./node_modules/strapi/lib/Strapi.js` */
    await Strapi().load();
    instance = strapi; // strapi is global now
    await instance.server
      .use(instance.server.router.routes()) // populate KOA routes
      .use(instance.server.router.allowedMethods()); // populate KOA methods

    await instance.server.mount();
  return instance;

module.exports = {


const fs = require("fs");
const { setupStrapi } = require("./helpers/strapi");

beforeAll(async () => {
  await setupStrapi();

afterAll(async () => {
  const dbSettings = strapi.config.get("database.connection.connection");

  //close server to release the db-file
  await strapi.server.destroy();


  //delete test database after all tests
  if (dbSettings && dbSettings.filename) {
    const tmpDbFile = `${dbSettings.filename}`;

    if (fs.existsSync(tmpDbFile)) {

it("should return hello world", async () => {
  await request(strapi.server.httpServer).get("/api/hello").expect(200); // Expect response http code 200


const path = require("path");

module.exports = ({ env }) => ({
  connection: {
    client: "sqlite",
    connection: {
      filename: path.join(
        env("DATABASE_FILENAME", ".tmp/test.db")
    useNullAsDefault: true,

The route /api/hello is a custom API endpoint. This works perfectly when running strapi develop, and all permissions are set correctly.

The tests run, but every endpoint that is not / or /admin returns 403 Forbidden, meaning there is a problem with the permissions. It would seem that the database file .tmp/data.db (used in development) is not replicated correctly in .tmp/test.db. In other words, this is close to working, but the permissions for API endpoints are not set correctly.

I have been searching through StackOverflow and the Stapi Forums over the past few days but to no avail. I would greatly appreciate some pointers as to how to fix this :slight_smile:

1 Like

The issue you get is due to the missing permissions for your /api/hello endpoint.
You can inject them in your database during the bootstrap phase like it is made in the templates: https://github.com/strapi/starters-and-templates/blob/main/packages/templates/blog/template/src/bootstrap.js#L174-L180

Or you can also try config-sync with importOnBootstrap: true option https://github.com/boazpoolman/strapi-plugin-config-sync

Hope this helps!

1 Like