Angular 5 Jasmine Error: Expected one matching request for criteria found none

后端 未结 4 1419
一生所求
一生所求 2021-01-04 05:34

I have a very simple service call and a jasmine test for it.

Service call:

myServiceCall(testId: number) : void {
    const url = `${this.url}/param         


        
相关标签:
4条回答
  • 2021-01-04 06:16

    You are already calling httpMock.verify(), which should fail if there are unexpected requests, and log some information about those requests to the console. If your expectOne failed with a "found none", and verify did not fail, then your service must not actually have called http.put(). Add some logging or step through the test in a debugger to see what's actually happening.

    As other answers have pointed out, this could be due to timing issues. Your service call does not return an Observable or Promise so your spec can't tell when it finishes. This means you'll have to manipulate time with waitForAsync or fakeAsync.

    0 讨论(0)
  • 2021-01-04 06:18

    My problem is solved. After I added to params to the URL (if you use params).

    let results = { param: 'results', value: '50' };
    url = `${api.url}${route.url}?${results.param}=${results.value}`;
    

    HttpTestingController always display only URL without params, but if used expectOne(url) it use a URL with query string like that: http://example.com/path/to/page?name=ferret&color=purple

    0 讨论(0)
  • 2021-01-04 06:22

    You've read the error wrong, let me rephrase it for you :

    Error: Expected one matching request [...], found none.

    This simply means that your URL doesn't match.

    What you can do is add a console log of your URL with

    console.log(req.request.url);
    

    Or you can simply try to match the request.

    Other solution : since you rely on environment variables, you can run this test instead :

    expect(req.request.url.endsWith("/paramX/123")).toEqual(true);
    
    0 讨论(0)
  • 2021-01-04 06:22

    You should have your test inside a fakeAsync and call tick() at the end of your test. like

    it('should call myServiceCall', inject([MyService], fakeAsync((service: MyService) => {
        let testId = undefined;
        service.myServiceCall(testId);
        let req = httpMock.expectOne(environment.baseUrl + "/paramX/123");
    
        expect(req.request.url).toBe(environment.baseUrl + "/paramX/123");
        expect(req.request.body).toEqual({});
    
        req.flush({});
        httpMock.verify();
        tick();
    
    })));
    
    0 讨论(0)
提交回复
热议问题