LiveLoveApp logo

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 the sequenceEqual() operator we verify that the passcode is valid.

Exercise

Create several tests using the TestScheduler for the verifyPasscode() custom operator.

  1. Open exercise on codesandbox.
  2. Create a test asserting after 4 correct values the operator emits a next notification whose value is true.
  3. Create a test asserting after only 1 correct value the operator never emits a next notification.
  4. Create a test asserting after 4 incorrect values the operator emits a next notification whose value is false.
  5. Create a test asserting after 8 incorrect values the operator emits a next notification whose value is false.