Search code examples
node.jsunit-testingjestjsstrapi

How to implement unit testing within the strapi framework


I'm experimenting with Strapi and would like to create a controller verified by unit tests.

How do I setup Unit tests within Strapi?

I have written the following test

test('checks entity inside boundary',async ()=> {
    ctx={};
    var result = await controller.findnearby(ctx);
    result = {};
    expect(result).anyting();
});

however, inside my Controller I have code that accesses a global strapi object, which causes this error ReferenceError: strapi is not defined

   strapi.log.info('findNearby');
   strapi.log.info(ctx.request.query.lat);
   strapi.log.info(ctx.request.query.long);

What is the best practice with Strapi and testing?


Solution

  • I've managed to achieve testing in Strapi by creating a helper

    const Strapi = require("strapi"); 
    // above require creates a global named `strapi` that is an instance of Strapi 
    
    let instance; // singleton 
    
    async function setupStrapi() {
      if (!instance) {
        await Strapi().load();
        instance = strapi; 
        instance.app
          .use(instance.router.routes()) // this code in copied from app/node_modules/strapi/lib/Strapi.js
          .use(instance.router.allowedMethods());
      }
      return instance;
    }
    
    module.exports = { setupStrapi };
    

    You can get all of the controllers from app.controllers now and test them one by one.

    My example test (in Jest) for API endpoint would look like

    const request = require("supertest");
    const { setupStrapi } = require("./helpers/strapi");
    
    // We're setting timeout because sometimes bootstrap can take 5-7 seconds (big apps)
    jest.setTimeout(10000);
    
    let app; // this is instance of the the strapi
    
    beforeAll(async () => {
      app = await setupStrapi(); // return singleton so it can be called many times
    });
    
    it("should respond with 200 on /heartbeat", (done) => {
      request(app.server) // app server is and instance of Class: http.Server
        .get("/heartbeat")
        .expect(200) // expecting response header code to by 200 success
        .expect("Hello World!") // expecting reponse text to be "Hello World!"
        .end(done); // let jest know that test is finished
    });
    

    I've tried to cover this topic on my blog https://medium.com/qunabu-interactive/strapi-jest-testing-with-gitlab-ci-82ffe4c5715a