Created
November 11, 2022 14:43
-
-
Save ivanahuckova/18617179fd17325bd1e158ad44ccd049 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { of } from 'rxjs'; | |
import { map, toArray, mergeMap, delay, catchError } from 'rxjs/operators'; | |
describe('subscribe & assert testing in RxJS', () => { | |
it('should compare each emitted value', () => { | |
const source$ = of(1,2,3) | |
const final$ = source$.pipe(map(value => value * 10)) | |
// array with expected values | |
const expected = [10, 20, 30] | |
// we'll use the index and increment it after each call | |
let index = 0; | |
final$.subscribe(value => { | |
expect(value).toEqual(expected[index]) | |
index++ | |
}) | |
}) | |
it('should compare each emitted value with toArray', () => { | |
const source$ = of(1,2,3) | |
const final$ = source$.pipe( | |
map(value => value * 10), | |
toArray() | |
) | |
// array with expected values | |
const expected = [10, 20, 30] | |
final$.subscribe(value => { | |
expect(value).toEqual(expected) | |
}) | |
}) | |
//Use a single argument called done. Jest will wait until the done callback is called before finishing the test. | |
it('should let you test async operations with done callback', done => { | |
const source$ = of('Ready','Set', 'Go').pipe( | |
// delay each emission so we have async behavior | |
mergeMap((message, index) => of(message).pipe(delay(index * 1000))) | |
); | |
const expected = ['Ready', 'Set', 'Go']; | |
let index = 0 | |
source$.subscribe(value => { | |
expect(value).toEqual(expected[index]) | |
index++ | |
// Run done() on complete | |
}, null, done) | |
}) | |
//Use a single argument called done. Jest will wait until the done callback is called before finishing the test. | |
it('should let you test errors and error messages', () => { | |
const source$ = of({first: 'Brian', last: 'Smith'}, null).pipe( | |
// delay each emission so we have async behavior | |
map(o => `${o.first} ${o.last}`), | |
catchError(() => { | |
throw 'Invalid response!' | |
}) | |
); | |
const expected = ['Brian Smith', 'Invalid response!']; | |
const actual = [] | |
source$.subscribe({ | |
next: value => { | |
actual.push(value) | |
}, | |
error: error => { | |
actual.push(error) | |
expect(actual).toEqual(expected) | |
} | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment