Created
December 8, 2022 11:41
-
-
Save n2o/811da12b48e5cf1c4b89285ba22ea57e to your computer and use it in GitHub Desktop.
Strapi v4 Testing: setup and tearDown in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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