Skip to content

Commit d2ab01d

Browse files
authored
docs(testing): include observables testing snippet (#21)
1 parent 6f9b16b commit d2ab01d

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
title: Different ways of observables' testing
3+
description: "Unwrap & test your observables in different ways depending on a case"
4+
tags: ["angular", "rxjs", "jest", "testing"]
5+
pubDate: Feb 25, 2023
6+
contributedBy: "@bartosz_wasilew"
7+
---
8+
9+
Let's assume we have some `UserListComponent` exposing public stream `users$` (typeof User):
10+
11+
```typescript
12+
type User = {
13+
id: number;
14+
name: string;
15+
email: string;
16+
};
17+
```
18+
19+
In case we'd like to test it, for this example we'll need the following setup:
20+
21+
```typescript
22+
const usersMock: User[] = [
23+
{ id: 1, name: 'Johny Bravo', email: '[email protected]' },
24+
{ id: 2, name: 'React dev', email: '[email protected]' }, // Heey I'm just kidding, Angular 🤝 React
25+
{ id: 3, name: '10x Dev', email: '[email protected]' },
26+
];
27+
28+
const userListComponent = {
29+
users$: of(usersMock),
30+
};
31+
```
32+
33+
Then you aren't limited only to use `subscribe()` on this Observable, you can pick different ways depending on your case:
34+
35+
```typescript
36+
it('done func', (done: DoneCallback) => {
37+
userListComponent.users$.subscribe((expectedUsers: User[]) => {
38+
expect(expectedUsers).toStrictEqual(usersMock);
39+
done();
40+
});
41+
});
42+
43+
it('first value from', async () => {
44+
const expectedUsers: User[] = await firstValueFrom(
45+
userListComponent.users$,
46+
);
47+
expect(expectedUsers).toStrictEqual(usersMock);
48+
});
49+
50+
it('Fake async & tick', fakeAsync(() => {
51+
let expectedUsers;
52+
userListComponent.users$.subscribe((users: User[]) =>
53+
setTimeout(() => {
54+
expectedUsers = users;
55+
}, 2000),
56+
);
57+
tick(2100);
58+
expect(expectedUsers).toStrictEqual(usersMock);
59+
}));
60+
61+
it('marbles', () => {
62+
const testScheduler = new TestScheduler((actual, expected) => {
63+
expect(actual).toStrictEqual(expected);
64+
});
65+
testScheduler.run(({ expectObservable }) => {
66+
expectObservable(userListComponent.users$).toBe('(a|)', {
67+
a: usersMock,
68+
});
69+
});
70+
});
71+
```
72+
73+
74+

0 commit comments

Comments
 (0)