Solution - First Test
Solution
import { TestScheduler } from 'rxjs/testing';
import { map } from 'rxjs/operators';
describe('getting started with RxJS testing with marbles', () => {
let testScheduler: TestScheduler;
beforeEach(() => {
testScheduler = new TestScheduler((actual, expected) =>
expect(actual).toEqual(expected)
);
});
test('map values for the 10x developer', () => {
testScheduler.run(({ cold, expectObservable }) => {
const values = {
a: 1,
b: 10
};
const source = cold('1000ms a', values);
const expected = ' 1000ms b';
expectObservable(source.pipe(map((value) => value * 10))).toBe(
expected,
values
);
});
});
});
Let's review the solution code above:
- First, we set up the
TestSchedulerin thebeforeEach()method. - In our first test we are asserting the values emitted by the source Observable 10x, since, well, we're all 10x developers here.
- We invoke the
run()method on theTestSchedulerinstance, which takes acallbackfunction that is invoked with theRunHelpersobject. Using object destructuring we obtain thecold()andexpectObservable()functions. - Within the callback function we define the
valuesobject. - We then create a new cold Observable using the
cold()function, specifying the marble string along with thevaluesfor the next notifications. - The
expectedmarble string represents the expected behavior that we'll assert in the test. - Finally, we invoke the
expectObservable()function, providing thesourceObservable. Using themap()in the source Observable's pipe we map each next notification value to the value multiplied by 10. TheexpectObservable()returns an object containing a singletoBeproperty. Using chaining we invoke thetoBefunction and specify theexpectedmarble string, and thevaluesfor the expected next notifications.