I need a way to determine the type of an HTML element in Jest. I have tried below code to see If HTMLLabelElement is available. I am getting ReferenceError: HTMLLabelElement is not defined
Jest it() function code snippet
it('check HTML label Element type', async () => {
const doc = document.createElement('label');
console.log(doc instanceof HTMLLabelElement);
});
Let me know if anybody have any idea on this.
2
Answers
If you need to test against some class, explicitly import that class. In the case of the DOM, HTML classes are bound to
window
, so:That said, this is a baffling weird test: by definition elements implement their element class in any DOM compliant implementation. By using JSDom, you are already guaranteed that this is going to be true, and testing for it gets you nothing that wasn’t already true before you even ran any tests.
So I’m pretty sure you’re actually testing for completely the wrong thing in whatever your real test cases are, like checking if a tag yields a standard or custom element, which you wouldn’t do this way, and you really should have asked about whatever you actually want to do instead.
All of the
HTMLElement
interfaces should be available in the browser.Since you are running Jest as a Node CLI via
ts-jest
, you have to make sure that you have a DOMdocument
object available during testing. Make sure you installjest-environment-jsdom
.Sample code
The following minimal configuration works.
index.test.ts
index.test.js
jest.config.js
tsconfig.json
package.json
References
Here is a mock for demonstration purposes only.