testing-logger.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { VendureLogger } from '@vendure/core';
  2. /**
  3. * @description
  4. * The TestingLogger can be used in unit tests or e2e tests to make assertions on whether the various
  5. * Logger methods have been called, and which arguments.
  6. *
  7. * Here's some examples of how to use it in e2e tests and unit tests. In both cases we are using
  8. * the Jest testing framework, but the TestingLogger should work with other similar frameworks
  9. * (e.g. replacing `jest.fn()` with `jasmine.createSpy()`).
  10. *
  11. * @example
  12. * ```ts
  13. * // e2e test example
  14. * import { createTestEnvironment, TestingLogger } from '\@vendure/testing';
  15. *
  16. * const testingLogger = new TestingLogger(() => jest.fn());
  17. *
  18. * const { server, adminClient, shopClient } = createTestEnvironment({
  19. * ...testConfig,
  20. * logger: testingLogger,
  21. * });
  22. *
  23. * // e2e testing setup omitted
  24. *
  25. * it('should log an error', async () => {
  26. * // The `errorSpy` property exposes the Jest mock function
  27. * testingLogger.errorSpy.mockClear();
  28. *
  29. * await doSomethingThatErrors();
  30. *
  31. * expect(testingLogger.errorSpy).toHaveBeenCalled();
  32. * });
  33. * ```
  34. *
  35. * @example
  36. * ```ts
  37. * // unit test example
  38. * import { Test } from '\@nestjs/testing';
  39. * import { Logger } from '\@vendure/core';
  40. * import { TestingLogger } from '\@vendure/testing';
  41. *
  42. * beforeEach(async () => {
  43. * const moduleRef = await Test.createTestingModule({
  44. * // Nest testing setup omitted
  45. * }).compile();
  46. *
  47. * Logger.useLogger(testingLogger);
  48. * moduleRef.useLogger(new Logger());
  49. * }
  50. * ```
  51. *
  52. * @docsCategory testing
  53. */
  54. export class TestingLogger<Spy extends (...args: any[]) => any> implements VendureLogger {
  55. constructor(private createSpyFn: () => Spy) {
  56. this.debugSpy = createSpyFn();
  57. this.errorSpy = createSpyFn();
  58. this.infoSpy = createSpyFn();
  59. this.verboseSpy = createSpyFn();
  60. this.warnSpy = createSpyFn();
  61. }
  62. debugSpy: Spy;
  63. errorSpy: Spy;
  64. infoSpy: Spy;
  65. verboseSpy: Spy;
  66. warnSpy: Spy;
  67. debug(message: string, context?: string): void {
  68. this.debugSpy(message, context);
  69. }
  70. error(message: string, context?: string, trace?: string): void {
  71. this.errorSpy(message, context, trace);
  72. }
  73. info(message: string, context?: string): void {
  74. this.infoSpy(message, context);
  75. }
  76. verbose(message: string, context?: string): void {
  77. this.verboseSpy(message, context);
  78. }
  79. warn(message: string, context?: string): void {
  80. this.warnSpy(message, context);
  81. }
  82. }