如何对自定义元素进行单元测试 [英] How can I unit test a custom element

查看:70
本文介绍了如何对自定义元素进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展 HTMLElement 的类.通过阅读该线程

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

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

我看到我无法实例化自定义元素而没有得到非法构造函数.此外, registerElement 看起来很有希望,因为它返回了自定义元素的构造函数,但是现在不赞成使用窗口对象上存在的 CustomElementRegistry.define() 1.2.返回void.任何解决方案将不胜感激,谢谢.

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.

对于此特定设置,我尝试使用本机自定义元素而不是Web组件框架,因为我只需要自定义元素.另外,我正在使用TypeScript并尝试使用Jest对其进行测试.

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.

当在不同的类中实现不同的事物时,可以实现关注的分离.这也意味着可以在不实例化具体HtmlElement的情况下测试分离的事物.

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.

此时,controll的转换非常方便,因为如果可以从类外部设置分离类的依赖关系(可能是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.

这个想法是要以一种独立于单元测试中不可访问或不可控制的东西的方式设计代码.

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

这篇关于如何对自定义元素进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