Alternative Mocking Strategy
An alternative to using MockBackend is to create our own light mocks. Here we create an object and then tell TypeScript to treat it as Http using type assertion. We then create a spy for its get method and return an observable similar to what the real Http service would do.
This method still allows us to check to see that the service has requested the right URL, and that it returns that expected data.
wikisearch.spec.ts
1
import {
2
fakeAsync,
3
inject,
4
TestBed
5
} from '@angular/core/testing';
6
import { HttpClientModule } from '@angular/common/http';
7
import { Observable } from 'rxjs/Observable';
8
import 'rxjs/add/observable/of';
9
import { SearchWiki } from './wikisearch.service';
10
11
const mockResponse = {
12
"batchcomplete": "",
13
"continue": {
14
"sroffset": 10,
15
"continue": "-||"
16
},
17
"query": {
18
"searchinfo": {
19
"totalhits": 36853
20
},
21
"search": [{
22
"ns": 0,
23
"title": "Stuff",
24
"snippet": "<span></span>",
25
"size": 1906,
26
"wordcount": 204,
27
"timestamp": "2016-06-10T17:25:36Z"
28
}]
29
}
30
};
31
32
describe('Wikipedia search service', () => {
33
34
beforeEach(() => {
35
mockHttp = { get: null } as Http;
36
37
spyOn(mockHttp, 'get').and.returnValue(Observable.of({
38
json: () => mockResponse
39
}));
40
41
TestBed.configureTestingModule({
42
imports: [HttpClientModule],
43
providers: [
44
{
45
provide: Http,
46
useValue: mockHttp
47
},
48
SearchWiki
49
]
50
});
51
});
52
53
it('should get search results', fakeAsync(
54
inject([SearchWiki], searchWiki => {
55
const expectedUrl = 'https://en.wikipedia.org/w/api.php?' +
56
'action=query&list=search&srsearch=Angular';
57
58
searchWiki.search('Angular')
59
.subscribe(res => {
60
expect(mockHttp.get).toHaveBeenCalledWith(expectedUrl);
61
expect(res).toEqual(mockResponse);
62
});
63
})
64
));
65
66
});
Copied!
Last modified 2yr ago
Copy link