首页 > 解决方案 > 如何模拟文件,用茉莉花隐藏​​?

问题描述

我正在尝试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

提前致谢

标签: javascriptangularjasmine

解决方案


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

document.hidden = true;

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

class MyComponent {
   constructor(@Inject(DOCUMENT) private document: Document) {}
 ...
}
// test
let documentMock: any;
...

documentMock = {hidden: true};
TestBed.configureTestingModule({
   providers: [{provide: DOCUMENT, useValue: documentMock}]
})

推荐阅读