Ошибка: не ожидается открытых запросов, найдено 1 (угловой) - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь создать тестовый пример для службы в angular6 .Служба имеет несколько различных http методов запроса (get, put, post и т. Д.), И внутри них выполняется вызов API, который выбирает соответствующий ответ.Я пытаюсь создать тестовые случаи, когда создается ложный запрос http и возвращается ответ.Тем не менее, я следовал Tutorial , который, по-видимому, помогает мне делать именно то, что я хочу.

Однако, когда я запускаю тестовый пример для службы, он выдает мне следующую ошибку (я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)

Я пытался просмотреть Это решение, а также Это одно, но длябезрезультатно.

Вот код моей службы:

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

Контрольный пример :

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('')
});

1 Ответ

0 голосов
/ 28 ноября 2018

решено Я забыл добавить запрос ожидаемого вызова API для тестового случая:

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

Очень наивное наблюдение, извинения за неудобства.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...