写文章的目的是:咱们应该在之前的学习认知的水平上进行学习,而不是一次次的重复,用文章记录咱们的学习,先散而后才能成章。javascript
前端测试工具 jest, 咱们阅读 Jest 官方文章以后,使用 Jest 从简单到深刻的学习 Jest 的测试,方便咱们编写高质量的组件。html
yarn add --dev jest
# 全局安装
yarn add global jest
复制代码
在根目录建立 /test/index.test.js
前端
// index.test.js
test('plus', () => {
expect(1+2).toBe(3)
})
// 获得以下的结果
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.828s
复制代码
若是使用过glup的话,这里 test 函数就比如 gulp 的 task 任务。这里理解为 test 任务。java
任务 plus 的做用: expect 的值,与toBe 的值进行对比。android
expect(value), expect函数的参数是 value 表示一个值。其中expect函数的返回是一个指望对象,指望对象具备 toBe 方法,因此这就能构成一个闭环。正则表达式
有时候咱们须要严格的区分 undefined, null, false,gulp
// 匹配上面特定的值数组
定义分为两种: 定义toBeDefined, 没有定义 toBeUndefined.异步
字符串类型,最多的就是用 regexp 来匹配,因此咱们仍是要把正则表示学好呀!函数
定义个函数,使用函数的形式来在test的时候抛出一个错误。
function compileAndroidCode() {
throw new Error('you are using the wrong JDK')
}
test('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(Error)
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK');
expect(compileAndroidCode).toThrow(/JDK/);
})
复制代码
__test__
存放测试文件