Test Angular2 service with mock backend

前端 未结 2 603
说谎
说谎 2021-01-02 05:35

First: I\'m aware that Angular2 is in alpha and changing frequently.

I\'m working with Angular2. There is an injectable service with http dependency that I\

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 06:15

    I just found this topic while looking for testing tips but I can't see a direct answer to that so...

    This one is based on Angular RC.1

    Testing service with Mock Backend

    Let's say your service is:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    
    @Injectable()
    export class CoreService {
      constructor(private http: Http) {}
    
      getStatus() {
        return this.http.get('/api/status');
      }
    }
    

    Test to the service above will look like this:

    import {
      beforeEach,
      beforeEachProviders,
      describe,
      expect,
      inject,
      it,
    } from '@angular/core/testing';
    
    import { provide } from '@angular/core';
    import { BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
    import { MockBackend, MockConnection } from '@angular/http/testing';
    
    describe('Http', () => {
    
      beforeEachProviders(() => [
        CoreService,
        BaseRequestOptions,
        MockBackend,
        provide(Http, {
          useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        })
      ]);
    
      beforeEach(inject([MockBackend], (backend: MockBackend) => {
        const baseResponse = new Response(new ResponseOptions({ body: 'status' }));
        backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
      }));
    
      it('should return response when subscribed to getStatus',
        inject([CoreService], (coreService: CoreService) => {
          coreService.getStatus().subscribe((res: Response) => {
            expect(res.text()).toBe('status');
          });
        })
      );
    
    })
    

    What you really have to look at there is to have proper mocking in beforeEachProviders. Test itself is quite simple and ends up with subscribing to the service method.


    Note: Don't forget to set base providers first:

    import { setBaseTestProviders } from '@angular/core/testing';
    import {
      TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
      TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
    } from '@angular/platform-browser-dynamic/testing';
    
    setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
    

提交回复
热议问题