Javascript 单元测试 - DOM 操作 [英] Javascript Unit Testing - DOM Manipulation

查看:30
本文介绍了Javascript 单元测试 - DOM 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Javacript 单元测试很陌生.一件事一直困扰着我.在测试javascript时,我们经常需要做DOM操作.看起来我正在对控制器/组件中的方法/函数进行单元测试,但我仍然需要依赖模板中的 HTML 元素.一旦更改了 id(或在我的测试用例中曾经是选择器的属性),我的测试用例也需要更改!这不会违背单元测试的目的吗?

I'm quite new to Javacript Unit testing. One thing keep bothering me. When testing javascript, we often need to do the DOM manipulation. It looks like I am unit testing a method/function in a Controller/Component, but I still need to depend on the HTML elements in my templates. Once the id(or attributes used to be selectors in my test cases) is changed, my test cases also need to be CHANGED! Wouldn't this violate the purpose of unit testing?

推荐答案

javascript 单元测试最困难的部分之一不是测试,而是学习如何构建代码以使其可测试.

One of the toughest parts of javascript unit testing is not the testing, it's learning how to architect your code so that it is testable.

您需要将可测试逻辑和 DOM 操作明确分离来构建代码.

You need to structure your code with a clear separation of testable logic and DOM manipulation.

我的经验法则是:

如果您正在测试任何依赖于 DOM 结构的内容,那么您就做错了.

If you are testing anything that is dependent on the DOM structure, then you are doing it wrong.

总结:尝试仅测试数据操作和逻辑运算.

In summary:Try to test data manipulations and logical operations only.

这篇关于Javascript 单元测试 - DOM 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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