错误:预计没有打开的请求,发现 1 (Angular)

Meh*_*Meh 1 javascript jasmine angular

我正在尝试为angular6 中的服务创建一个测试用例。该服务有一堆不同的http请求方法(get, put, post等),并且在其中进行了一个 API 调用,以获取适当的响应。我正在尝试创建模拟http请求并返回响应的测试用例。但是,我遵循了一个教程,它显然可以帮助我做我想做的事。

但是,当我运行该服务的测试用例时,它给了我以下错误(出于隐私目的,我已对输入URL进行GET了审查:

Error: Expected no open requests, found 1: GET https://staging.xxxxxxxxxx.co.uk/rest/v11_1/oauth2/token
    at HttpClientTestingBackend.push../node_modules/@angular/common/fesm5/http/testing.js.HttpClientTestingBackend.verify (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/common/fesm5/http/testing.js:326:1)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/Services/adapter.service.spec.ts:22:13)
    at TestBed.push../node_modules/@angular/core/fesm5/testing.js.TestBed.execute (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/testing.js:1073:1)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/testing.js:1224:29)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:388:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:288:1)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:387:1)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:138:1)
    at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:509:1)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:524:1)
Run Code Online (Sandbox Code Playgroud)

我已经通过尝试浏览解决方案,以及为一个,但无济于事。

这是我的服务的代码:

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import {
  HttpHeaders,
    HttpClient,
    HttpParams,
} from '@angular/common/http';
import { Request, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';

const API_URL = environment.api.host;

@Injectable({
    providedIn: 'root'
})
export class AdapterService {

    constructor(private http: HttpClient, private jwtService: JwtService) {}

    private formatErrors(self: AdapterService) {
        return (res: Response) => {
            return Observable.throw(res);
        };
    }

    private requestHeaders(path: string) {
    let headers;
    if (path !== 'oauth2/token') {
        headers = new HttpHeaders({
          'Accept':  'application/json',
          'Oauth-Token': this.jwtService.getToken()
        })
      }
        return headers;
    }

    get(path: string, params: HttpParams = new HttpParams()): Observable < any > {
    let headers = this.requestHeaders(path);
        return this.http.get(`${API_URL}${path}`, { headers })
            .catch(catchError(this.formatErrors(this)));
    }

    put(path: string, body: Object = {}): Observable < any > {
        return this.http.put(
            `${API_URL}${path}`,
            JSON.stringify(body),
        ).catch(catchError(this.formatErrors(this)));
    }

    post(path: string, body: Object = {}): Observable < any > {
    return this.http.post(
            `${API_URL}${path}`,
            JSON.stringify(body),
        ).catch(catchError(this.formatErrors(this)));
    }

    delete(path): Observable < any > {
    return this.http.delete(
            `${API_URL}${path}`,
        ).catch(catchError(this.formatErrors(this)));
    }
}
Run Code Online (Sandbox Code Playgroud)

测试案例

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { AdapterService } from './adapter.service';

describe('AdapterService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
        HttpClientTestingModule
      ],
      providers: [
        AdapterService
      ]
    });
  });

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

  it('should send a valid get request for token', async(inject([AdapterService, HttpTestingController],
    (service: AdapterService, backend: HttpTestingController) => {
      service.get('oauth2/token').subscribe((next)=>{
        expect(next).toBeDefined();
      });
    })));
//  it('')
});
Run Code Online (Sandbox Code Playgroud)

Meh*_*Meh 5

解决了我忘记在测试用例中为 API 调用添加一个 expectOne 请求:

backend.expectOne( API_URL + 'oauth2/token').flush(null, { status: 200, statusText:'Ok' });

非常幼稚的观察,给您带来的不便敬请谅解。