Restarting Strapi in Unit Tests

Update -

I’m restarting the server in case a new role was added - pay attention to the createAllRoles function below.

This does not solve the problem in testing, though - still get the same errors.

'use strict'
const _ = require("lodash")

module.exports = async () => {
  const userPermissionsService = await strapi.plugins["users-permissions"].services.userspermissions

  const MY_ROLES = [{ name: 'MyRoleA' }, { name: 'MyRoleB' }]
  await createAllRoles(MY_ROLES, userPermissionsService)

  const myRole1 = await getRole("myrolea", userPermissionsService)
  setPermission(myRole1, "application", "user", "create", true)
  await userPermissionsService.updateRole(myRole1.id, myRole1)

  return
}

const createAllRoles = async (ALL_ROLES, userPermissionsService) => {
  let newRoleWasCreated = false
  try {
    const createRoleIfNotExists = async (role) => {
      const tentativeRole = await getRole(role.name.toLowerCase(), userPermissionsService)
      if (tentativeRole) {
        strapi.log.info(`role ${role.name} already exists`)
        return
      } else {
        strapi.log.info(`creating role ${role.name}`)
        newRoleWasCreated = true
        return userPermissionsService.createRole(role)
      }
    }

    for (const role of ALL_ROLES) {
      await createRoleIfNotExists(role)
    }
    if (newRoleWasCreated) {
      strapi.log.info('at least one new role was created, restarting server to populate its permissions')
      strapi.reload()
    }
  } catch (e) {
    const msg = 'Failed to create roles'
    throw new Error(msg, e)
  }
}


/**
 * @param {PluginPermissionKey} roleType
 * @param {UserPermissionsService} userPermissionsService 
 */
const getRole = async (roleType, userPermissionsService) => {
  const plugins = await userPermissionsService.getPlugins("en")
  const allRoles = await userPermissionsService.getRoles()

  const tentativeRole = _.find(allRoles, x => x.type === roleType)
  if (!tentativeRole) {
    return undefined
  }
  const { id } = tentativeRole
  return userPermissionsService.getRole(id, plugins)
}

/**
 * @param {Role} role
 * @param {PluginPermissionKey} type
 * @param {string} controller
 * @param {string} action
 * @param {boolean} enabled
 */
const setPermission = (role, type, controller, action, enabled) => {
  try {
    role.permissions[type].controllers[controller][action].enabled = enabled
  }
  catch (e) {
    strapi.log.error(`Couldn't set permission ${role.name} ${type}:${controller}:${action}:${enabled}`, e)
  }
}