Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue 项目前端测试 #23

Open
XueSeason opened this issue Nov 15, 2018 · 0 comments
Open

Vue 项目前端测试 #23

XueSeason opened this issue Nov 15, 2018 · 0 comments
Labels

Comments

@XueSeason
Copy link
Member

组件测试的好处

  1. 在未来更加容易重构组件
  2. 提高代码质量(单一职责原则、模块化代码、更清楚的认识到组件真正的功能)
  3. 良好的文档代码

Confidence to Change/Removal of Fear +
High Code Quality +
Well-Document Code =
Developer Happiness

Vue 的组件测试

关注组件的输入和输出部分,即测试公共接口功能,不测试内部实现细节。

输入:

  1. Props
  2. 用户交互
  3. 生命周期方法

输出:

  1. 事件
  2. 渲染视图

Props => Component => Rendered Output

User Interaction => Component => Events

NOTE:

我们不需要过度关注组件的内部实现细节,把组件想象成一个黑盒,只测试共有部分。同时避免测试框架自身 (检测数据是否渲染到视图、组件属性校验等操作),我们需要相信框架是可用的,框架的测试就交给框架作者吧。

Integration and Shallow

Integration: 子组件触发事件 => 父组件修改子组件 Props => 子组件 UI 更新
Shallow: 组件是否触发事件、重新设置 Props 组件 UI 是否更新 (前者不关心其他组件 UI 是否更新,后者不关注是如何触发 Props 更新)

两者之间的权衡

Integration Shallow
Maintainability Medium/Low High
Coverage High Medium
Modularity Low High

前端测试需要考虑的点

  1. 浏览器环境的模拟
  2. 组件的执行环境
  3. 用户行为的模拟
  4. 视图界面的校验

浏览器环境的模拟

JSDOM 是 Node 模拟浏览器环境的库,遵循 WHATWG DOM 和 HTML 标准。相比真实浏览器测试足够轻量简单。如果你是用 Jest 框架,自带 JSDOM 环境。

当然也可以选择 puppeteer 等真实浏览器进行测试,但是实现起来比较麻烦,而且更加消耗性能,需要额外地下载安装包。

组件的执行环境

借助官方的 Vue Test Utils 工具,可以对 Vue 组件进行隔离挂载,然后模拟必要的输入 (prop、注入和用户事件) 和对输出 (渲染结果、触发的自定义事件) 的断言来测试 Vue 组件。被挂载的组件会返回到一个 Wrapper 内,而 Wrapper 会暴露很多封装、遍历和查询其内部的 Vue 组件实例的便捷的方法。

用户行为的模拟

Vue Test Utils 可以简单地模拟一系列 DOM 事件。通过 Wrapper 的 trigger 方法,可以在组件上触发 DOM 事件。官方也有大量示例参考。

视图界面的校验

Vue Test Utils 通过 Wrapper 的 html 方法,返回组件的 HTML 字符串进行校验,不过对于 DOM 节点多的情况下,手写校验比较繁琐。

更多情况下,推荐使用 Jest 的快照,实现更加简单。

参考资料

@XueSeason XueSeason added the Vue label Nov 15, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant