【问题标题】:Access to DOM body element from within Angular TestBed从 Angular TestBed 中访问 DOM 正文元素
【发布时间】:2021-04-03 17:04:53
【问题描述】:

我们使用标准的 Jasmine/Angular 单元测试设置进行组件单元测试,使用

fixture = TestBed.createComponent(MyComponent);

在 beforeEach 方法中。

大多数时候,我们使用访问元素没有问题

fixture.debugElement.query(By.css('myelement'));

但是每隔一段时间,我们想要测试一些实际附加到 html 正文的 UI 的行为。例如,我们正在使用从“MyComponent”中调用的定制对话服务,并希望验证它是否正确加载了正确的内容。 (我知道您可能会争辩说它超出了“MyComponent”单元测试的范围,但我们假设我们需要这样做。)

当我尝试时

const allHTML = fixture.debugElement.query(By.css('*'));

我可以看到 Angular 只给了我“MyComponent”的内容,而不是整个 DOM。因此,正因为如此,我无法访问可能附加到正文的元素。

有没有人找到一种方法来测试这个限制?

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:
    <html id="main">
    
    // in beforeEach: create above code via createElement and setAttribute
    const dummyElement = document.createElement('html');
    dummyElement.setAttribute('id', 'main');
    document.getElementById = jasmine.createSpy('HTML Element').and.returnValue(dummyElement);
    
    const main = <HTMLInputElement>document.getElementById('main');
    

    【讨论】:

    • 感谢您的回答,但这只会给我一个空的 html 元素。它不允许我访问附加到 html 正文的 UI 元素,因为在 fixture.debugElement 查询中返回的 DOM 只包括我的组件中的所有内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2017-03-03
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    相关资源
    最近更新 更多