How can I unit test a custom element

爱⌒轻易说出口 提交于 2021-01-28 10:10:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/47800461/how-can-i-unit-test-a-custom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!