test-server.ts 5.0 KB

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