简体   繁体   中英

How can I unit test a custom element

I have a class that extends HTMLElement . From reading this thread

https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089

I see that I can't instantiate a custom element with out getting a Illegal constructor . Additionally, the registerElement looked promising as it returned the constructor for the custom element but that is now deprecated for using CustomElementRegistry.define() that 1. exists on the window object and 2. returns void. Any solutions will be greatly appreciated thank you.

for this particular setup I am attempting to use native custom elements as opposed to a web component framework because I only need custom elements. Also, I am using TypeScript and attempting to use Jest to test it.

Depending on what extactly your element is doing you could consider to take the design principles "separation of concern" and "inversion of control" into account.

Separation of concern would be achieved when different things are implemented in different classes. This would also mean that the separated things can be tested without instantiating a concrete HtmlElement.

Inversion of controll comes in handy at this Point because if the dependencies of the separated classes (probably the HtmlElement) are settable from outside of the class, you can easily stub or mock the HtmlElement by giving a stub to the test-instance.

The idea is to design your code in a way that it is independent of things that are not accessible or controllable in unittests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM