issues
search
LLwanran
/
front_end_studying
前端知识要点
https://llwanran.github.io/front_end_studying/
2
stars
1
forks
source link
前端编写单元测试有哪些原则?(北京京东到家3面)
#34
Open
LLwanran
opened
5 years ago
LLwanran
commented
5 years ago
单元测试是什么?
为检测特定的目标是否符合标准而采用专用的工具或者方法进行验证,并最终得出特定的结果
需要访问数据库的测试不是单元测试
需要访问网络的测试不是单元测试
需要访问文件系统的测试不是单元测试
为什么需要单元测试?
正确性:测试可以验证代码的正确性,在上线前做到心里有底
自动化:当然手工也可以测试,通过console可以打印出内部信息,但是这是一次性的事情,下次测试还需要从头来过,效率不能得到保证。通过编写测试用例,可以做到一次编写,多次运行
解释性:测试用例用于测试接口、模块的重要性,那么在测试用例中就会涉及如何使用这些API。其他开发人员如果要使用这些API,那阅读测试用例是一种很好地途径,有时比文档说明更清晰
驱动开发,指导设计:代码被测试的前提是代码本身的可测试性,那么要保证代码的可测试性,就需要在开发中注意API的设计,TDD将测试前移就是起到这么一个作用
保证重构:互联网行业产品迭代速度很快,迭代后必然存在代码重构的过程,那怎么才能保证重构后代码的质量呢?有测试用例做后盾,就可以大胆的进行重构
测试分类
单元测试(Unit tests):关注应用中每个零部件的正常运转,防止后续修改影响之前的组件
功能测试(Functional tests):确保其整体表现符合预期,关注能否让用户正常使用
整合测试(Integration tests):确保单独运行正常的零部件整合到一起之后依然能正常运行
原则
测试代码时,只考虑测试,不考虑内部实现
数据尽量模拟现实,越靠近现实越好
充分考虑数据的边界条件
对重点、复杂、核心代码,重点测试
利用AOP(beforeEach、afterEach),减少测试代码数量,避免无用功能
测试、功能开发相结合,有利于设计和代码重构
常见的测试工具:
Mocha(JavaScript 的测试框架,类似于 Java 中的 Junit)
Chai(单元测试的验证框架)
Sinon(mock 框架)
Enzyme(React 官方测试工具库的封装)
Karma(基于 Node.js 的 JavaScript 测试执行过程管理工具)
Jasmine(JavaScript 测试框架)
Selenium(专门为 Web 应用程序编写的一个验收测试工具)
PhantomJS(基于 webkit 的服务器端 JavaScript API)
CasperJS(开源的导航脚本和测试工具)
Istanbul(JavaScript 程序的代码覆盖率工具)
Jest(Facebook 发布的一个开源的、基于 Jasmine 框架的 JavaScript 单元测试工具)
Nightwatch(基于 Node.js 平台的浏览器自动化测试解决方案)
单元测试是什么?
为什么需要单元测试?
测试分类
原则
常见的测试工具: