utils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
  2. import { asapScheduler, Subscription, timer, isObservable } from 'rxjs';
  3. import { OBSERVABLE_TEST_TIMEOUT_IN_MS } from './types';
  4. export function forceObservableCompletion(subscription: Subscription, resolve: (args: any) => void) {
  5. const timeoutObservable = timer(OBSERVABLE_TEST_TIMEOUT_IN_MS, asapScheduler);
  6. subscription.add(
  7. timeoutObservable.subscribe(() => {
  8. subscription.unsubscribe();
  9. resolve({
  10. pass: false,
  11. message: () =>
  12. `${matcherHint('.toEmitValues')}
  13. Expected ${printReceived('Observable')} to be ${printExpected(
  14. `completed within ${OBSERVABLE_TEST_TIMEOUT_IN_MS}ms`
  15. )} but it did not.`,
  16. });
  17. })
  18. );
  19. }
  20. export function expectObservableToBeDefined(received: any): jest.CustomMatcherResult | null {
  21. if (received) {
  22. return null;
  23. }
  24. return {
  25. pass: false,
  26. message: () => `${matcherHint('.toEmitValues')}
  27. Expected ${printReceived(received)} to be ${printExpected('defined')}.`,
  28. };
  29. }
  30. export function expectObservableToBeObservable(received: any): jest.CustomMatcherResult | null {
  31. if (isObservable(received)) {
  32. return null;
  33. }
  34. return {
  35. pass: false,
  36. message: () => `${matcherHint('.toEmitValues')}
  37. Expected ${printReceived(received)} to be ${printExpected('an Observable')}.`,
  38. };
  39. }
  40. export function expectObservable(received: any): jest.CustomMatcherResult | null {
  41. const toBeDefined = expectObservableToBeDefined(received);
  42. if (toBeDefined) {
  43. return toBeDefined;
  44. }
  45. const toBeObservable = expectObservableToBeObservable(received);
  46. if (toBeObservable) {
  47. return toBeObservable;
  48. }
  49. return null;
  50. }