test-server.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { INestApplication, INestMicroservice } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { DefaultLogger, Logger, VendureConfig } from '@vendure/core';
  4. import {
  5. preBootstrapConfig,
  6. runBeforeBootstrapHooks,
  7. runBeforeWorkerBootstrapHooks,
  8. } from '@vendure/core/dist/bootstrap';
  9. import { populateForTesting } from './data-population/populate-for-testing';
  10. import { getInitializerFor } from './initializers/initializers';
  11. import { TestServerOptions } from './types';
  12. // tslint:disable:no-console
  13. /**
  14. * @description
  15. * A real Vendure server against which the e2e tests should be run.
  16. *
  17. * @docsCategory testing
  18. */
  19. export class TestServer {
  20. public app: INestApplication;
  21. public worker?: INestMicroservice;
  22. constructor(private vendureConfig: Required<VendureConfig>) {}
  23. /**
  24. * @description
  25. * Bootstraps an instance of Vendure server and populates the database according to the options
  26. * passed in. Should be called in the `beforeAll` function.
  27. *
  28. * The populated data is saved into an .sqlite file for each test file. On subsequent runs, this file
  29. * is loaded so that the populate step can be skipped, which speeds up the tests significantly.
  30. */
  31. async init(options: TestServerOptions): Promise<void> {
  32. const { type } = this.vendureConfig.dbConnectionOptions;
  33. const { dbConnectionOptions } = this.vendureConfig;
  34. const testFilename = this.getCallerFilename(1);
  35. const initializer = getInitializerFor(type);
  36. try {
  37. await initializer.init(testFilename, dbConnectionOptions);
  38. const populateFn = () => this.populateInitialData(this.vendureConfig, options);
  39. await initializer.populate(populateFn);
  40. await initializer.destroy();
  41. } catch (e) {
  42. throw e;
  43. }
  44. await this.bootstrap();
  45. }
  46. /**
  47. * @description
  48. * Bootstraps a Vendure server instance. Generally the `.init()` method should be used, as that will also
  49. * populate the test data. However, the `bootstrap()` method is sometimes useful in tests which need to
  50. * start and stop a Vendure instance multiple times without re-populating data.
  51. */
  52. async bootstrap() {
  53. const [app, worker] = await this.bootstrapForTesting(this.vendureConfig);
  54. if (app) {
  55. this.app = app;
  56. } else {
  57. console.error(`Could not bootstrap app`);
  58. process.exit(1);
  59. }
  60. if (worker) {
  61. this.worker = worker;
  62. }
  63. }
  64. /**
  65. * @description
  66. * Destroy the Vendure server instance and clean up all resources.
  67. * Should be called after all tests have run, e.g. in an `afterAll` function.
  68. */
  69. async destroy() {
  70. // allow a grace period of any outstanding async tasks to complete
  71. await new Promise(resolve => global.setTimeout(resolve, 500));
  72. await this.app.close();
  73. if (this.worker) {
  74. await this.worker.close();
  75. }
  76. }
  77. private getCallerFilename(depth: number): string {
  78. let pst: ErrorConstructor['prepareStackTrace'];
  79. let stack: any;
  80. let file: any;
  81. let frame: any;
  82. pst = Error.prepareStackTrace;
  83. Error.prepareStackTrace = (_, _stack) => {
  84. Error.prepareStackTrace = pst;
  85. return _stack;
  86. };
  87. stack = new Error().stack;
  88. stack = stack.slice(depth + 1);
  89. do {
  90. frame = stack.shift();
  91. file = frame && frame.getFileName();
  92. } while (stack.length && file === 'module.js');
  93. return file;
  94. }
  95. /**
  96. * Populates an .sqlite database file based on the PopulateOptions.
  97. */
  98. private async populateInitialData(
  99. testingConfig: Required<VendureConfig>,
  100. options: TestServerOptions,
  101. ): Promise<void> {
  102. const [app, worker] = await populateForTesting(testingConfig, this.bootstrapForTesting, {
  103. logging: false,
  104. ...options,
  105. });
  106. if (worker) {
  107. await worker.close();
  108. }
  109. await app.close();
  110. }
  111. /**
  112. * Bootstraps an instance of the Vendure server for testing against.
  113. */
  114. private async bootstrapForTesting(
  115. userConfig: Partial<VendureConfig>,
  116. ): Promise<[INestApplication, INestMicroservice | undefined]> {
  117. const config = await preBootstrapConfig(userConfig);
  118. Logger.useLogger(config.logger);
  119. const appModule = await import('@vendure/core/dist/app.module');
  120. try {
  121. DefaultLogger.hideNestBoostrapLogs();
  122. const app = await NestFactory.create(appModule.AppModule, {
  123. cors: config.apiOptions.cors,
  124. logger: new Logger(),
  125. });
  126. let worker: INestMicroservice | undefined;
  127. await runBeforeBootstrapHooks(config, app);
  128. await app.listen(config.apiOptions.port);
  129. if (config.workerOptions.runInMainProcess) {
  130. const workerModule = await import('@vendure/core/dist/worker/worker.module');
  131. worker = await NestFactory.createMicroservice(workerModule.WorkerModule, {
  132. transport: config.workerOptions.transport,
  133. logger: new Logger(),
  134. options: config.workerOptions.options,
  135. });
  136. await runBeforeWorkerBootstrapHooks(config, worker);
  137. await worker.listenAsync();
  138. }
  139. DefaultLogger.restoreOriginalLogLevel();
  140. return [app, worker];
  141. } catch (e) {
  142. console.log(e);
  143. throw e;
  144. }
  145. }
  146. }