【问题标题】:Angular Unit Testing injecting parametersAngular 单元测试注入参数
【发布时间】:2019-04-26 16:38:37
【问题描述】:

我正在尝试使用注入设置单元测试。但我不确定如何设置参数。

正在测试的类(auth.service.ts)的构造函数是:

constructor(private http : HttpClient, private token: TokenStorage) {}

单元测试类 (auth.service.spec.ts)

import { TestBed, inject } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClient, HttpHandler, HttpClientModule } from '@angular/common/http';
import { TokenStorage } from './token.storage';

describe('AuthService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [AuthService, HttpClient, HttpHandler, HttpClientModule, TokenStorage]
        });
    });
    it('should be created', inject([AuthService], (service: AuthService) => {
        expect(service).toBeTruthy();
    }));
});

【问题讨论】:

标签: angular unit-testing karma-jasmine inject


【解决方案1】:
  1. 您需要使用HttpClientTestingModule 来测试您的服务中的HttpClient 使用情况。
  2. 为TokenStorage 使用假值,否则您的单元测试将成为集成测试。

另见angular - Testing services with the TestBed

import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { AuthService } from './auth.service';
import { TokenStorage } from './token.storage';

describe('AuthService', () => {
  let injector: TestBed;
  let service: AuthService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        AuthService,
        { provide: TokenStorage, useValue: {} }
      ]
    });
    injector = getTestBed();
    service = injector.get(AuthService);
    httpMock = injector.get(HttpTestingController);
  });

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

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

【讨论】:

  • 我收到以下错误:错误:StaticInjectorError(DynamicTestModule)[AuthService -> HttpClient]: 错误属性:Object({ ngTempTokenPath: null, ngTokenPath: ['AuthService', Function ] })跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2021-06-28
  • 2016-05-29
  • 2013-03-23
  • 2018-12-27
相关资源
最近更新 更多