|
| 1 | +import {type AsyncExpectationResult, type MatcherState} from '@vitest/expect' |
| 2 | +import {firstValueFrom, type OperatorFunction, Subject, toArray} from 'rxjs' |
| 3 | + |
| 4 | +export const NO_EMISSION = Symbol('NO_EMISSION') |
| 5 | + |
| 6 | +type Snapshot<A, B> = [A, B | typeof NO_EMISSION] |
| 7 | + |
| 8 | +interface OperatorFunctionMatchers<Type = unknown> { |
| 9 | + /** |
| 10 | + * Ensure each entry in the provided array results in the expected value being emitted when piped |
| 11 | + * to the observable. |
| 12 | + */ |
| 13 | + toMatchEmissions: Type extends () => OperatorFunction<infer A, infer B> |
| 14 | + ? (snapshots: Snapshot<A, B>[]) => Promise<Type> |
| 15 | + : never |
| 16 | +} |
| 17 | + |
| 18 | +declare module 'vitest' { |
| 19 | + interface Assertion<T = any> extends OperatorFunctionMatchers<T> {} |
| 20 | + interface AsymmetricMatchersContaining extends OperatorFunctionMatchers {} |
| 21 | +} |
| 22 | + |
| 23 | +export async function toMatchEmissions( |
| 24 | + this: MatcherState, |
| 25 | + createOperator: () => OperatorFunction<unknown, unknown>, |
| 26 | + snapshots: [A: unknown, B: unknown][], |
| 27 | +): AsyncExpectationResult { |
| 28 | + const {equals} = this |
| 29 | + const input$ = new Subject() |
| 30 | + |
| 31 | + const expectedEmissions = snapshots |
| 32 | + .filter(([, expectedEmission]) => expectedEmission !== NO_EMISSION) |
| 33 | + .map(([, expectedEmission]) => expectedEmission) |
| 34 | + |
| 35 | + const emissions$ = input$.pipe(createOperator(), toArray()) |
| 36 | + const emissions = firstValueFrom(emissions$) |
| 37 | + |
| 38 | + snapshots.forEach(([value]) => input$.next(value)) |
| 39 | + input$.complete() |
| 40 | + |
| 41 | + const actualEmissions = await emissions |
| 42 | + |
| 43 | + return { |
| 44 | + pass: equals(actualEmissions, expectedEmissions), |
| 45 | + message: () => 'Observable emissions did not match', |
| 46 | + actual: actualEmissions, |
| 47 | + expected: expectedEmissions, |
| 48 | + } |
| 49 | +} |
0 commit comments