Strapi

Automated Testing for Strapi v5 Plugins: Testing the API's

Boaz Poolman

Published on 20 January 2025

In the first article of this series, we explored setting up a playground instance to facilitate automated testing for Strapi plugins. Building upon that foundation, this article focuses on validating the API endpoints of your Strapi plugin to ensure they function as intended.

 

Prerequisites:

  • A Strapi plugin initialized using @strapi/sdk-plugin.
  • A playground instance of Strapi configured for testing.
  • Basic understanding of Jest and Supertest.

To get up to speed I recommend you read the previous article first. You can find it here:

Automated Testing for Strapi v5 Plugins: Using a Playground Instance

Boaz Poolman

3 weeks ago

Strapi v5 Boilerplate Plugin

A quick note before we start: the setup that I'll be explaining in this article is available as a template on Github. If you want to get right in to it, or prefer exploring a Github Repository rather than reading an article, please refer to the Strapi v5 Plugin Boilerplate. It has been setup with all the automated testing goodness and is ready for you to start building!

 

Now on with the article.

1. Setting Up Testing Dependencies

To begin, ensure that Jest and Supertest are installed as development dependencies in your plugin's root directory:

yarn add -D jest supertest

This command installs Jest for running tests and Supertest for making HTTP assertions.

2. Configuring Jest

In your plugin's package.json file, add the following script to facilitate running tests:

{
  "scripts": {
    "test:jest": "ENV_PATH=./playground/.env  jest --verbose --runInBand --forceExit",
  }
}

Additionally, create a file called jest.config.js with the basic Jest configuration:

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

This setup ensures that Jest uses the Node.js environment and ignores unnecessary directories during testing.

3. Initializing the Playground for Testing

To test your plugin's API endpoints, initialize the Playground instance within your test suite. Create a tests directory in the playground's root and add a helpers.js file with the following setup:

const { createStrapi, compileStrapi } = require("@strapi/strapi");
const fs = require("fs");

let instance;

/**
 * Setups strapi for futher testing
 */
async function setupStrapi() {
  if (!instance) {
    const app = await createStrapi({
      appDir: "./playground",
      distDir: "./playground/dist",
    }).load();

    instance = app; // strapi is global now

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

/**
 * Closes strapi after testing
 */
async function stopStrapi() {
  if (instance) {
    await instance.server.httpServer.close();
    await instance.db.connection.destroy();
    instance.destroy();
    const tmpDbFile = strapi.config.get(
      "database.connection.connection.filename"
    );

    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }

  }
  return instance;
}

module.exports = {
  setupStrapi,
  stopStrapi,
};

This script provides functions to set up and tear down the Playground instance for testing purposes.

4. Writing Tests for Your Plugin's API Endpoint

With the setup complete, you can now write tests to validate your plugin's API's. Assuming your plugin has been setup with @strapi/sdk-plugin, it will have an example API endpoint provided by default. Create a tests directory in the root of your repository, and add an example.test.ts file and write your first test:

const request = require('supertest');
const { setupStrapi, stopStrapi } = require('../playground/tests/helpers');

let strapi;

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

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

it('should return a successful response from the example endpoint', async () => {
  const response = await request(strapi.server.httpServer)
    .get('/api/boilerplate')
    .expect(200);

  expect(response.text).toBe('Welcome to Strapi 🚀');
});

it('should return the correct message from the example service', async () => {
  const welcomeMessage = strapi.service('plugin::boilerplate.service').getWelcomeMessage();

  expect(welcomeMessage).toBe('Welcome to Strapi 🚀');
});

This test suite initializes the Playground instance before running tests and cleans up afterward. The test checks that a GET request to the /api/boilerplate endpoint returns a 200 status code and a response body containing the value 'Welcome to Strapi 🚀'.

 

Note that this test is written for a plugin called 'boilerplate'. Please replace 'boilerplate' with the identifier of your plugin.

5. Running Your Tests

Execute the tests by running the following command in your plugin's root directory:

yarn run test:jest

Jest will run the test suite, and you should see output indicating whether the tests passed or failed.

6. Integrate your tests in the pipeline

All the steps you've followed above can be reproduced in a pipeline. By doing so, we can validate that the API's of your plugin still work after each change in the codebase.

 

You can take the GitHub Actions configuration of the Plugin Boilerplate as an example.

Conclusion

By following these steps, you've set up automated testing for your Strapi plugin's API endpoints using Jest and Supertest. This approach ensures that your plugin's APIs function correctly, enhancing the reliability and robustness of your plugin.

 

In the next article, we'll delve into more advanced testing strategies, such as integration and end-to-end testing, to further solidify your plugin's quality assurance processes.

Boaz Poolman

Published on 20 January 2025

More of Strapi