https://www.notion.so/Unit-Test-63c0089d6e314758856eb7a1608831c5
Http Mock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {HttpTestingController} from '@angular/common/http/testing';
describe('DataService', () => {
let service: DataService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [DataService]
});
service = TestBed.get(DataService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('be able to retrieve posts from the API bia GET', () => {
const dummyPosts: Post[] = [{
userId: '1',
id: 1,
body: 'Hello World',
title: 'testing Angular'
}, {
userId: '2',
id: 2,
body: 'Hello World2',
title: 'testing Angular2'
}];
service.getPost().subscribe(posts => {
expect(posts.length).toBe(2);
expect(posts).toEqual(dummyPosts);
});
const request = httpMock.expectOne( `${service.ROOT_URl}/posts`);
expect(request.request.method).toBe('GET');
request.flush(dummyPosts);
});
});