[RxJS] Marbles Testings
Install:
npm install — save-dev jasmine-marbles
Basic example:
import {cold, getTestScheduler} from 'jasmine-marbles';
import 'rxjs/add/operator/concat';
describe('Test', () => {
it('concat', () => {
const one$ = cold('x-x|');
const two$ = cold('-y|');
expect(one$.concat(two$)).toBeObservable(cold('x-x-y|'));
});
});
Advanced example:
import { MovieShowingsComponent } from './movie-showings.component';
import { cold, getTestScheduler } from 'jasmine-marbles';
describe('MovieShowingsComponent', () => {
it('should not have a race condition', () => {
const backend = jasmine.createSpyObj('backend', ['getShowings']);
const cmp = new MovieShowingsComponent(backend);
backend.getShowings.and.returnValue(cold('--x|', {x: ['10am']}));
cmp.selectMovie('After the Storm');
backend.getShowings.and.returnValue(cold('-y|', {y: ['11am']}));
cmp.selectMovie('Paterson');
// this will flush all observables
getTestScheduler().flush();
expect(cmp.movieTitle).toEqual('Paterson');
expect(cmp.showings).toEqual(['11am']); // This will fail because showings is ['10am'].
});
});
Component:
@Component({ selector: 'movie-showings-cmp', templateUrl: './movie-showings.component.html' }) export class MovieShowingsComponent { public movieTitle: string; public showings: string[]; private getShowings = new Subject<string>(); constructor(private backend: Backend) { this.getShowings.switchMap(movieTitle => this.backend.getShowings(movieTitle)).subscribe(showings => { this.showings = showings; }); } showShowings(movieTitle: string) { this.movieTitle = movieTitle; this.getShowings.next(movieTitle); } }

浙公网安备 33010602011771号