5

I'm trying to add unit testing on a brand new strapi application. The official documentation is still in progress. So, until the documentation is being ready is there a way to add jest unit testing to strapi application ? i followed the approach in the v3 documentation with no luck.

1
  • Too broad. Please explain the specific problem.
    – Lin Du
    Dec 9, 2021 at 5:43

1 Answer 1

5

There are quite a few changes from Strapi V3 to Strapi V4 when it comes to initializing a Strapi application's APIs. The most important changes are how Strapi populates the KOA routes, and how to make requests to the http server.

To populate the KOA routes use

await instance.server.mount();

instead of

await instance.app
       .use(instance.router.routes()) // populate KOA routes
       .use(instance.router.allowedMethods()); // populate KOA methods
instance.server = http.createServer(instance.app.callback());

To call the http server use

 strapi.server.httpServer

instead of

 strapi.server

You also need to use the new database configuration schema when defining your test database. You can use the following as an initial setup for your tests.

The following is an updated (and WIP) guide based on Strapi V3 Unit Testing guide.

First run

 yarn add --dev jest supertest sqlite3

or

 npm install --save-dev jest supertest sqlite3

Then add the following to your ./package.json scripts:

"scripts": {
   // ...strapi scripts
  "test": "jest --forceExit --detectOpenHandles", //add
  "watch": "yarn test --watch", // optional
}

Then add the following files:

./jest.config.js

module.exports = {
    verbose: true,
    testPathIgnorePatterns: [
        "/node_modules/",
        ".tmp",
        ".cache"
    ],
    modulePaths: [
        "/node_modules/",
    ],
    testEnvironment: "node",
};

./config/env/test/database.json

{
    "connection": {
        "client": "sqlite",
        "connection": {
            "filename": ".tmp/test.db"
        },
        "useNullAsDefault": true,
        "pool": {
            "min": 0,
            "max": 1
        }
    }
}

./tests/helpers/strapi.js

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

let instance;

async function setupStrapi() {
  if (!instance) {
    await Strapi().load();
    instance = strapi;
    await instance.server.mount();
  }
  return instance;
}

async function cleanupStrapi() {
  const dbSettings = strapi.config.get("database.connection");
  const tmpDbFile = dbSettings.connection.filename

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

  //delete test database after all tests
  if (dbSettings && tmpDbFile) {
    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
  // close the connection to the database
  await strapi.db.connection.destroy();
}

module.exports = { setupStrapi, cleanupStrapi };

Note that you need to have the /hello endpoint in your project as specified in the strapi docs for the next tests to pass.

./tests/app.test.js

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

jest.setTimeout(15000);

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

afterAll(async () => {
 await cleanupStrapi();
});

it("strapi is defined", () => {
  expect(strapi).toBeDefined();
});

require('./hello')

./tests/hello/index.js

const request = require('supertest');

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

I hope this helps anyone struggling with the same issues. I will update the answer as I progress.

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 22, 2022 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.