我收到此错误:
TypeError: Cannot read property 'url' of undefined
这部分代码的原因:
export class ImageCardComponent implements OnInit {
@Input() image: any; // Can be an image or imageToUpload
imageUrls = [];
...
ngOnInit() {
this.imageUrls.push((this.image as any).url);
this.image.outOfSync = true;
}
测试代码
describe('ImageCardComponent', () => {
let component: ImageCardComponent;
let fixture: ComponentFixture<ImageCardComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ImageCardComponent ],
imports: [FormsModule],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ImageCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.image = getImageGetResponseMock().image;
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
模拟数据
export function getImageGetResponseMock() {
return {
id: 1,
image: [
{
id: 2,
height: 90,
width: 160,
format: 'jpg',
url: 'https://i.imgflip.com/mlqo9.jpg?a430032',
tags: ['testTag']
}
]
};
}
我该怎么办呢?我是否需要将我的两个可能的输入合并到一个公共类中,或者是否有办法为测试脚本提供输入的模拟?
imageUrl
未使用值初始化,这意味着如果您尝试在值之前从中获取值,则该值将是未定义的。
您应该模拟测试中所需的对象,然后编写测试用例。
const imageUrl = {image: 'testImage.png', url:'image_url'};
现在在TestBed设置之后,有一个beforeEach块来模拟所需的输入:
beforeEach(() => {
const fixture = TestBed.createComponent(ImageCardComponent );
component = fixture.componentInstance;
component.imageUrl= imageUrl;
});
it('should have image url info', () => {
expect(component.imageUrl).toBeTruthy(); // whatever you have to check for..
)};