我正在尝试使用注入设置单元测试。但我不知道如何设置参数。
被测试类的构造函数(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();
}));
});
HttpClientTestingModule
来测试服务中的HttpClient
用法。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();
});
});