【发布时间】:2020-12-11 11:35:53
【问题描述】:
我正在尝试为使用两种服务和一种表单的 Angular 组件编写 Jasmine 单元测试(使用 Karma)。测试教程 (like this one from the Angular Docs) 仅展示了如何使用一项服务测试组件,但不知何故我无法使其与更复杂的组件一起工作:
我的组件:user-login.component.ts:
该组件有一个登录表单,用户可以在其中输入他的凭据。 OnSubmit 我将提供的凭据发送到身份验证服务,该服务处理对我的 API 的 http 请求。如果来自 API 的 http 响应的状态为 200,它将包含一个登录令牌 (JWT),我将其存储在另一个名为 TokenStorageService 的服务中:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { TokenStorageService } from '../../../_services/token-storage.service';
import { AuthenticationService } from '../../../_services/authentication.service';
import { AuthRequest } from '../../../_models/authRequest';
@Component({
selector: 'app-user-login',
templateUrl: './user-login.component.html',
styleUrls: ['./user-login.component.scss']
})
export class UserLoginComponent implements OnInit {
loginForm: FormGroup;
constructor(private formBuilder: FormBuilder,
private tokenStorage: TokenStorageService,
private authService: AuthenticationService) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.compose([Validators.required])],
password: ['', Validators.required]
});
}
onSubmit() {
this.authService.login({
userName: this.loginForm.controls.username.value,
password: this.loginForm.controls.password.value
})
.subscribe(data => {
if (data.status === 200) {
this.tokenStorage.saveToken(data.body)
console.log("SUCCESS: logged in")
}
}
});
}
}
我的测试:user-login.component.spec.ts:
所以我明白了我在构造函数中提供的三件事(FormBuilder、TokenStorageService 和AuthenticationService)我也必须在我的TestBed 中提供。因为我真的不想为单元测试注入服务,所以我使用的是存根服务。所以我这样做了:
TestBed.configureTestingModule({
imports: [{HttpClientTestingModule}],
providers: [{provide: FormBuilder}, { provide: TokenStorageService, useValue: tokenStorageServiceStub }, { provide: AuthenticationService, useValue: authenticationServiceStub }
整个测试如下所示:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserLoginComponent } from './user-login.component';
import { FormBuilder } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TokenStorageService } from 'src/app/_services/token-storage.service';
import { AuthenticationService } from 'src/app/_services/authentication.service';
describe('UserLoginComponent', () => {
let component: UserLoginComponent;
let fixture: ComponentFixture<UserLoginComponent>;
let tokenStorageServiceStub: Partial<TokenStorageService>;
let authenticationServiceStub: Partial<AuthenticationService>;
// let tokenStorageService;
// let authenticationService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [{HttpClientTestingModule}],
providers: [{provide: FormBuilder}, { provide: TokenStorageService, useValue: tokenStorageServiceStub }, { provide: AuthenticationService, useValue: authenticationServiceStub } ],
declarations: [ UserLoginComponent ]
})
fixture = TestBed.createComponent(UserLoginComponent);
component = fixture.componentInstance;
// tokenStorageService = TestBed.inject(TokenStorageService);
// authenticationService = TestBed.inject(AuthenticationService);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我评论了 4 行,因为我认为它们是错误的,但在 the Angular Docs example 他们也在注入真正的服务,即使他们说他们不想在测试中使用真正的服务。我不明白文档示例中的那部分?
但无论哪种方式,我都会不断收到此错误消息:
由于错误说明了有关@NgModule 的内容,我认为这可能与我的app.module.ts 文件有关?这是我的app.module.ts:
@NgModule({
declarations: [
AppComponent,
SidebarComponent,
UsersComponent,
DetailsComponent,
ProductsComponent,
UploadFileComponent,
GoogleMapsComponent,
AddUserComponent,
ProductFormComponent,
UserLoginComponent,
EditUserComponent,
ProductDetailsComponent,
MessagesComponent,
MessageDetailsComponent,
ChatComponent,
UploadMultipleFilesComponent,
InfoWindowProductOverviewComponent,
AddDormComponent,
AddProductComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
ImageCropperModule,
DeferLoadModule,
//Angular Material inputs (spezielle UI Elemente)
MatDatepickerModule,
MatInputModule,
MatNativeDateModule,
MatSliderModule,
MatSnackBarModule,
MatSelectModule,
MatCardModule,
MatTooltipModule,
MatChipsModule,
MatIconModule,
MatExpansionModule,
MDBBootstrapModule,
AgmCoreModule.forRoot({
apiKey: gmaps_environment.GMAPS_API_KEY
})
],
providers: [
UploadFileService,
{provide: MAT_DATE_LOCALE, useValue: 'de-DE'},
{provide:HTTP_INTERCEPTORS, useClass:BasicAuthHttpInterceptorService, multi:true},
],
bootstrap: [AppComponent],
})
export class AppModule { }
【问题讨论】:
-
spec 文件中提供者 {provide: FormBuilder} 中是否缺少 useClass 或 use 值?
-
我认为对于 FormBuilder,您不必添加 'useValue'
-
尝试移除FormBuilder并导入ReactiveFormModule
-
我现在试过了,但没用。我也在使用 FormBuilder 的其他组件的测试中尝试过,但似乎没有什么不同。
-
我也尝试做一个 stackblitz 的例子,但似乎不可能在 stackblitz 中进行测试。
标签: angular unit-testing jasmine karma-jasmine