Skip to content

Instantly share code, notes, and snippets.

@n2o
Created December 8, 2022 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n2o/811da12b48e5cf1c4b89285ba22ea57e to your computer and use it in GitHub Desktop.
Save n2o/811da12b48e5cf1c4b89285ba22ea57e to your computer and use it in GitHub Desktop.
Strapi v4 Testing: setup and tearDown in TypeScript
// Taken from https://codesandbox.io/s/wg9317
// Thanks, you helped me a lot! https://github.com/haysclark
import strapi, { Strapi } from "@strapi/strapi";
import { compile } from "@strapi/typescript-utils";
import * as fs from "fs";
let instance: Strapi;
export const setupStrapi = async (): Promise<Strapi> => {
if (!instance) {
await compile("");
instance = await strapi({ distDir: "./dist" }).load();
const { app } = instance.server;
app
.use(instance.server.router.routes())
.use(instance.server.router.allowedMethods());
}
jest.setTimeout(60000);
return instance;
};
export async function tearDownStrapi(strapi: Strapi) {
const dbSettings = strapi.config.get("database");
await strapi.destroy();
instance = undefined;
// delete test database after all tests
if (dbSettings && dbSettings.filename) {
const tmpDbFile = `${__dirname}/../${dbSettings.filename}`;
if (fs.existsSync(tmpDbFile)) {
fs.unlinkSync(tmpDbFile);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment