Exercise - Test Custom Operator
Testing Custom Operators
This is the where using RxJS's TestScheduler
shines.
As indicated earlier in the course, it is likely unnecessary to use the TestScheduler
for writing automated tests for an application that uses RxJS Observables.
However, it is very likely that you should use the TestScheduler
for automated testing of custom operators.
Example Custom Operator
Let's look at an example custom operator:
import { from, pipe } from 'rxjs';
import { bufferCount, mergeMap, sequenceEqual } from 'rxjs/operators';
export const verifyPasscode = (valid: number[]) =>
pipe(
bufferCount<number>(4),
mergeMap((passcode) => from(passcode).pipe(sequenceEqual(from(valid))))
);
The verifyPasscode()
operator may look familiar to you.
We used the verifyPassword()
operator in the solution to the exercise on using the pipe function for creating custom operators.
To quickly recap:
- The
verifyPasscode()
operators buffers next notifications. Once 4 next notifications are emitted, the values are concatenated into an array. - The
mergeMap()
operator accepts the array of values, and using thesequenceEqual()
operator we verify that thepasscode
is valid.
Exercise
Create several tests using the TestScheduler
for the verifyPasscode()
custom operator.
- Open exercise on codesandbox.
- Create a test asserting after 4 correct values the operator emits a next notification whose value is
true
. - Create a test asserting after only 1 correct value the operator never emits a next notification.
- Create a test asserting after 4 incorrect values the operator emits a next notification whose value is
false
. - Create a test asserting after 8 incorrect values the operator emits a next notification whose value is
false
.