1 import { logger } from "@medusajs/framework/logger"
2 import {
3 ContainerRegistrationKeys,
4 DmlEntity,
5 isSharedConnectionSymbol,
6 loadModels,
7 Modules,
8 ModulesSdkUtils,
9 normalizeImportPathWithSource,
10 toMikroOrmEntities,
11 } from "@medusajs/framework/utils"
12 import * as fs from "fs"
13 import { getDatabaseURL, getMikroOrmWrapper, TestDatabase } from "./database"
14 import { formatError } from "./medusa-test-runner-utils"
15 import { initModules, InitModulesOptions } from "./init-modules"
16 import { default as MockEventBusService } from "./mock-event-bus-service"
17 import { ulid } from "ulid"
18
19 export interface SuiteOptions<TService = unknown> {
20 MikroOrmWrapper: TestDatabase
21 medusaApp: any
22 service: TService
23 dbConfig: {
24 schema: string
25 clientUrl: string
26 }
27 }
28
29 interface ModuleTestRunnerConfig<TService = any> {
30 moduleName: string
31 moduleModels?: any[]
32 moduleOptions?: Record<string, any>
33 moduleDependencies?: string[]
34 schema?: string
35 dbName?: string
36 injectedDependencies?: Record<string, any>
37 resolve?: string
38 debug?: boolean
39 cwd?: string
40 /**
41 * Migration directories to apply instead of deriving the schema from the
42 * module models. Needed when the schema under test spans more than one
43 * package, e.g. a module and the provider being tested.
44 */
45 pathToMigrations?: string | string[]
46 hooks?: {
47 beforeModuleInit?: () => Promise<void>
48 afterModuleInit?: (medusaApp: any, service: TService) => Promise<void>
49 }
50 }
51
52 function createMikroOrmWrapper(options: {
53 moduleModels?: (Function | DmlEntity<any, any>)[]
54 resolve?: string
55 dbConfig: any
56 cwd?: string
57 pathToMigrations?: string | string[]
58 }): {
59 MikroOrmWrapper: TestDatabase
60 models: (Function | DmlEntity<any, any>)[]
61 } {
62 let moduleModels: (Function | DmlEntity<any, any>)[] =
63 options.moduleModels ?? []
64
65 if (!options.moduleModels) {
66 const basePath = normalizeImportPathWithSource(
67 options.resolve ?? options.cwd ?? process.cwd()
68 )
69
70 const modelsPath = fs.existsSync(`${basePath}/dist/models`)
71 ? "/dist/models"
72 : fs.existsSync(`${basePath}/models`)
73 ? "/models"
74 : ""
75
76 if (modelsPath) {
77 moduleModels = loadModels(`${basePath}${modelsPath}`)
78 } else {
79 moduleModels = []
80 }
81 }
82
83 moduleModels = toMikroOrmEntities(moduleModels)
84
85 const MikroOrmWrapper = getMikroOrmWrapper({
86 mikroOrmEntities: moduleModels,
87 pathToMigrations: options.pathToMigrations,
88 clientUrl: options.dbConfig.clientUrl,
89 schema: options.dbConfig.schema,
90 })
91
92 return { MikroOrmWrapper, models: moduleModels }
93 }
94
95 class ModuleTestRunner<TService = any> {
96 private moduleName: string
97 private schema: string
98 private dbName: string
99 private dbConfig: {
100 clientUrl: string
101 schema: string
102 debug: boolean
103 }
104 private debug: boolean
105 private resolve?: string
106 private cwd?: string
107 private moduleOptions: Record<string, any>
108 private moduleDependencies?: string[]
109 private injectedDependencies: Record<string, any>
110 private pathToMigrations?: string | string[]
111 private hooks: ModuleTestRunnerConfig<TService>["hooks"] = {}
112
113 private connection: any = null
114 private MikroOrmWrapper!: TestDatabase
115 private moduleModels: (Function | DmlEntity<any, any>)[] = []
116 private modulesConfig: any = {}
117 private moduleOptionsConfig!: InitModulesOptions
118
119 private shutdown: () => Promise<void> = async () => void 0
120 private moduleService: any = null
121 private medusaApp: any = {}
122
123 constructor(config: ModuleTestRunnerConfig<TService>) {
124 const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
125 this.moduleName = config.moduleName
126 const moduleName = this.moduleName ?? ulid()
127 this.dbName =
128 config.dbName ??
129 `medusa-${moduleName.toLowerCase()}-integration-${tempName}`
130 this.schema = config.schema ?? "public"
131 this.debug = config.debug ?? false
132 this.resolve = config.resolve
133 this.cwd = config.cwd
134 this.moduleOptions = config.moduleOptions ?? {}
135 this.moduleDependencies = config.moduleDependencies
136 this.injectedDependencies = config.injectedDependencies ?? {}
137 this.pathToMigrations = config.pathToMigrations
138 this.hooks = config.hooks ?? {}
139
140 this.dbConfig = {
141 clientUrl: getDatabaseURL(this.dbName),
142 schema: this.schema,
143 debug: this.debug,
144 }
145
146 this.setupProcessHandlers()
147 this.initializeConfig(config.moduleModels)
148 }
149
150 private setupProcessHandlers(): void {
151 process.on("SIGTERM", async () => {
152 await this.cleanup()
153 process.exit(0)
154 })
155
156 process.on("SIGINT", async () => {
157 await this.cleanup()
158 process.exit(0)
159 })
160 }
161
162 private initializeConfig(moduleModels?: any[]): void {
163 const moduleSdkImports = require("@medusajs/framework/modules-sdk")
164
165 // Use a unique connection for all the entire suite
166 this.connection = ModulesSdkUtils.createPgConnection(this.dbConfig)
167
168 const { MikroOrmWrapper, models } = createMikroOrmWrapper({
169 moduleModels,
170 resolve: this.resolve,
171 dbConfig: this.dbConfig,
172 cwd: this.cwd,
173 pathToMigrations: this.pathToMigrations,
174 })
175
176 this.MikroOrmWrapper = MikroOrmWrapper
177 this.moduleModels = models
178
179 this.modulesConfig = {
180 [this.moduleName]: {
181 definition: moduleSdkImports.ModulesDefinition[this.moduleName],
182 resolve: this.resolve,
183 dependencies: this.moduleDependencies,
184 options: {
185 database: this.dbConfig,
186 ...this.moduleOptions,
187 [isSharedConnectionSymbol]: true,
188 },
189 },
190 }
191
192 this.moduleOptionsConfig = {
193 injectedDependencies: {
194 [ContainerRegistrationKeys.PG_CONNECTION]: this.connection,
195 [Modules.EVENT_BUS]: new MockEventBusService(),
196 [ContainerRegistrationKeys.LOGGER]: console,
197 [ContainerRegistrationKeys.CONFIG_MODULE]: {
198 modules: this.modulesConfig,
199 },
200 ...this.injectedDependencies,
201 },
202 modulesConfig: this.modulesConfig,
203 databaseConfig: this.dbConfig,
204 preventConnectionDestroyWarning: true,
205 cwd: this.cwd,
206 }
207 }
208
209 private createMedusaAppProxy(): any {
210 return new Proxy(
211 {},
212 {
213 get: (target, prop) => {
214 return this.medusaApp?.[prop]
215 },
216 }
217 )
218 }
219
220 private createServiceProxy(): any {
221 return new Proxy(
222 {},
223 {
224 get: (target, prop) => {
225 return this.moduleService?.[prop]
226 },
227 }
228 )
229 }
230
231 public async beforeAll(): Promise<void> {
232 try {
233 this.setupProcessHandlers()
234 process.env.LOG_LEVEL = "error"
235 } catch (error) {
236 await this.cleanup()
237 throw error
238 }
239 }
240
241 public async beforeEach(): Promise<void> {
242 try {
243 if (this.moduleModels.length) {
244 await this.MikroOrmWrapper.setupDatabase()
245 }
246
247 if (this.hooks?.beforeModuleInit) {
248 await this.hooks.beforeModuleInit()
249 }
250
251 const output = await initModules(this.moduleOptionsConfig)
252 this.shutdown = output.shutdown
253 this.medusaApp = output.medusaApp
254 this.moduleService = output.medusaApp.modules[this.moduleName]
255
256 if (this.hooks?.afterModuleInit) {
257 await this.hooks.afterModuleInit(this.medusaApp, this.moduleService)
258 }
259 } catch (error) {
260 // Deliberately not cleaning up: the shared connection lives for the whole
261 // suite, so destroying it here would replace every later failure with an
262 // unrelated "Unable to acquire a connection". `afterAll` still cleans up.
263 logger.error(`Error in beforeEach:\n${formatError(error)}`)
264 throw error
265 }
266 }
267
268 public async afterEach(): Promise<void> {
269 try {
270 if (this.moduleModels.length) {
271 await this.MikroOrmWrapper.clearDatabase()
272 }
273 await this.shutdown()
274 this.moduleService = {}
275 this.medusaApp = {}
276 } catch (error) {
277 logger.error(`Error in afterEach:\n${formatError(error)}`)
278 throw error
279 }
280 }
281
282 public async cleanup(): Promise<void> {
283 try {
284 process.removeAllListeners("SIGTERM")
285 process.removeAllListeners("SIGINT")
286
287 await (this.connection as any)?.context?.destroy()
288 await (this.connection as any)?.destroy()
289
290 this.moduleService = null
291 this.medusaApp = null
292 this.connection = null
293
294 if (global.gc) {
295 global.gc()
296 }
297 } catch (error) {
298 logger.error(`Error during cleanup:\n${formatError(error)}`)
299 }
300 }
301
302 public getOptions(): SuiteOptions<TService> {
303 return {
304 MikroOrmWrapper: this.MikroOrmWrapper,
305 medusaApp: this.createMedusaAppProxy(),
306 service: this.createServiceProxy(),
307 dbConfig: {
308 schema: this.schema,
309 clientUrl: this.dbConfig.clientUrl,
310 },
311 }
312 }
313 }
314
315 export function moduleIntegrationTestRunner<TService = any>({
316 moduleName,
317 moduleModels,
318 moduleOptions = {},
319 moduleDependencies,
320 schema = "public",
321 dbName,
322 debug = false,
323 testSuite,
324 resolve,
325 injectedDependencies = {},
326 cwd,
327 hooks,
328 pathToMigrations,
329 }: {
330 moduleName: string
331 moduleModels?: any[]
332 moduleOptions?: Record<string, any>
333 moduleDependencies?: string[]
334 schema?: string
335 dbName?: string
336 injectedDependencies?: Record<string, any>
337 resolve?: string
338 debug?: boolean
339 cwd?: string
340 hooks?: ModuleTestRunnerConfig<TService>["hooks"]
341 pathToMigrations?: string | string[]
342 testSuite: (options: SuiteOptions<TService>) => void
343 }) {
344 const runner = new ModuleTestRunner<TService>({
345 moduleName,
346 moduleModels,
347 moduleOptions,
348 moduleDependencies,
349 schema,
350 dbName,
351 debug,
352 resolve,
353 injectedDependencies,
354 cwd,
355 hooks,
356 pathToMigrations,
357 })
358
359 return describe("", () => {
360 let testOptions: SuiteOptions<TService>
361
362 beforeAll(async () => {
363 await runner.beforeAll()
364 testOptions = runner.getOptions()
365 })
366
367 beforeEach(async () => {
368 await runner.beforeEach()
369 })
370
371 afterEach(async () => {
372 await runner.afterEach()
373 })
374
375 afterAll(async () => {
376 // Run main cleanup
377 await runner.cleanup()
378
379 // Clean references to the test options
380 for (const key in testOptions) {
381 if (typeof testOptions[key] === "function") {
382 testOptions[key] = null
383 } else if (
384 typeof testOptions[key] === "object" &&
385 testOptions[key] !== null
386 ) {
387 Object.keys(testOptions[key]).forEach((k) => {
388 testOptions[key][k] = null
389 })
390 testOptions[key] = null
391 }
392 }
393
394 // Encourage garbage collection
395 // @ts-ignore
396 testOptions = null
397
398 if (global.gc) {
399 global.gc()
400 }
401 })
402
403 // Run test suite with options
404 testSuite(runner.getOptions())
405 })
406 }