【问题标题】:Angular2 async testing issue with ng-inline-svgng-inline-svg 的 Angular2 异步测试问题
【发布时间】:2017-05-15 13:14:30
【问题描述】:

我为我的 angular2 组件编写了测试,该组件使用 ng-inline-svg 模块来加载我的 svg 文件。在编写了实际组件后,结果发现该组件运行良好,但测试失败。我怀疑测试不会等待 svg 插入完成。有什么办法可以解决吗?测试失败:

it('Should create new svg element', async(()=>{
    fixture.detectChanges();
    expect(de.query(By.css('svg'))).toBeTruthy();
}));

如果我用“div”替换“svg”选择器,它会发现包装器没有问题。

【问题讨论】:

    标签: angular karma-runner


    【解决方案1】:

    编辑:

    这是一个已知的错误:https://github.com/angular/angular/issues/15164

    By.css() 无法选择 SVGElement 实例。

    您应该能够使用DOMElement.querySelector 方法获得对SVG 元素的引用。

    it('Should create new svg element', async(()=>{
        fixture.whenStable().then(() => {
            const nativeElement = de.nativeElement;
            fixture.detectChanges();        
            expect(nativeElement.querySelector('svg')).toBeTruthy();
        });
    }));
    

    plunker:https://embed.plnkr.co/bgH31O/


    原答案:

    我不知道ng-inline-svgmodule的实现细节,但也许<svg>元素是异步插入到DOM中的?

    如果是这样,你可以使用whenStable():

    it('Should create new svg element', async(()=>{
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            expect(de.query(By.css('svg'))).toBeTruthy();
        });
    }));
    

    引用文档

    事实上,whenStable 承诺会在此测试中所有待处理的异步活动完成时解决——“稳定”的定义。

    【讨论】:

    • 我很确定它是异步插入的,因为它使用 Http.get() 获取文件,不幸的是 whenStable() 没有帮助。
    • 我已经更新了我的答案。这是 By.css 方法的一个已知错误。
    • 我之前使用过 querySelector(),如果我直接将它放在模板中,它确实可以很好地选择 svg,它仍然不适用于从文件插入的 svg。我在模板中添加并打印了测试变量,并使用了(onSVGInserted)="test=true",它打印为真,但在测试中为假。
    • 我实际上在模板中添加了 test bool 的插值,它不会在 karma 预览中更新,并且即使 console.log(this.test); 调用 onSVGInserted 打印结果为 true,它仍然是 false。所以测试似乎在它被调用之前就结束了。
    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2018-04-30
    • 2013-10-01
    相关资源
    最近更新 更多