javascript - 如何以角度测试组件@Input?
问题描述
我已经做了很多次没有问题,但由于某种原因,我无法让它工作。在我的组件中,我有一个 input @Input data: Data
,在我的模板中,我使用该 input 有条件地显示或隐藏内容。由于某些原因,在我的测试中,即使我直接使用 设置组件,组件也不会注册数据存在component.data = {props: values}
,但是如果我使用 单独运行测试fit
,它们运行良好。
data.component.spec.ts
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges();
component.ngOnInit();
fixture.detectChanges();
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
数据组件.ts
export class DataComponent implements OnInit {
@Input() data!: Data;
constructor() {};
ngOnInit() {
console.log('init');
}
}
data.component.html
<div *ngIf="data.values.length">
<p data-content *ngFor="let value of data.values">{{value}}</p>
</div>
我得到的错误:
Expected null to not be null "[data-content]"
解决方案
我想这可能是因为你打电话fixture.detectChanges
和ngOnInit
。你第一个fixture.detectChanges
呼唤,呼唤ngOnInit
你。
尝试这个:
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges(); // => this will call ngOnInit
// component.ngOnInit(); // remove this line, the first fixture.detectChanges()
// calls ngOnInit for you.
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
推荐阅读
- java - Spring Boot Rest API-无效请求参数异常:java.lang.IllegalArgumentException:参数值[计算机]与预期类型不匹配
- c# - 16位图像旋转并保存在c#中
- javascript - 是否可以在 Vee Validate 中更改 aria 属性的位置?
- ruby - 在链接点击时启动一个网址 - Ruby Shoes 3
- ios - iOS App Store Rejection - 您的应用使用“prefs:root=”非公共 URL 方案。有什么可测试的修复吗?
- protractor - 如何使用 JavaScript 实现量角器网格系统?
- flutter - 如何在颤动中突出显示一段文本?
- qt - 黑莓 10 级联。如何让长时间运行的无头应用程序自行终止?
- python - 需要更多了解python fuzz部分比例
- python - 如何使用 Spacy 提取标签属性