【问题标题】:angular 6 unit testing on http service errors关于 http 服务错误的 Angular 6 单元测试
【发布时间】:2018-10-19 10:31:52
【问题描述】:

我在尝试测试我的一项服务时遇到错误。

该服务有一个在服务器上发出 POST 请求然后返回数据的方法,是的,我知道为什么是 POST 而不是 GET。

我需要说我不能使用身份验证服务,因为使用我的登录名然后我从服务器获取令牌。 由于我无法登录获取令牌,所有请求均无效。

如何在不向服务器发出请求的情况下对 HTTP 调用进行单元测试,只使用模拟服务器响应的本地数据。

我的服务是这样的。

inventory.service.ts

  /**
   * GETS THE INVENTORY DATA.
   * @returns Observable of inventory data from the server.
   */
  getInventoryData<T>() {

    const options = { headers: this.getHeaders() };
    const body: AdditionFiltersEntity = this.shared.getAdditionFilters({});
    const url = `${this.shared.baseUrl}/inventory`;

    return this.http.post(url, body, options).pipe(
      tap(val => console.log(`BEFORE MAP: ${val}`)),
      map(res => res.json()),
      catchError(e => this.shared.handleError(e))
    );

  }

问题是因为我有catchError(e =&gt; this.shared.handleError(e)) 这会检查响应在我的情况下是否有错误我有“未授权”状态文本

在我的情况下,我在所有 HTTP 测试中都会遇到这种类型的错误。

状态:401,正常:假,状态文本:“未授权” 但这没关系,因为我是单元测试我无法通过授权部分。

我的单元测试文件是这个。

inventory.service.spec.ts

import { TestBed, async, inject } from '@angular/core/testing';

// Modules
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { MatSnackBarModule } from '@angular/material';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClientModule } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';

// Services
import { InventoryService } from './inventory.service';
import { HelpersService } from '@app-services/helpers/helpers.service';
import { MediatorService } from '@app-services/mediator/mediator.service';
import { AuthService } from '@app-services/auth/auth.service';
import { StorageService } from '@app-services/storage/storage.service';

// Models
import { InventoryEntity } from '@app-models/inventory';



describe('InventoryService', () => {

  // let service: InventoryService;
  let httpMock: HttpTestingController;
  let auth: AuthService;
  // let user: User;

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [ HttpModule, MatSnackBarModule, RouterTestingModule, HttpClientModule,
      HttpClientTestingModule, BrowserAnimationsModule
    ],
      providers: [
        InventoryService, AuthService, HelpersService, MediatorService, StorageService
      ]
    });


    httpMock  = TestBed.get(HttpTestingController);
    auth      = TestBed.get(AuthService);
    localStorage.setItem('store_ids', JSON.stringify([1])); // just set a test id so we gonna get some kind data.

  });


  beforeEach(async(() => {
    TestBed.compileComponents().catch(error => console.error(error));
  }));

  it('should be created', inject([InventoryService], (service: InventoryService) => {
    expect(service).toBeTruthy();
  }));

  // This is where I get the errors
  fit('Should get inventory data', inject([InventoryService], async (service: InventoryService) => {

    await service.getInventoryData().subscribe( (res: InventoryEntity[]) => {

      // get array first element keys.
      const evaluationKeys = ['brand', 'color_code', 'color_tag', 'family', 'frame_size', 'gender', 'provider', 'quantity', 'tag'];
      const keys = Object.keys(res[0]);

      expect(keys).toEqual(evaluationKeys);

    });

  }));


});
  • 谁能向我解释一下如何对像这样的 HTTP 调用进行单元测试 service.getInventoryData().subscribe

  • 以及如何处理认证部分。 身份验证是我所有测试失败的地方。

  • 如果我需要使用模拟数据,如何制作,有人可以给我一个例子吗?

响应应该给我这个数据。

[
  {
    'brand': 'brand-1',
    'color_code': '593',
    'color_tag': 'SILVER',
    'family': 'SOL',
    'frame_size': '54x16x140',
    'gender': 'Unisexe',
    'provider': 'hgg',
    'quantity': 82,
    'tag': '44554'
  }, {
    'brand': 'brand-2',
    'color_code': 'MAU1O1',
    'color_tag': 'BLACK',
    'family': 'SOL',
    'frame_size': '54x17x140',
    'gender': 'Unisexe',
    'provider': 'hgg',
    'quantity': 98,
    'tag': '45445'
  }
]

【问题讨论】:

  • 从您的测试平台配置导入中删除 HttpClientModule
  • 嗨,@Joey Gough 我已将其删除,但无法正常工作。我从响应中得到了同样的错误,它说我未经授权在服务器上发出任何请求。所有请求都必须首先有效,因为我无法登录以从服务器获取令牌,我收到此错误。
  • 您需要决定 - 它是集成/e2e 测试(命中服务器)还是单元测试(模拟响应)。在 UT 不存在这样的问题,您可以自己提供所需的任何东西。
  • @Antoniossss 是单元测试
  • 那你为什么要打真实服务器?

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

正如 cmets 中所建议的,在 单元测试 时,您不必担心您的 http 调用。我希望 API 响应在服务器端单独测试。在测试服务时,我的任务是验证我的服务是否正确完成了它应该做的事情,假设响应可用。如果没有,您可以测试您的服务是否正确处理错误响应)。你可以在jasmine docs阅读更多关于它的信息

所以,在这种情况下,我通常会嘲笑我的回应。您可以使用 jasminespy 来监视服务调用,例如 spy.On(service, 'getInventoryData').and.returnValues(of({your json});

或者,如果您觉得自己有一个非常大的 json,请将其存储在本地资源文件夹中,例如:app/test/resources/response1.json`,然后将其导入您的规范中,例如:

const response: any = require('../test/resources/response1.json');

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2019-03-24
    • 2018-12-11
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多