我的组件类很简单。它接收来自父组件的输入,并根据该输入从ngOnInit
内的ENUM中解析出一个参数
我的Component类:
export class TestComponent implements OnInit {
@Input() serviceType: string;
serviceUrl : string;
ngOnInit() {
this.findServiceType();
}
findServiceType= () => {
if (this.serviceType) {
if (this.serviceType === 't1') {
this.serviceUrl = TestFileEnumConstants.T1_URL;
}else if (this.serviceType === 't2') {
this.serviceUrl = TestFileEnumConstants.T2_URL;
}
}
}
}
describe('testcomponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let mockService = <Serv1>{};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
TestComponent, TestChildComponent],
providers: [
{ provide: MockService, useValue: mockService }
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should create testcomponent', () => {
expect(component).toBeDefined();
});
describe('testType1', () => {
beforeEach( () => {
spyOn(component, 'findServiceType');
});
it('should correctly wire url based on type1', () => {
component.serviceType = 'type1';
fixture.detectChanges();
expect(component.findServiceType).toHaveBeenCalled();
expect(component.serviceUrl).toBe(TestFileEnumConstants.T1_URL)
});
});
}
问题是serviceUrl
没有得到解决,因为'serviceType' - 即使在调用更改检测之后,输入也会变为undefined
。
答案 0 :(得分:1)
您应该创建两个测试而不是一个。第一个测试this.findServiceType();
是否在ngOnInit
上调用,然后是第二个测试findServiceType
的测试。
it('should correctly wire url based on type1', () => {
component.serviceType = 'type1';
component.findServiceType()
expect(component.serviceUrl)
.toBe(TestFileEnumConstants.T1_URL)
});
答案 1 :(得分:0)
问题在于SpyOn
细分中的beforEach()
声明。由于mock函数没有返回任何数据,因此返回值继续获取undefined
。问题陈述如下,我必须评论spyOn
陈述:
beforeEach( () => {
// spyOn(component, 'findServiceType');
});
&#13;
删除此功能并且工作正常。