toEmitValuesWith.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { matcherHint, printReceived } from 'jest-matcher-utils';
  2. import { Observable, Subscription } from 'rxjs';
  3. import { expectObservable, forceObservableCompletion } from './utils';
  4. function tryExpectations(received: any[], expectations: (received: any[]) => void): jest.CustomMatcherResult {
  5. try {
  6. expectations(received);
  7. return {
  8. pass: true,
  9. message: () => `${matcherHint('.not.toEmitValues')}
  10. Expected observable to complete with
  11. ${printReceived(received)}
  12. `,
  13. };
  14. } catch (err) {
  15. return {
  16. pass: false,
  17. message: () => 'failed ' + err,
  18. };
  19. }
  20. }
  21. /**
  22. * Collect all the values emitted by the observables (also errors) and pass them to the expectations functions after
  23. * the observable ended (or emitted error). If Observable does not complete within OBSERVABLE_TEST_TIMEOUT_IN_MS the
  24. * test fails.
  25. */
  26. export function toEmitValuesWith(
  27. received: Observable<any>,
  28. expectations: (actual: any[]) => void
  29. ): Promise<jest.CustomMatcherResult> {
  30. const failsChecks = expectObservable(received);
  31. if (failsChecks) {
  32. return Promise.resolve(failsChecks);
  33. }
  34. return new Promise((resolve) => {
  35. const receivedValues: any[] = [];
  36. const subscription = new Subscription();
  37. subscription.add(
  38. received.subscribe({
  39. next: (value) => {
  40. receivedValues.push(value);
  41. },
  42. error: (err) => {
  43. receivedValues.push(err);
  44. subscription.unsubscribe();
  45. resolve(tryExpectations(receivedValues, expectations));
  46. },
  47. complete: () => {
  48. subscription.unsubscribe();
  49. resolve(tryExpectations(receivedValues, expectations));
  50. },
  51. })
  52. );
  53. forceObservableCompletion(subscription, resolve);
  54. });
  55. }