test-server.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import { INestApplication } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { DefaultLogger, JobQueueService, Logger, VendureConfig } from '@vendure/core';
  4. import { preBootstrapConfig } 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. // tslint: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) {
  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 pst: ErrorConstructor['prepareStackTrace'];
  62. let stack: any;
  63. let file: any;
  64. let frame: any;
  65. pst = Error.prepareStackTrace;
  66. Error.prepareStackTrace = (_, _stack) => {
  67. Error.prepareStackTrace = pst;
  68. return _stack;
  69. };
  70. stack = new Error().stack;
  71. stack = stack.slice(depth + 1);
  72. do {
  73. frame = stack.shift();
  74. file = frame && frame.getFileName();
  75. } while (stack.length && file === 'module.js');
  76. return file;
  77. }
  78. /**
  79. * Populates an .sqlite database file based on the PopulateOptions.
  80. */
  81. private async populateInitialData(
  82. testingConfig: Required<VendureConfig>,
  83. options: TestServerOptions,
  84. ): Promise<void> {
  85. const app = await populateForTesting(testingConfig, this.bootstrapForTesting, {
  86. logging: false,
  87. ...options,
  88. });
  89. await app.close();
  90. }
  91. /**
  92. * Bootstraps an instance of the Vendure server for testing against.
  93. */
  94. private async bootstrapForTesting(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  95. const config = await preBootstrapConfig(userConfig);
  96. Logger.useLogger(config.logger);
  97. const appModule = await import('@vendure/core/dist/app.module');
  98. try {
  99. DefaultLogger.hideNestBoostrapLogs();
  100. const app = await NestFactory.create(appModule.AppModule, {
  101. cors: config.apiOptions.cors,
  102. logger: new Logger(),
  103. });
  104. await app.listen(config.apiOptions.port);
  105. await app.get(JobQueueService).start();
  106. DefaultLogger.restoreOriginalLogLevel();
  107. return app;
  108. } catch (e) {
  109. console.log(e);
  110. throw e;
  111. }
  112. }
  113. }