首页 > 解决方案 > 为什么 @cacheable 装饰器使我的错误测试在 Jasmine 中失败

问题描述

我有这个 puesto.service.ts 服务,在 getPuestos() 函数之前有一个 @cacheable 装饰器,我正在对该函数进行三个测试,其中一个是错误测试,另一个是返回数据,但是这两个失败了。我尝试注释掉 @cacheable 装饰器,这样它就可以正确运行所有测试。如果有@cacheable,你能告诉我如何做这些测试吗?有没有办法只在 spec.ts 中禁用 @cacheable?

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


import { Observable } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';

import { HttpErrorHandler, HandleError } from './http-error-handler.service';

import { ModelService } from './model.service';
import { Puesto } from '../models/puesto';

import { Cacheable } from 'ngx-cacheable';

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token'
    })
  };

  
@Injectable({
    providedIn: 'root',
  })
  export class PuestoService {
      apiUrl = 'api/puestos';  // URL to web api
      apiName = 'Puesto';
  
    private handleError: HandleError;
  
    constructor(
      private http: HttpClient,
      private modelService: ModelService,
      httpErrorHandler: HttpErrorHandler) {
      this.handleError = httpErrorHandler.createHandleError(this.apiName + 'Service');
    }

    @Cacheable()
    getPuestos(): Observable<Puesto[]> {
      return this.http.get<Puesto[]>(this.apiUrl)
        .pipe(
          catchError(this.handleError('get' + this.apiName, []))
        );
    }
}

我在规范中的测试是:

import { TestBed } from '@angular/core/testing';
import { PuestoService } from './puesto.service';
import { ModelService } from './model.service';
import { HttpErrorHandler } from './http-error-handler.service';
import { MessageService } from './message.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { Puesto } from '../models/puesto';


describe('PuestoService', () => {
    let httpTestingController: HttpTestingController;
    let service: PuestoService;
    let apiUrl = 'api/puestos';  // URL to web api
    let apiName = 'Puesto';

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule
            ],
            providers: [
                PuestoService,
                ModelService,
                HttpErrorHandler,
                MessageService
            ]
        });
    });

    beforeEach(() => {
        httpTestingController = TestBed.get(HttpTestingController);
        service = TestBed.get(PuestoService);
    });

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

    it('Should created PuestoService', () => {
        expect(service).toBeTruthy();
    });

    it('Test to Contructor', () => {
        let puesto = new Puesto();
        expect(puesto).toBeDefined();
    });

    it('getPuestos should use GET to retrieve data', () => {
        service.getPuestos().subscribe();
        const testRequest = httpTestingController.expectOne(apiUrl);
        expect(testRequest.request.method).toEqual('GET');
    });

    it('getPuestos should return expected data', (done) => {
        const expectedData: Puesto[] = [];

        service.getPuestos().subscribe(data => {
            expect(data).toEqual(expectedData);
            done();
        });

        const testRequest = httpTestingController.expectOne(apiUrl);

        testRequest.flush(expectedData);
    });

    it('getPuestos should return an empty object on error', (done) => {
        const expectedData: Puesto[] = []

        service.getPuestos().subscribe(data => {
            expect(data).toEqual(expectedData);
            done();
        });

        const testRequest = httpTestingController.expectOne(apiUrl);

        testRequest.flush('error', { status: 500, statusText: 'Broken Service' });
    });
});

让我失败的部分是:

it('getPuestos should return expected data', (done) => {
    const expectedData: Puesto[] = [];

    service.getPuestos().subscribe(data => {
        expect(data).toEqual(expectedData);
        done();
    });

    const testRequest = httpTestingController.expectOne(apiUrl);

    testRequest.flush(expectedData);
});
 it('getPuestos should return an empty object on error', (done) => {
    const expectedData: Puesto[] = []

    service.getPuestos().subscribe(data => {
        expect(data).toEqual(expectedData);
        done();
    });

    const testRequest = httpTestingController.expectOne(apiUrl);

    testRequest.flush('error', { status: 500, statusText: 'Broken Service' });
});

我在此处向您展示捕获 输入图像描述中的错误

如果我对装饰器@cacheable 发表评论,则测试会完美运行。如您在此处看到的:在此处 输入图像描述

标签: angularjasminekarma-jasminenodejs-serverjasmine2.0

解决方案


推荐阅读