Hi,
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(strapi).toBeDefined();
expect(await strapi.services.utils.checkProfanity).toBeDefined();
expect(
await strapi.services.utils.checkProfanity("I am clean.").isProfane
).toBeFalsy();
expect(
await strapi.services.utils.checkProfanity("I am an arse.").isProfane
).toBeTruthy();
done();
});
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
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?