使用Jest测试JavaScript (入门篇)

1 什么是 Jest?

Jest是 Facebook 的一套开源的 JavaScript 测试框架, 它自动集成了断言、JSDom、覆盖率报告等开发者所须要的全部测试工具,是一款几乎零配置的测试框架。而且它对一样是 Facebook 的开源前端框架 React 的测试十分友好。前端

2 安装Jest

2.1 初始化package.json

shell中输入如下命令,初始化前端项目并生成package.jsonios

npm init -y

2.2 安装Jest及相关依赖

shell中输入如下命令,安装测试所须要的依赖:正则表达式

npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime

babel-jestbabel-coreregenerator-runtimebabel-preset-env这几个依赖是为了让咱们能够使用ES6的语法特性进行单元测试,ES6提供的 import 来导入模块的方式,Jest自己是不支持的。shell

2.3 添加.babelrc文件

在项目的根目录下添加.babelrc文件,并在文件复制以下内容:npm

json

{
"presets": ["env"]
}

<h4><strong>2.4 修改<code>package.json</code>中的<code>test</code>脚本</strong></h4>
<p>打开<code>package.json</code>文件,将<code>script</code>下的<code>test</code>的值修改成<code>jest</code>:</p>

"scripts": {
"test": "jest"
}axios


<h3><strong>3. 编写你的第一个Jest测试</strong></h3>
<p><strong>建立<code>src</code>和<code>test</code>目录及相关文件</strong></p>
<ul>
<li>在项目根目录下建立<code>src</code>目录,并在<code>src</code>目录下添加<code>functions.js</code>文件</li>
<li>在项目根目录下建立<code>test</code>目录,并在<code>test</code>目录下建立<code>functions.test.js</code>文件</li>
</ul>
<p>Jest会自动找到项目中全部使用<code>.spec.js</code>或<code>.test.js</code>文件命名的测试文件并执行,一般咱们在编写测试文件时遵循的命名规范:<strong>测试文件的文件名 = 被测试模块名 + <code>.test.js</code></strong>,例如被测试模块为<code>functions.js</code>,那么对应的测试文件命名为<code>functions.test.js</code>。</p>
<p><strong>在<code>src/functions.js</code>中建立被测试的模块</strong></p>

export default {
sum(a, b) {
return a + b;
}
}segmentfault


<p><strong>在<code>test/functions.test.js</code>文件中建立测试用例</strong></p>

import functions from '../src/functions';数组

test('sum(2 + 2) 等于 4', () => {
expect(functions.sum(2, 2)).toBe(4);
})前端框架


<p><strong>运行<code>npm run test</code>, Jest会在<code>shell</code>中打印出如下消息:</strong></p>

