我正在尝试在名为AlbumInfoComponent
的Angular组件上运行业力测试。在此组件中,我有一个名为getStyles()
的函数,该函数执行以下操作:
getStyles() {
return {
"background-image":'url('+this.data.images[1].url+')'
}
}
它使用一个名为data
的变量,其初始化为:private user: {} = {}
我有一个仅运行默认should create
测试的测试。尽管由于某种原因在运行测试时得到TypeError: Cannot read property 'images' of undefined
。我最初的想法是,由于Angular不知道数据中有一个名为images
的值,因此它将失败。因此,我尝试将组件设置为等于模拟组件数据。这是我的测试代码:
describe('AlbumInfoComponent', () => {
let component: AlbumInfoComponent;
let fixture: ComponentFixture<AlbumInfoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LandingComponent, FaIconComponent, HomeComponent, LoginComponent, AlbumInfoComponent, RecentReleasesComponent, QueueComponent, SearchComponent, TitleComponent, UserComponent, SearchBarComponent, RecentReleaseComponent, YourQueueComponent ],
imports: [FormsModule, HttpClientTestingModule, RouterTestingModule.withRoutes([]), MatSnackBarModule ],
providers: [InfoService, HttpClient, TokenService ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AlbumInfoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
component.data = {
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/ab67616d0000b273626d2ce1fb80955645d4d787",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/ab67616d00001e02626d2ce1fb80955645d4d787",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/ab67616d00004851626d2ce1fb80955645d4d787",
"width": 64
}
]
}
expect(component).toBeTruthy();
});
});
是否有一种方法可以强制数据变量等于模拟数据来修复错误?
答案 0 :(得分:0)
此答案有效:https://github.com/ngrx/platform/issues/1546#issuecomment-461945741
我们需要在每次测试后销毁灯具。这样做:
afterEach(() => {
fixture.destroy();
});