原文:An Overview of JavaScript Testing in 2021,本文是对原文消化后的部分整理,如果以前未接触过前端测试,请读者看原文
测试类型
- 单元测试
- 集成测试(组件测试)
- 功能测试(E2E,端对端测试)
测试环境
- 浏览器
- 无界面浏览器
- Nodejs
测试工具类型
框架对比表
框架 功能 | Test lanuchers | Testing structure providers | Assertion functions | Generate and display test progress and summary | Mocks, spies, and stubs | Generate and compare snapshots | Generate code coverage | Browser Controllers | Visual Regression Tools |
Karma | ✔️ | ✔️ | |||||||
Jasmine | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ||||
Jest | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ||
TestCafe | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ||||
Cypress | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ||||
webdriverio | ✔️ | ||||||||
Mocha | ✔️ | ✔️ | |||||||
Cucumber | ✔️ | ||||||||
Chai | ✔️ | ||||||||
Unexpected | ✔️ | ||||||||
Sinon | ✔️ | ||||||||
enzyme | ✔️ | ||||||||
testdouble | ✔️ | ||||||||
Ava | ✔️ | ||||||||
Instanbul | ✔️ | ||||||||
Blanket | ✔️ | ||||||||
Nightwatch | ✔️ | ||||||||
Nightmare | ✔️ | ||||||||
Phantom | ✔️ | ||||||||
Pupperteer | ✔️ | ||||||||
Applitools | ✔️ | ||||||||
Percy | ✔️ | ||||||||
Wraith | ✔️ | ||||||||
WebdriverCSS | ✔️ |
Browser Controllers
模拟用户行为,比如:点击鼠标、拖拽、上滑、码字和导航等
借助安装驱动,比如selenium, protractor, webdriverIO, Nightwatch, Apium
Your code on Node.js <> WebDriver <> FF/Chrome/Safari Driver <> Browser
注入脚本,比如testCafe, Cypress
document.getElementByID('someButton').dispatchEvent(clickEvent)
暴露浏览器的原生API,比如puppeteer
Your code on Node.js <> Browser's API
组合使用测试框架
像Jest, Jasmine, TestCafe, Cypress是集成型的可以开箱即用。而有些需要组合使用比如一种常见的组合:mocha + chai + sinon
建议从两个方面考虑:1、单元测试和集成测试;2、端对端测试(功能测试)。因为功能测试特别耗时间,特别是测试不同浏览器时
集成型的简单,开箱即用,功能也强大。而非集成型的比较灵活,可以任意组合
各种测试类型需要的测试框架能力:
- 单元测试:assertion functions和code coverage reporting tool
单元测试一般用于函数式编程和尽可能保持纯洁(无副用作),越纯洁测试就越容易
- 集成测试:Mocks, spies, and stubs和component snapshot
集成测试应该涵盖重要的跨模块过程。有时它们扩展到跨多个类的流程,有时扩展到测试不同的系统,如前端-后端交互
- 功能测试: control browsers和Visual regression tools
补充:根据js框架推荐测试框架
- vue: jest(单元测试) + Vue Testing Library(组件测试) + cypress(E2E测试)
- react: jest(单元测试) + enzyme(组件测试) + cypress(E2E测试)
- angular: jasmine(单元测试、组件测试) + karma(运行器和测试报告) + protractor(E2E测试)