【问题标题】:Angular test - how to mock document.getElementbyId in angular test?角度测试 - 如何在角度测试中模拟 document.getElementbyId?
【发布时间】:2022-01-10 00:17:52
【问题描述】:

我在角度分量中的一个函数中有以下两行。我的角度测试失败,抛出错误 TypeError: Cannot set properties of null (setting 'value')。

test.ts

function reset(){
 (<HTMLInputElement>document.getElementById('test1')).value = '';
 this.nameCtrl.setValue(null);
}

test.spec

fixture.debugElement.componentInstance.test1.value='';
fixture.debugElement.componentInstance.nameCtrl.setValue(null);

我尝试使用上面的方法来模拟静止的线条,但它仍然失败。请帮忙

【问题讨论】:

  • 我不明白 test.ts 和 test.spec 有什么关系。组件在哪里?你有 orgTeam 实例化吗?

标签: angular angular-test


【解决方案1】:

考虑使用 Angular ViewChild 装饰器而不是 document.getElementById 来访问 test1 DOM 元素。

在此处查看示例: https://www.digitalocean.com/community/tutorials/angular-viewchild-access-component

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2020-06-24
    • 1970-01-01
    • 2019-06-05
    • 2023-04-02
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多