Unit testing setup

I’m trying to test a service that I’ve created. I’ve done my setup as mentioned in the unit testing guide.
Here’s my test/utils/index.js:

"use strict";
it("profanity filter works", async (done) => {
  expect(await strapi.services.utils.checkProfanity).toBeDefined();
    await strapi.services.utils.checkProfanity("I am clean.").isProfane
    await strapi.services.utils.checkProfanity("I am an arse.").isProfane

I have require("./utils"); at the bottom of my tests/app.test.js.

The expect(strapi).toBeDefined(); statement works, but I get a TypeError: Cannot read property 'utils' of undefined on the test. I do have the service working outside of a test. Any ideas?

Hello :slight_smile:
In the unit tests, no app is launched, only the code required by the test file is used. Thus, the global variable strapi doesn’t exist. You can do const utils = require('./utils') and then call your function with utils.checkProfanity (without using the global variable strapi).


That makes sense, thanks. I got my code working with a reference like you mentioned. I’m curious though, as to how this is working - strapi.plugins["users-permissions"].services.user.add in this example I found:

That repo is from the same guy who authored the unit testing guide I believe. His setup for tests is the same as mine, but if no app is launched, then we shouldn’t be able to access strapi.plugins either right?

@Pierre_Noel is there any way I can test functions that call strapi.services within them?

You can look at how a End to End test is made here : strapi/admin-role.test.e2e.js at master · strapi/strapi · GitHub

You can see the strapi variable instanciated. You can use it for your purpose I guess.
This feature was developped by @Convly :slight_smile:

1 Like