PASS test/functions.test.js
√ sum(2 + 2) 等于 4 (7ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.8s


<h3><strong>4.经常使用的几个Jest断言</strong></h3>
<p>上面测试用例中的<code>expect(functions.sum(2, 2)).toBe(4)</code>为一句断言,Jest为咱们提供了<code>expect</code>函数用来包装被测试的方法并返回一个对象,该对象中包含一系列的匹配器来让咱们更方便的进行断言,上面的<code>toBe</code>函数即为一个匹配器。咱们来介绍几种经常使用的Jest断言,其中会涉及多个匹配器。</p>
<p><strong><code>.not</code></strong></p>

//functions.test.js
import functions from '../src/functions'

test('sum(2, 2) 不等于 5', () => {
expect(functions.sum(2, 2)).not.toBe(5);
})


<p><code>.not</code>修饰符容许你测试结果不等于某个值的状况,这和英语的语法几乎彻底同样,很好理解。</p>
<p><strong><code>.toEqual()</code></strong></p>

// functions.js
export default {
getAuthor() {
return {
name: 'LITANGHUI',
age: 24,
}
}
}


// functions.test.js
import functions from '../src/functions';

test('getAuthor()返回的对象深度相等', () => {
expect(functions.getAuthor()).toEqual(functions.getAuthor());
})

test('getAuthor()返回的对象内存地址不一样', () => {
expect(functions.getAuthor()).not.toBe(functions.getAuthor());
})


<p><code>.toEqual</code>匹配器会递归的检查对象全部属性和属性值是否相等,因此若是要进行应用类型的比较时,请使用<code>.toEqual</code>匹配器而不是<code>.toBe</code>。</p>
<p><strong><code>.toHaveLength</code></strong></p>

// functions.js
export default {
getIntArray(num) {
if (!Number.isInteger(num)) {
throw Error('"getIntArray"只接受整数类型的参数');
}

let result = [];
for (let i = 0, len = num; i &lt; len; i++) {
  result.push(i);
}

return result;

}
}


// functions.test.js
import functions from '../src/functions';

test('getIntArray(3)返回的数组长度应该为3', () => {
expect(functions.getIntArray(3)).toHaveLength(3);
})


<p><code>.toHaveLength</code>能够很方便的用来测试字符串和数组类型的长度是否知足预期。</p>
<p><strong><code>.toThrow</code></strong></p>

// functions.test.js
import functions from '../src/functions';

test('getIntArray(3.3)应该抛出错误', () => {
function getIntArrayWrapFn() {
functions.getIntArray(3.3);
}
expect(getIntArrayWrapFn).toThrow('"getIntArray"只接受整数类型的参数');
})


<p><code>.toThorw</code>可可以让咱们测试被测试方法是否按照预期抛出异常,可是在使用时须要注意的是:<strong>咱们必须使用一个函数将将被测试的函数作一个包装</strong>,正如上面<code>getIntArrayWrapFn</code>所作的那样,不然会由于函数抛出致使该断言失败。</p>
<p><strong><code>.toMatch</code></strong></p>

// functions.test.js
import functions from '../src/functions';

test('getAuthor().name应该包含"li"这个姓氏', () => {
expect(functions.getAuthor().name).toMatch(/li/i);
})


<p><code>.toMatch</code>传入一个正则表达式,它容许咱们用来进行字符串类型的正则匹配。</p>
<h3><strong>5 测试异步函数</strong></h3>
<p><strong>安装<code>axios</code></strong><br>这里咱们使用最经常使用的http请求库<code>axios</code>来进行请求处理</p>

npm install axios


<p><strong>编写http请求函数</strong><br>咱们将请求<code>http://jsonplaceholder.typicode.com/users/1</code>,这是由<strong>JSONPlaceholder</strong>提供的mock请求地址</p>

// functions.js
import axios from 'axios';

export default {
fetchUser() {
return axios.get('http://jsonplaceholder.typicode.com/users/1')
.then(res => res.data)
.catch(error => console.log(error));
}
}


// functions.test.js
import functions from '../src/functions';

test('fetchUser() 能够请求到一个含有name属性值为Leanne Graham的对象', () => {
expect.assertions(1);
return functions.fetchUser()
.then(data => {
expect(data.name).toBe('Leanne Graham');
});
})


<p>上面咱们调用了<code>expect.assertions(1)</code>,它能确保在异步的测试用例中,有一个断言会在回调函数中被执行。这在进行异步代码的测试中十分有效。</p>
<p><strong>使用<code>async</code>和<code>await</code>精简异步代码</strong></p>

test('fetchUser() 能够请求到一个用户名字为Leanne Graham', async () => {
expect.assertions(1);
const data = await functions.fetchUser();
expect(data.name).toBe('Leanne Graham')
})
```

固然咱们既然安装了Babel,为什么不使用asyncawait的语法来精简咱们的异步测试代码呢? 可是别忘记都须要调用expect.assertions方法

参考资料

【1】 Jest官方文档(https://jestjs.io/zh-Hans/)
【2】 Jest Crash Course - Unit Testing in JavaScript(https://www.youtube.com/watch...

来源:http://www.javashuo.com/article/p-erwjgruk-hu.html

<h4><strong>2.4 修改<code>package.json</code>中的<code>test</code>脚本</strong></h4> <p>打开<code>package.json</code>文件,将<code>script</code>下的<code>test</code>的值修改成<code>jest</code>:</p><h3><strong>3. 编写你的第一个Jest测试</strong></h3> <p><strong>建立<code>src</code>和<code>test</code>目录及相关文件</strong></p> <ul> <li>在项目根目录下建立<code>src</code>目录,并在<code>src</code>目录下添加<code>functions.js</code>文件</li> <li>在项目根目录下建立<code>test</code>目录,并在<code>test</code>目录下建立<code>functions.test.js</code>文件</li> </ul> <p>Jest会自动找到项目中全部使用<code>.spec.js</code>或<code>.test.js</code>文件命名的测试文件并执行,一般咱们在编写测试文件时遵循的命名规范:<strong>测试文件的文件名 = 被测试模块名 + <code>.test.js</code></strong>,例如被测试模块为<code>functions.js</code>,那么对应的测试文件命名为<code>functions.test.js</code>。</p> <p><strong>在<code>src/functions.js</code>中建立被测试的模块</strong></p><p><strong>在<code>test/functions.test.js</code>文件中建立测试用例</strong></p><p><strong>运行<code>npm run test</code>, Jest会在<code>shell</code>中打印出如下消息:</strong></p><h3><strong>4.经常使用的几个Jest断言</strong></h3> <p>上面测试用例中的<code>expect(functions.sum(2, 2)).toBe(4)</code>为一句断言,Jest为咱们提供了<code>expect</code>函数用来包装被测试的方法并返回一个对象,该对象中包含一系列的匹配器来让咱们更方便的进行断言,上面的<code>toBe</code>函数即为一个匹配器。咱们来介绍几种经常使用的Jest断言,其中会涉及多个匹配器。</p> <p><strong><code>.not</code></strong></p><p><code>.not</code>修饰符容许你测试结果不等于某个值的状况,这和英语的语法几乎彻底同样,很好理解。</p> <p><strong><code>.toEqual()</code></strong></p><p><code>.toEqual</code>匹配器会递归的检查对象全部属性和属性值是否相等,因此若是要进行应用类型的比较时,请使用<code>.toEqual</code>匹配器而不是<code>.toBe</code>。</p> <p><strong><code>.toHaveLength</code></strong></p>let result = []; for (let i = 0, len = num; i &lt; len; i++) { result.push(i); } return result;<p><code>.toHaveLength</code>能够很方便的用来测试字符串和数组类型的长度是否知足预期。</p> <p><strong><code>.toThrow</code></strong></p><p><code>.toThorw</code>可可以让咱们测试被测试方法是否按照预期抛出异常,可是在使用时须要注意的是:<strong>咱们必须使用一个函数将将被测试的函数作一个包装</strong>,正如上面<code>getIntArrayWrapFn</code>所作的那样,不然会由于函数抛出致使该断言失败。</p> <p><strong><code>.toMatch</code></strong></p><p><code>.toMatch</code>传入一个正则表达式,它容许咱们用来进行字符串类型的正则匹配。</p> <h3><strong>5 测试异步函数</strong></h3> <p><strong>安装<code>axios</code></strong><br>这里咱们使用最经常使用的http请求库<code>axios</code>来进行请求处理</p><p><strong>编写http请求函数</strong><br>咱们将请求<code>http://jsonplaceholder.typicode.com/users/1</code>,这是由<strong>JSONPlaceholder</strong>提供的mock请求地址</p><p>上面咱们调用了<code>expect.assertions(1)</code>,它能确保在异步的测试用例中,有一个断言会在回调函数中被执行。这在进行异步代码的测试中十分有效。</p> <p><strong>使用<code>async</code>和<code>await</code>精简异步代码</strong></p>Babelasyncawaitexpect.assertions
相关文章
相关标签/搜索