【发布时间】:2019-03-26 09:47:38
【问题描述】:
我正在尝试在 Angular 6 中对“添加对象”(添加菜)组件进行单元测试。使用我当前的代码,我收到错误 “无法读取未定义的属性 'dishForm'”。
那么,似乎 DishAddComponent 没有被识别为要测试的组件?有人可以帮我解决这个问题吗?提前致谢!
我还尝试(以及其他)将异步添加到 beforeEach,如下所述:Angular 2 Testing - Component Instance is undefined,但它不起作用。
要进行单元测试的 Angular 组件:
export class DishAddComponent implements OnInit {
public dishForm: FormGroup;
constructor(private dishService: DishService,
private formBuilder: FormBuilder,
private router: Router) { }
ngOnInit() {
// define dishForm (with empty default values)
this.dishForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.maxLength(30), Validators.pattern('[a-zA-Z :]*')]],
country: [''],
ingredients: this.formBuilder.array([]),
recipe: ['', [Validators.required, Validators.minLength(50)]],
}, { validator: CustomValidators.DishNameEqualsCountryValidator });
}
addIngredient(): void {
let ingredientsFormArray = this.dishForm.get('ingredients') as FormArray;
ingredientsFormArray.push(IngredientSingleComponent.createIngredient());
}
addDish(): void {
if (this.dishForm.dirty && this.dishForm.valid) {
let dish = this.dishForm.value;
this.dishService.addDish(dish)
.subscribe(
() => {
this.router.navigateByUrl('/dishes');
});
}
}
}
Jest 中的单元测试:
describe('DishAddComponent', () => {
let component: DishAddComponent;
let fixture: ComponentFixture<DishAddComponent>;
let formGroup: FormGroup;
let formBuilderMock: any;
let dishServiceMock: any;
beforeEach(() => {
formBuilderMock = {
group: jest.fn().mockName('formBuilderMock.group'),
array: jest.fn().mockName('formBuilderMock.array')
};
dishServiceMock = {
addDish: jest.fn().mockName('dishServiceMock.addDish')
};
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule, FormsModule, RouterTestingModule.withRoutes(routes)],
declarations: [ DishAddComponent, IngredientSingleComponent ],
providers:
[
{ provide: FormBuilder, useValue: formBuilderMock },
{ provide: FormGroup, useValue: formGroup },
{ provide: DishService, useValue: dishServiceMock }
]
});
fixture = TestBed.createComponent(DishAddComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('form invalid when empty', () => {
(console).log(component);
expect(component.dishForm.valid).toBeFalsy();
});
});
编辑: 如果我使用下面的代码,我也会收到错误:
DishAddComponent › 应该创建
期望(收到).toBeTruthy()
收到:未定义
it('should create', () => {
expect(component).toBeTruthy();
});
【问题讨论】:
-
尝试使用默认测试,即
should create → expect(component).toBetruhty();。看看它是否有效。另外,请发布您面临的错误。 -
感谢您的快速回复!我已经编辑了我的问题。如果我将其更改为默认测试,我会收到以下错误: ● DishAddComponent › 应该创建 ● expect(received).toBeTruthy() ● Received: undefined
标签: angular unit-testing undefined