Skip to content

Commit 64a0b92

Browse files
committed
feat(services): add example of jasmine spy stubbing
1 parent 729451a commit 64a0b92

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ All the scenarios are listed here below and nicely linked to the source file.
4343
_Learn how to test async operations using the `async()` as well as `fakeAsync()` functions._
4444
* [Mocking and remote http calls](./src/app/services/remote.service.spec.ts)
4545
_Learn how to mock external dependencies, such as use the `MockBackend` provided by Angular to respond to http calls._
46+
* [Mocking remote calls with Jasmine spies](./src/app/services/remote.service.fake-call.spec.ts)
47+
_Fake the call by using Jasmine spies._
4648
1. [**Testing Pipes**](./src/app/pipes)
4749
* [custom filter pipe](./src/app/pipes/filter.pipe.spec.ts)
4850
* [async pipes within templates](./src/app/components/async-stream.component.spec.ts)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/* tslint:disable:no-unused-variable */
2+
3+
import {
4+
HttpClientTestingModule,
5+
HttpTestingController
6+
} from '@angular/common/http/testing';
7+
import { of } from 'rxjs/observable/of';
8+
import { TestBed } from '@angular/core/testing';
9+
import { RemoteService } from './remote.service';
10+
11+
describe('RemoteService (fake call with Jasmine)', () => {
12+
let service: RemoteService;
13+
14+
beforeEach(() => {
15+
TestBed.configureTestingModule({
16+
imports: [HttpClientTestingModule],
17+
// providers: [{ provide: RemoteService, useValue: jasmineSpy }]
18+
providers: [RemoteService]
19+
});
20+
21+
// inject the service
22+
service = TestBed.get(RemoteService);
23+
});
24+
25+
it('should have a service instance', () => {
26+
expect(service).toBeDefined();
27+
});
28+
29+
it('should return the mocked data in the subscribe', () => {
30+
const spy = spyOn(service, 'fetchViaHttp').and.returnValue(
31+
of({
32+
name: 'Juri'
33+
})
34+
);
35+
36+
// act
37+
service.fetchViaHttp().subscribe(data => {
38+
expect(data.name).toBe('Juri');
39+
});
40+
41+
// assert
42+
expect(spy).toHaveBeenCalled();
43+
});
44+
45+
it('should not invoke the error throwing function since we mocked it', () => {
46+
const emptyFn = () => {};
47+
const spy = spyOn(service, 'throwingError').and.callFake(emptyFn);
48+
49+
// act
50+
service.throwingError();
51+
52+
// assert
53+
expect(spy).toHaveBeenCalled();
54+
});
55+
});

src/app/services/remote.service.ts

+4
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,8 @@ export class RemoteService {
99
fetchViaHttp(): Observable<any> {
1010
return this.http.get('/someendpoint/people.json');
1111
}
12+
13+
throwingError() {
14+
throw new Error('Should be mocked');
15+
}
1216
}

0 commit comments

Comments
 (0)