Jest-Javascript单元测试工具

 
 
 
    

Jest是一个JavaScript测试框架,由Facebook用来测试所有JavaScript代码,包括React应用程序。

不同级别的自动化测试:单元、集成、组件和功能. 单元测试可以看作是和在组件级别测试JavaScript对象和方法一样的最基本的。默认情况下,React Native提供在Android和iOS都可以使用的Jest来进行单元测试。现在,测试的覆盖率并不完美,但是根据Facebook的说法,未来将会有更强大测试能力的工具被引入到React Native,同时用户也可以构建他们自己的测试工具。

Jest的测试特性

适应性:Jest是模块化、可扩展和可配置的。

快速和沙盒:Jest虚拟化JavaScript环境,能模拟浏览器,并在工作进程之间并行运行测试。

快照测试:Jest能够对React 树进行快照或别的序列化数值快速编写测试,提供快速更新的用户体验。

快速交互模式: 错误信息会有帮助的颜色编码标记,堆栈跟踪快速指向问题的根源。

使用

配置Jest

可以使用npm运行 **npm install --save-dev jest**  也可以与使用所有的Js包一样:先配置package.json,再执行npm install。

编写测试脚本

1.让我们写一个假设的测试是sum.js文件,函数为:

module.exports = (a, b) => a + b;

2.创建一个目录____tests____/和文件xxx-test.js,或直接创建名称xxx.test.js或xxx.spec.js并把它放在你的项目的任何地方(**其实在jest中我们对脚步的定义是有约束的,采用这几钟创建方式,使jest在源码文件中可以找到测试脚步并执行**)

test('adds 1 + 2 to equal 3', () => {

const sum = require('../sum');

expect(sum(1, 2)).toBe(3);

});

3.执行脚本  (执行脚本有两种方式)

1)可以添加到package.json

"scripts": {

"test": "jest"

}

2)直接执行命令

需要安装全局jest命令: npm install -g jest,进入项目,执行命令:jest

4.运行

运行**npm test**会打印此消息:**PASS ____tests____/sum-test.js** 到此你就成功使用Jest写了你的第一个测试!


所有的断言

.expect(value)

.lastCalledWith(arg1, arg2, ...) is an alias for .toHaveBeenLastCalledWith(arg1, arg2, ...)

.not

.toBe(value)

.toBeCalled() is an alias for .toHaveBeenCalled()

.toBeCalledWith(arg1, arg2, ...) is an alias for .toHaveBeenCalledWith(arg1, arg2, ...)

.toHaveBeenCalled()

.toHaveBeenCalledTimes(number)

.toHaveBeenCalledWith(arg1, arg2, ...)

.toHaveBeenLastCalledWith(arg1, arg2, ...)

.toBeCloseTo(number, numDigits)

.toBeDefined()

.toBeFalsy()

.toBeGreaterThan(number)

.toBeGreaterThanOrEqual(number)

.toBeLessThan(number)

.toBeLessThanOrEqual(number)

.toBeInstanceOf(Class)

.toBeNull()

.toBeTruthy()

.toBeUndefined()

.toContain(item)

.toContainEqual(item)

.toEqual(value)

.toHaveLength(number)

.toMatch(regexp)

.toMatchObject(object)

.toMatchSnapshot()

.toThrow()

.toThrowError(error)

.toThrowErrorMatchingSnapshot()

作者:小涛先生呢 链接:https://www.jianshu.com/p/a656a5459e73 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/hsany330/article/details/79136136