How to mock document,hidden with Jasmine?

Viewed 400

I am trying to mock document.hidden in angular unit test, but it is not working.

I already have tried these options:

 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

Thanks in advance

1 Answers

spies are made for functions, not for just property values. to mock a property just do

document.hidden = true;

update: because hidden is a readonly property I would suggest to inject document object to the component, and then provide it with any value you want inside of test

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

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