【问题标题】:How to mock document,hidden with Jasmine?如何模拟文件,用茉莉花隐藏​​?
【发布时间】:2021-02-14 23:36:57
【问题描述】:

我正在尝试在角度单元测试中模拟 document.hidden,但它不起作用。

我已经尝试过这些选项:

 spyOn(Document.prototype, <any>'hidden').and.returnValue(true);
 spyOn(Document, <any>'hidden').and.returnValue(true);
 spyOn(document, <any>'hidden').and.returnValue(true);
 spyOn(document, <any>'hidden').and.callFake(() => true);

 spyOn(DOCUMENT, <any>'hidden').and.returnValue(true); // using TestBed

提前致谢

【问题讨论】:

    标签: javascript angular jasmine


    【解决方案1】:

    间谍是为函数而设计的,而不仅仅是属性值。模拟一个属性就行了

    document.hidden = true;
    

    更新:因为 hidden 是一个只读属性,我建议将文档对象注入到组件中,然后在测试中为它提供您想要的任何值

    class MyComponent {
       constructor(@Inject(DOCUMENT) private document: Document) {}
     ...
    }
    
    // test
    let documentMock: any;
    ...
    
    documentMock = {hidden: true};
    TestBed.configureTestingModule({
       providers: [{provide: DOCUMENT, useValue: documentMock}]
    })
    

    【讨论】:

    • 它是一个只读属性,有什么解决方法来设置它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多