2017-11-27 10 views
1

私はAngular 5 Projectで作業しています。 2.1/2.2の初期段階からAngular2 +のビジネスを離れました。HttpClientを使用したサービスの角度検査が機能しません

だから私は、しかし、私のテストをして失敗し続け、パブリックAPIを呼び出して、このサービスを持っている:Error: Expected one matching request for criteria "Match URL: http://api.icndb.com/jokes/random/10", found none.

コード:

fact.service.spec.ts

import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"; 
import {TestBed, inject} from "@angular/core/testing"; 
import {FactService} from "./fact.service"; 
import {Fact} from "../models/fact"; 
import {FactHttpResponse} from "../models/factHttpResponse"; 

describe("FactService",() => { 
    let factService: FactService; 
    let httpMock: HttpTestingController; 

    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      imports: [HttpClientTestingModule], 
      providers: [FactService], 
     }); 
     httpMock = TestBed.get(HttpTestingController); 
     factService = TestBed.get(FactService); 
    }); 

    // TODO: Something is going wrong with this test get some help online 
    it("Should be able to retrieve Facts in subscription when calling loadFacts", (done) => { 
    const factList: Fact[] = [ 
     {id: 1, joke: "a"}, 
     {id: 2, joke: "a"}, 
    ]; 

    const factResponse: FactHttpResponse = { value: factList}; 

    factService.subscribe(val => { 
     expect(val).toEqual(factList); 
     done(); 
    }); 

    const mockRequest = httpMock 
     .expectOne(factService.CHUCK_NORRIS_API.replace("{count}", "10")); 
    expect(mockRequest.request.method).toEqual('GET'); 

    factService.loadFacts(); 

    mockRequest.flush(factResponse); 
}); 

afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => { 
    httpMock.verify(); 
})); 
}); 

事実.service.ts

コードは実際に動作しますが、私は見えませんそれをテストする:-(。私がverifyOneを削除すると、実際にはエラーで言及された全く同じURLへのオープン要求について文句を言います。

+0

すべてのフレームワーク侵入を行わずに手作業で書くのはなぜでしょうか?それは、オブジェクトのメソッドをスタブし、それをアサーションし、サービスを直接インスタンス化することだけです。 –

+0

しかし、これは素晴らしいテストフレームワークではありません。要求される定型文の量は自明ではありません。また、観察可能なものを簡単にスタブすることができます。必要なものはすべてサブジェクトです。 –

答えて

2

HTTPリクエストを生成するのはfactService.loadFacts()なので、最後の3つのテストが順不同です。

describe(...,() => { 
    it(...,() => { 
     ... 

     // queue up the http request in the mockHttp request queue 
     factService.loadFacts(); 

     // verify that there is now one (and only one) request queued up 
     const mockRequest = httpMock 
      .expectOne(factService.CHUCK_NORRIS_API.replace("{count}", "10")); 
     expect(mockRequest.request.method).toEqual('GET'); 

     // satisfy the pending request in the mockHttp request queue 
     mockRequest.flush(factResponse); 
    }); 

    // Bonus tip: you already have mockHttp in the describe() scope. Simplify: 
    afterEach(() => { 
     // verify there are no unsatisfied requests in the mockHttp queue 
     httpMock.verify(); 
    }); 
}); 
関連する問題