{ "id": "guide/testing-services", "title": "Testing services", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Testing serviceslink

\n

To check that your services are working as you intend, you can write tests specifically for them.

\n
\n

For the sample app that the testing guides describe, see the sample app.

\n

For the tests features in the testing guides, see tests.

\n
\n

Services are often the easiest files to unit test.\nHere are some synchronous and asynchronous unit tests of the ValueService\nwritten without assistance from Angular testing utilities.

\n\n// Straight Jasmine testing without Angular's testing support\ndescribe('ValueService', () => {\n let service: ValueService;\n beforeEach(() => { service = new ValueService(); });\n\n it('#getValue should return real value', () => {\n expect(service.getValue()).toBe('real value');\n });\n\n it('#getObservableValue should return value from observable',\n (done: DoneFn) => {\n service.getObservableValue().subscribe(value => {\n expect(value).toBe('observable value');\n done();\n });\n });\n\n it('#getPromiseValue should return value from a promise',\n (done: DoneFn) => {\n service.getPromiseValue().then(value => {\n expect(value).toBe('promise value');\n done();\n });\n });\n});\n\n\n\n

Services with dependencieslink

\n

Services often depend on other services that Angular injects into the constructor.\nIn many cases, it's easy to create and inject these dependencies by hand while\ncalling the service's constructor.

\n

The MasterService is a simple example:

\n\n@Injectable()\nexport class MasterService {\n constructor(private valueService: ValueService) { }\n getValue() { return this.valueService.getValue(); }\n}\n\n\n

MasterService delegates its only method, getValue, to the injected ValueService.

\n

Here are several ways to test it.

\n\ndescribe('MasterService without Angular testing support', () => {\n let masterService: MasterService;\n\n it('#getValue should return real value from the real service', () => {\n masterService = new MasterService(new ValueService());\n expect(masterService.getValue()).toBe('real value');\n });\n\n it('#getValue should return faked value from a fakeService', () => {\n masterService = new MasterService(new FakeValueService());\n expect(masterService.getValue()).toBe('faked service value');\n });\n\n it('#getValue should return faked value from a fake object', () => {\n const fake = { getValue: () => 'fake value' };\n masterService = new MasterService(fake as ValueService);\n expect(masterService.getValue()).toBe('fake value');\n });\n\n it('#getValue should return stubbed value from a spy', () => {\n // create `getValue` spy on an object representing the ValueService\n const valueServiceSpy =\n jasmine.createSpyObj('ValueService', ['getValue']);\n\n // set the value to return when the `getValue` spy is called.\n const stubValue = 'stub value';\n valueServiceSpy.getValue.and.returnValue(stubValue);\n\n masterService = new MasterService(valueServiceSpy);\n\n expect(masterService.getValue())\n .toBe(stubValue, 'service returned stub value');\n expect(valueServiceSpy.getValue.calls.count())\n .toBe(1, 'spy method was called once');\n expect(valueServiceSpy.getValue.calls.mostRecent().returnValue)\n .toBe(stubValue);\n });\n});\n\n\n

The first test creates a ValueService with new and passes it to the MasterService constructor.

\n

However, injecting the real service rarely works well as most dependent services are difficult to create and control.

\n

Instead you can mock the dependency, use a dummy value, or create a\nspy\non the pertinent service method.

\n
\n

Prefer spies as they are usually the easiest way to mock services.

\n
\n

These standard testing techniques are great for unit testing services in isolation.

\n

However, you almost always inject services into application classes using Angular\ndependency injection and you should have tests that reflect that usage pattern.\nAngular testing utilities make it easy to investigate how injected services behave.

\n

Testing services with the TestBedlink

\n

Your app relies on Angular dependency injection (DI)\nto create services.\nWhen a service has a dependent service, DI finds or creates that dependent service.\nAnd if that dependent service has its own dependencies, DI finds-or-creates them as well.

\n

As service consumer, you don't worry about any of this.\nYou don't worry about the order of constructor arguments or how they're created.

\n

As a service tester, you must at least think about the first level of service dependencies\nbut you can let Angular DI do the service creation and deal with constructor argument order\nwhen you use the TestBed testing utility to provide and create services.

\n\n

Angular TestBedlink

\n

The TestBed is the most important of the Angular testing utilities.\nThe TestBed creates a dynamically-constructed Angular test module that emulates\nan Angular @NgModule.

\n

The TestBed.configureTestingModule() method takes a metadata object that can have most of the properties of an @NgModule.

\n

To test a service, you set the providers metadata property with an\narray of the services that you'll test or mock.

\n\nlet service: ValueService;\n\nbeforeEach(() => {\n TestBed.configureTestingModule({ providers: [ValueService] });\n});\n\n\n

Then inject it inside a test by calling TestBed.inject() with the service class as the argument.

\n
\n

Note: TestBed.get() was deprecated as of Angular version 9.\nTo help minimize breaking changes, Angular introduces a new function called TestBed.inject(), which you should use instead.\nFor information on the removal of TestBed.get(),\nsee its entry in the Deprecations index.

\n
\n\nit('should use ValueService', () => {\n service = TestBed.inject(ValueService);\n expect(service.getValue()).toBe('real value');\n});\n\n\n

Or inside the beforeEach() if you prefer to inject the service as part of your setup.

\n\nbeforeEach(() => {\n TestBed.configureTestingModule({ providers: [ValueService] });\n service = TestBed.inject(ValueService);\n});\n\n\n

When testing a service with a dependency, provide the mock in the providers array.

\n

In the following example, the mock is a spy object.

\n\nlet masterService: MasterService;\nlet valueServiceSpy: jasmine.SpyObj<ValueService>;\n\nbeforeEach(() => {\n const spy = jasmine.createSpyObj('ValueService', ['getValue']);\n\n TestBed.configureTestingModule({\n // Provide both the service-to-test and its (spy) dependency\n providers: [\n MasterService,\n { provide: ValueService, useValue: spy }\n ]\n });\n // Inject both the service-to-test and its (spy) dependency\n masterService = TestBed.inject(MasterService);\n valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>;\n});\n\n\n

The test consumes that spy in the same way it did earlier.

\n\nit('#getValue should return stubbed value from a spy', () => {\n const stubValue = 'stub value';\n valueServiceSpy.getValue.and.returnValue(stubValue);\n\n expect(masterService.getValue())\n .toBe(stubValue, 'service returned stub value');\n expect(valueServiceSpy.getValue.calls.count())\n .toBe(1, 'spy method was called once');\n expect(valueServiceSpy.getValue.calls.mostRecent().returnValue)\n .toBe(stubValue);\n});\n\n\n\n

Testing without beforeEach()link

\n

Most test suites in this guide call beforeEach() to set the preconditions for each it() test\nand rely on the TestBed to create classes and inject services.

\n

There's another school of testing that never calls beforeEach() and prefers to create classes explicitly rather than use the TestBed.

\n

Here's how you might rewrite one of the MasterService tests in that style.

\n

Begin by putting re-usable, preparatory code in a setup function instead of beforeEach().

\n\nfunction setup() {\n const valueServiceSpy =\n jasmine.createSpyObj('ValueService', ['getValue']);\n const stubValue = 'stub value';\n const masterService = new MasterService(valueServiceSpy);\n\n valueServiceSpy.getValue.and.returnValue(stubValue);\n return { masterService, stubValue, valueServiceSpy };\n}\n\n\n

The setup() function returns an object literal\nwith the variables, such as masterService, that a test might reference.\nYou don't define semi-global variables (e.g., let masterService: MasterService)\nin the body of the describe().

\n

Then each test invokes setup() in its first line, before continuing\nwith steps that manipulate the test subject and assert expectations.

\n\nit('#getValue should return stubbed value from a spy', () => {\n const { masterService, stubValue, valueServiceSpy } = setup();\n expect(masterService.getValue())\n .toBe(stubValue, 'service returned stub value');\n expect(valueServiceSpy.getValue.calls.count())\n .toBe(1, 'spy method was called once');\n expect(valueServiceSpy.getValue.calls.mostRecent().returnValue)\n .toBe(stubValue);\n});\n\n\n

Notice how the test uses\ndestructuring assignment\nto extract the setup variables that it needs.

\n\nconst { masterService, stubValue, valueServiceSpy } = setup();\n\n\n

Many developers feel this approach is cleaner and more explicit than the\ntraditional beforeEach() style.

\n

Although this testing guide follows the traditional style and\nthe default CLI schematics\ngenerate test files with beforeEach() and TestBed,\nfeel free to adopt this alternative approach in your own projects.

\n

Testing HTTP serviceslink

\n

Data services that make HTTP calls to remote servers typically inject and delegate\nto the Angular HttpClient service for XHR calls.

\n

You can test a data service with an injected HttpClient spy as you would\ntest any service with a dependency.\n\nlet httpClientSpy: { get: jasmine.Spy };\nlet heroService: HeroService;\n\nbeforeEach(() => {\n // TODO: spy on other methods too\n httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);\n heroService = new HeroService(httpClientSpy as any);\n});\n\nit('should return expected heroes (HttpClient called once)', () => {\n const expectedHeroes: Hero[] =\n [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\n\n httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));\n\n heroService.getHeroes().subscribe(\n heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'),\n fail\n );\n expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');\n});\n\nit('should return an error when the server returns a 404', () => {\n const errorResponse = new HttpErrorResponse({\n error: 'test 404 error',\n status: 404, statusText: 'Not Found'\n });\n\n httpClientSpy.get.and.returnValue(asyncError(errorResponse));\n\n heroService.getHeroes().subscribe(\n heroes => fail('expected an error, not heroes'),\n error => expect(error.message).toContain('test 404 error')\n );\n});\n\n

\n
\n

The HeroService methods return Observables. You must\nsubscribe to an observable to (a) cause it to execute and (b)\nassert that the method succeeds or fails.

\n

The subscribe() method takes a success (next) and fail (error) callback.\nMake sure you provide both callbacks so that you capture errors.\nNeglecting to do so produces an asynchronous uncaught observable error that\nthe test runner will likely attribute to a completely different test.

\n
\n

HttpClientTestingModulelink

\n

Extended interactions between a data service and the HttpClient can be complex\nand difficult to mock with spies.

\n

The HttpClientTestingModule can make these testing scenarios more manageable.

\n

While the code sample accompanying this guide demonstrates HttpClientTestingModule,\nthis page defers to the Http guide,\nwhich covers testing with the HttpClientTestingModule in detail.

\n\n \n
\n\n\n" }