angular - 使用@input 对角度组件进行单元测试
问题描述
我有一个角度组件,它有一个 @input 属性并在ngOnInit
. 通常在对@input 进行单元测试时,我只是将其作为,component.inputproperty=value
但在这种情况下,我不能,因为它在ngOnInit
. 如何在.spec.ts
文件中提供此输入值。我能想到的唯一选择是创建一个测试主机组件,但如果有更简单的方法,我真的不想走这条路。
解决方案
做一个测试主机组件是一种方法,但我知道这可能是太多的工作。
组件的ngOnInit
被调用fixture.detectChanges()
后的第一个TestBed.createComponent(...)
。
因此,要确保它被填充在 中ngOnInit
,请将其设置在第一个fixture.detectChanges()
.
例子:
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
component.inputproperty = value; // set the value here
fixture.detectChanges(); // first fixture.detectChanges call after createComponent will call ngOnInit
我假设所有这些都在 a 中beforeEach
,如果您想要 s 的不同值inputproperty
,则必须对describe
s 和进行创意beforeEach
。
例如:
describe('BannerComponent', () => {
let component: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({declarations: [BannerComponent]}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeDefined();
});
describe('inputproperty is blahBlah', () => {
beforeEach(() => {
component.inputproperty = 'blahBlah';
fixture.detectChanges();
});
it('should do xyz if inputProperty is blahBlah', () => {
// test when inputproperty is blahBlah
});
});
describe('inputproperty is abc', () => {
beforeEach(() => {
component.inputproperty = 'abc';
fixture.detectChanges();
});
it('should do xyz if inputProperty is abc', () => {
// test when inputproperty is abc
});
});
});
推荐阅读
- c - 使用用户定义的函数在 C 中反转给定字符串的单词
- jquery - jQuery 数据表返回 0
- ruby-on-rails - 如何识别自定义 COP 中的全局 Rails 设置?
- android - 未应用 AlertDialog 的自定义主题
- python - 对数字元素求和以获得所需的结果
- python - 如何分隔名称和数字总和?
- amazon-web-services - AWS IAM 根据 dynamodb 属性值授予权限
- angular - 刷新 NGRX 没有成功操作
- javascript - `.then` 和 `.catch` Promise 处理程序是否以某种方式配对并像 `.then(resolutionHandler, rejectHandler)` 处理?
- javascript - cv::imdecode 图像从 JS 到 C++ (opencv, emscripten)