0
votes

I am currently writing unit tests for a react component in my application. The react component utilize the DOM api such as document.getElementById(). When I use shallow() or mount() from enzyme, I get an error saying that the document object is null: enter image description here

I thought that jest already comes with jsdom as a headless browser. How can I fixed this issue to access a fake dom object?

1
you can use [ document && document... ], and then, test at updateProdSpan. Well, it only will run the test, maybe you need to mock the document object with jest.mockJoao Polo

1 Answers

0
votes

First of all, the component preferably shouldn't use DOM directly because this affects testability and SSR. Rven if it uses, it preferably should use relative queries, not document.

JSDOM is not headless browser but Node.js environment that emulates browser environment.

Jest uses JSDOM by default. document cannot be null, unless it was specifically assigned to it somewhere. If Jest were configured to not use JSDOM, it would throw document is not defined error.

The error states that it is document.getElementById() result that is null, not document.

document.getElementById is supposed to be mocked as any other function:

jest.spyOn(document, 'getElementById').mockReturnValueOnce({ value: '...' });