dimanche 21 août 2016

service testing http mock

Got following service:

/* imports */
@Injectable()
export class ProductsService extends ItemService {

  constructor(private attributeService: AttributesService, private http: Http) {
    console.log("constructor products");
    this.http.get(PRODUCTS_ENDPOINT).subscribe(val => {
      console.log("get from REST endpoint");
    });

    Observable.combineLatest(
      this.attributeService.getItems(),
      this.http.get(PRODUCTS_ENDPOINT)
    ).subscribe(v => {/*some action*/});
  }

  public getItems(): Observable<Array<Product>> {
    return <ReplaySubject<Product[]>>this.items;
  }
}

and following test:

/* imports */
describe("Products service", () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        productsProviders()
      ],
    });
  });

  describe("rest functions", () => {
    it("retrieves objects when calling getItems", inject([ProductsService, MockBackend], fakeAsync((service, mockBackend) => {
      let res: Product[];
      mockBackend.connections.subscribe(c => {
        console.log("BACKEND HIT");
      });
      service.getItems();
      tick();
      console.log("test");
    })));
  });
});

helper.ts:

/* imports */
export function attributeTypesProviders(): Array<any> {
    return [
      BaseRequestOptions,
      MockBackend,
      AttributeTypesService,
      provide(Http, {
        useFactory: (mockBackend: ConnectionBackend,
                     defaultOptions: BaseRequestOptions) => {
          return new Http(mockBackend, defaultOptions);
        }, deps: [MockBackend, BaseRequestOptions]}),
      provide(ReconnectingSocketService, {useClass: ReconnectingSocketServiceMock})
    ];
  }

export function attributesProviders(): Array<any> {
  return [
    attributeTypesProviders(),
    AttributesService,
  ];
}

export function productsProviders(): Array<any> {
  return [
    attributesProviders(),
    ProductsService,
  ];
}
export function mockGetItems(backend: MockBackend, req: Request): ResponseOptions {
  let response: ResponseOptions;
/* assigning to response depending on get url */
  return response;
}

As you can see I am trying to test if my service is correctly extracting array from json, which I am trying to provide in mockGetItems(). I expect, that when I will run test I would get following output:

constructor products <<< from service
BACKEND HIT <<< from mock backend
BACKEND HIT
BACKEND HIT (triple times because of service dependency)
test

Instead of that I am getting:

LOG: 'constructor products'
LOG: 'test'

As you can see my hits does not touch mocked backend. My question is: Why? What Am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire