toEmitValues.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
  2. import { isEqual } from 'lodash';
  3. import { Observable, Subscription } from 'rxjs';
  4. import { expectObservable, forceObservableCompletion } from './utils';
  5. function passMessage(received: any[], expected: any[]) {
  6. return `${matcherHint('.not.toEmitValues')}
  7. Expected observable to emit values:
  8. ${printExpected(expected)}
  9. Received:
  10. ${printReceived(received)}
  11. `;
  12. }
  13. function failMessage(received: any[], expected: any[]) {
  14. return `${matcherHint('.toEmitValues')}
  15. Expected observable to emit values:
  16. ${printExpected(expected)}
  17. Received:
  18. ${printReceived(received)}
  19. `;
  20. }
  21. function tryExpectations(received: any[], expected: any[]): jest.CustomMatcherResult {
  22. try {
  23. if (received.length !== expected.length) {
  24. return {
  25. pass: false,
  26. message: () => failMessage(received, expected),
  27. };
  28. }
  29. for (let index = 0; index < received.length; index++) {
  30. const left = received[index];
  31. const right = expected[index];
  32. if (!isEqual(left, right)) {
  33. return {
  34. pass: false,
  35. message: () => failMessage(received, expected),
  36. };
  37. }
  38. }
  39. return {
  40. pass: true,
  41. message: () => passMessage(received, expected),
  42. };
  43. } catch (err) {
  44. return {
  45. pass: false,
  46. message: () => err,
  47. };
  48. }
  49. }
  50. export function toEmitValues(received: Observable<any>, expected: any[]): Promise<jest.CustomMatcherResult> {
  51. const failsChecks = expectObservable(received);
  52. if (failsChecks) {
  53. return Promise.resolve(failsChecks);
  54. }
  55. return new Promise((resolve) => {
  56. const receivedValues: any[] = [];
  57. const subscription = new Subscription();
  58. subscription.add(
  59. received.subscribe({
  60. next: (value) => {
  61. receivedValues.push(value);
  62. },
  63. error: (err) => {
  64. receivedValues.push(err);
  65. subscription.unsubscribe();
  66. resolve(tryExpectations(receivedValues, expected));
  67. },
  68. complete: () => {
  69. subscription.unsubscribe();
  70. resolve(tryExpectations(receivedValues, expected));
  71. },
  72. })
  73. );
  74. forceObservableCompletion(subscription, resolve);
  75. });
  76. }