Skip to content

Instantly share code, notes, and snippets.

@Antoine-lb
Last active March 26, 2024 15:23
Show Gist options
  • Save Antoine-lb/d5c104ef4a2e8835a59186f826255d60 to your computer and use it in GitHub Desktop.
Save Antoine-lb/d5c104ef4a2e8835a59186f826255d60 to your computer and use it in GitHub Desktop.
Testing and Mocking Snippets for Strapi

Testing/Mocking Snippets for Strapi

Simple test

This test is done by using Jest and Super Test. You can follow the Strapi Documentation to set it up, or you can install the community plugin strapi-plugin-testing.

it("should not create an order because request empty", async (done) => {
  await request(strapi.server)
    .post("/orders", { cart: 12 })
    .expect(400)
    .then((data) => {
      expect(data.text).toBe("Missing order information");
    });
  done();
});

Test With Auth

it("get all clients", async (done) => {
  let userJWT;

  await request(strapi.server)
    .post("/auth/local")
    .set("accept", "application/json")
    .set("Content-Type", "application/json")
    .send({
      identifier: "admin@test.test",
      password: "test",
    })
    .then((data) => {
      userJWT = data.body.jwt;
    });

  await request(strapi.server)
    .get("/restaurant-clients")
    .set("Authorization", `Bearer ${userJWT}`)
    .expect(200)
    .then((data) => {
      expect(data.text).toBe("OK");
    });
  done();
});

Get role

// get authenticated role
const defaultRole = await strapi
  .query("role", "users-permissions")
  .findOne({}, []);
const role = defaultRole ? defaultRole.id : null;

Create a user

await strapi.plugins["users-permissions"].services.user.add({
  username: "username",
  email: "email@test.test",
  provider: "local",
  password: "password",
  confirmed: true,
  blocked: null,
  role,
});

Change permissions

permission = await strapi.query("permission", "users-permissions").findOne({
  type: "application",
  "restauran-table", //example
  action: "count", // create | delete | find ...
  role,
});
permission.enabled = 1;
await strapi
  .query("permission", "users-permissions")
  .update({ id: permission.id }, permission);

Create Super Admin

const params = {
  username: process.env.DEV_USER || "test",
  password: process.env.DEV_PASS || "test",
  firstname: process.env.DEV_USER || "test",
  lastname: process.env.DEV_USER || "test",
  email: process.env.DEV_EMAIL || "admin@test.test",
  blocked: false,
  isActive: true,
};
//Check if any account exists.
const admins = await strapi.query("user", "admin").find();

if (admins.length === 0) {
  let tempPass = params.password;
  let verifyRole = await strapi
    .query("role", "admin")
    .findOne({ code: "strapi-super-admin" });
  if (!verifyRole) {
    verifyRole = await strapi.query("role", "admin").create({
      name: "Super Admin",
      code: "strapi-super-admin",
      description:
        "Super Admins can access and manage all features and settings.",
    });
  }
  params.roles = [verifyRole.id];
  params.password = await strapi.admin.services.auth.hashPassword(
    params.password
  );
  try {
    await strapi.query("user", "admin").create({
      ...params,
    });
  } catch (error) {
    strapi.log.error(`Couldn't create Admin account during bootstrap: `, error);
    console.error(`Couldn't create Admin account during bootstrap: `, error);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment