预期有一个符合条件的要求

时间:2018-06-28 11:24:57

标签: javascript angular unit-testing

我正在尝试按照角度指南使用新的HTTP客户端测试服务。我收到以下错误消息,Expected one matching request for criteria "Match method: GET, URL: http://localhost:8080/services/shift/2016-12-01", found none.我将代码放在下面,不太确定我要去哪里哪里

单元测试

import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';

import { ShiftService } from './shift.service';

let service: ShiftService;
let backend: HttpTestingController;

describe('ShiftService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        ShiftService,
        HttpClient,
        HttpHandler
      ],
      imports: [HttpClientTestingModule]
    });

    service = TestBed.get(ShiftService);
    backend = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    backend.verify();
  });

  describe('When the getShift method is invoked', () => {
    it('should make a GET request to the services/shift endpoint', async() => {
      service.getShift().subscribe();
      backend.expectOne({
        url: 'http://localhost:8080/services/shift/2016-12-01',
        method: 'GET'
      });
    });
  });
});

服务

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class ShiftService {
  constructor(private http: HttpClient) { }

  public getShift = () => {
    return this.http.get('http://localhost:8080/services/shift/2016-12-01');
  }
}

我确保已预订getShift()方法,并且正在使用HTTPTestingController。我还尝试了HttpTestingController的其他重载,但没有运气:/谢谢您提前提供的帮助!

1 个答案:

答案 0 :(得分:0)

  use describe as below

 describe('When the getShift method is invoked', () => {
    it('should make a GET request to the services/shift endpoint', async() => {
        const path = '/testPath';
        service.get(path).subscribe(response => {
            expect(response).toBeTruthy();
        });

        const httpRequest = httpMock.expectOne(
        (req: HttpRequest<any>) => req.urlWithParams === path); 

     // write your expect criteria here....
      });
  });