角度单位测试注入参数

问题描述 投票:0回答:1

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

被测试类的构造函数(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个回答
0
投票
  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();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.