【问题标题】:Expected one matching request for criteria预期有一个匹配条件的请求
【发布时间】:2018-12-07 11:12:50
【问题描述】:

我正在尝试按照角度指南使用新的 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 的其他重载,但没有运气:/提前感谢您的帮助!

【问题讨论】:

  • 面临同样的问题。如果您找到解决方案,请更新
  • 我解决了我的问题,我只是在 url 的末尾添加了一个斜杠,删除斜杠后,它起作用了。希望有帮助!

标签: javascript angular unit-testing


【解决方案1】:
  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....
      });
  });

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2021-02-20
    • 1970-01-01
    • 2023-03-22
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多