main.test.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Delays, greeter } from '../src/main.js';
  2. describe('greeter function', () => {
  3. const name = 'John';
  4. let hello: string;
  5. let timeoutSpy: jest.SpyInstance;
  6. // Act before assertions
  7. beforeAll(async () => {
  8. // Read more about fake timers
  9. // http://facebook.github.io/jest/docs/en/timer-mocks.html#content
  10. // Jest 27 now uses "modern" implementation of fake timers
  11. // https://jestjs.io/blog/2021/05/25/jest-27#flipping-defaults
  12. // https://github.com/facebook/jest/pull/5171
  13. jest.useFakeTimers();
  14. timeoutSpy = jest.spyOn(global, 'setTimeout');
  15. const p: Promise<string> = greeter(name);
  16. jest.runOnlyPendingTimers();
  17. hello = await p;
  18. });
  19. // Teardown (cleanup) after assertions
  20. afterAll(() => {
  21. timeoutSpy.mockRestore();
  22. });
  23. // Assert if setTimeout was called properly
  24. it('delays the greeting by 2 seconds', () => {
  25. expect(setTimeout).toHaveBeenCalledTimes(1);
  26. expect(setTimeout).toHaveBeenLastCalledWith(
  27. expect.any(Function),
  28. Delays.Long,
  29. );
  30. });
  31. // Assert greeter result
  32. it('greets a user with `Hello, {name}` message', () => {
  33. expect(hello).toBe(`Hello, ${name}`);
  34. });
  35. });