angular - 如何在 ngOnInit 中测试函数
问题描述
我的组件类很简单。它从父组件获取输入,并根据该输入从ngOnInit
My Component 类中的 ENUM 解析参数:
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
即使在调用更改检测之后,输入也会出现。
解决方案
问题是因为SpyOn
该部分中的一个声明beforEach()
。由于模拟函数没有返回任何数据,因此返回值不断获取undefined
。问题陈述如下,我必须评论该spyOn
陈述:
beforeEach( () => {
// spyOn(component, 'findServiceType');
});
删除此功能并正常工作。
推荐阅读
- asp.net-mvc - 如何普遍创建从泛型类型继承的存储库?
- c - `int arr[3] = {1, 2, 3};` 是否预留了两块内存?
- python - 使用架构创建一个空数据框:TypeError: array() argument 1 must be an unicode character, not StringType
- c - 如何从 20 个样本中找到正弦波的幅度和频率?
- postgresql - 是否需要从存储的 plpgsql 函数中关闭返回的 refcursor?
- reactivesearch - AppBase / 反应式搜索:从 id 数组中过滤的策略
- python - 列出一组给定数字的组合及其总数
- java - 向从 Firebase 实时数据库检索的号码发送短信
- dart - 如何在 Flutter 中使用 bloc 模式在 UI 上显示函数回调和错误?
- haskell - 如何为具有不同构造函数 Haskell 的类型实例化 Eq(或任何类)