javascript - 预期有一个符合条件的请求

标签 javascript angular unit-testing

我正在尝试按照 Angular 指南使用新的 HTTP 客户端测试服务。我收到以下错误,应为标准“匹配方法:GET,URL:http://localhost:8080/services/shift/2016-12-01”的一个匹配请求,但找不到。我已将我的代码放在下面,不太确定我哪里出错了

单元测试

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 的其他重载,但没有成功:/提前感谢您的帮助!

最佳答案

  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....
      });
  });

关于javascript - 预期有一个符合条件的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081718/

相关文章:

javascript - 关联 2 个数组之间的项目

javascript - 如何修复拖动时数据表中标题的设计

css - 更改类名时 matInput 格式的格式更改

java - 在 VS Code 中哪里设置 JUnit 的 vmArgs?

ruby-on-rails - 在类之间共享 Rspec 测试

javascript - 无法在 VS 中的 C# ASP.NET MVC 应用程序中加载 Content & Script 文件夹中的任何文件

javascript - Jquery 或 JavaScript :Assigning the Textarea value to hidden field

javascript - 使用 XivelyJS 将 JS 值发送到 xively

javascript - 获取给定半径内以及给定纬度和经度(以米为单位)的纬度和经度

java - 使用 gradle 为各个单元测试生成 Jacoco 代码覆盖率报告