在Angular中,单元测试无法读取属性的问题通常是因为没有正确初始化组件或模块。
以下是几种可能的解决方法:
beforeEach
钩子函数初始化组件或模块:import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should have a defined property', () => {
expect(component.property).toBeDefined();
});
});
TestBed.createComponent
手动创建组件或模块:import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.property = 'test'; // 初始化属性
fixture.detectChanges();
});
it('should have a defined property', () => {
expect(component.property).toBeDefined();
});
});
ngOnInit
钩子函数初始化属性:import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my',
template: '{{ property }}
'
})
export class MyComponent implements OnInit {
property: string;
ngOnInit(): void {
this.property = 'test';
}
}
这样,单元测试就可以正确读取属性了。
请注意,以上代码示例仅为演示目的,实际情况可能需要根据具体组件或模块的需求进行适当的修改。