我正在尝试为方法编写单元测试:
public addCred:boolean=true;
public credName:any;
public addMachineCredential(credentialForm: NgForm) {
this.addCred = true;
this.credName = credentialForm.value.name;
}
在我的测试课程中:
it('should add machine credential', () => {
var machineCredentialForm: NgForm = new NgForm(null, null);
machineCredentialForm.controls['name'].setValue('name');
machineCredentialForm.controls['username'].setValue('username');
machineCredentialForm.controls['password'].setValue('password');
component.addMachineCredential(machineCredentialForm);
expect(component.addCred).toBe(true);
expect(component.credName).toBe("name");
});
我收到错误:TypeError: Cannot read property 'setValue' of undefined
如何测试函数“addMachineCredential”?
为了能够对模块进行单元测试,您应该使用ReactiveForms而不是评论中提到的模板驱动表单。我进行了重构(并根据您发布的代码段提出了一个示例...)并想出了一个解决方案:
因此,这是一种可以重构代码以使其工作的方法。
你的组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-unit-test',
template: `
<p>Works</p>
`,
styleUrls: ['./unit-test.component.css']
})
export class UnitTestComponent {
public addCred: boolean = true;
public credName: any;
form: FormGroup = new FormGroup({
name: new FormControl('', [])
});
constructor() {}
public addMachineCredential(credentialForm: FormGroup) {
this.addCred = true;
this.credName = credentialForm.controls.name.value;
}
}
你的spec文件:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { UnitTestComponent } from './unit-test.component';
fdescribe('UnitTestComponent', () => {
let component: UnitTestComponent;
let fixture: ComponentFixture<UnitTestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [UnitTestComponent],
imports: [FormsModule, ReactiveFormsModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UnitTestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should add machine credential', () => {
component.form.controls.name.setValue('name');
component.addMachineCredential(component.form);
expect(component.addCred).toBe(true);
expect(component.credName).toBe('name');
});
});
不要忘记你的组件模块必须声明ReactiveFormsModule,所以..
你的模块:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { UnitTestComponent } from './Questions/unit-test/unit-test.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
UnitTestComponent,
FormsModule,
ReactiveFormsModule
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
希望能帮助到你。