简体   繁体   English

如何对自定义元素进行单元测试

[英]How can I unit test a custom element

I have a class that extends HTMLElement . 我有一个扩展HTMLElement的类。 From reading this thread 从阅读这个线程

https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089 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 . 我看到我不能实例化一个自定义元素而没有得到一个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. 另外, registerElement看起来很有前途,因为它返回了自定义元素的构造函数,但现在不推荐使用CustomElementRegistry.define() ,它存在于window对象上,并且返回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. 对于这个特定的设置,我试图使用本机自定义元素而不是Web组件框架,因为我只需要自定义元素。 Also, I am using TypeScript and attempting to use Jest to test it. 此外,我正在使用TypeScript并尝试使用Jest来测试它。

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. 这也意味着可以在不实例化具体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. 控制的反转在这一点上派上用场,因为如果可以从类外部设置分离类(可能是HtmlElement)的依赖关系,则可以通过给测试实例提供存根来轻松地存根或模拟HtmlElement。

The idea is to design your code in a way that it is independent of things that are not accessible or controllable in unittests. 我们的想法是设计您的代码,使其独立于单元测试中无法访问或控制的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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