Jest JavaScript 单元测试工具

发布于 2023-04-20 21:27:09 字数 6763 浏览 55 评论 0

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 写了你的第一个测试!

断言

API

.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()

实例

.toBeFalsy

使用toBeFalsy当你不在乎一个值是什么,你只是想确保在布尔上下文值是错误的时候使用它 可能一开始的代码是这样,你可能不关心getErrors回报,特别是,它可能会返回false,null,或0,代码仍然工作

在JavaScript中,有六个falsy值:false, 0, '', null, undefined, and NaN。其他的都是真。

drinkSomeLaCroix();
if (!getErrors()) {
  drinkMoreLaCroix();
}
describe('drinking some La Croix', () => {
  it('does not lead to errors', () => {
     var getErrors = require('../js/sum');
    expect(getErrors()).toBeFalsy();
  });
});

.toBeGreaterThan

比较浮点数,您可以使用toBeGreaterThan。例如,如果您想要测试,ouncesPerCan()返回的值超过10

describe('ounces per can', () => {
  it('is more than 10', () => {
     var ouncesPerCan = require('../js/sum');
    expect(ouncesPerCan()).toBeGreaterThan(10);
  });
});

.toBeGreaterThanOrEqual

ouncesPerCan()返回的值至少12

describe('ounces per can', () => {
  it('is at least 12', () => {
     var ouncesPerCan = require('../js/sum');
    expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
  });
});

.toBeLessThan

ouncesPerCan()返回的值小于20

describe('ounces per can', () => {
  it('is less than 20', () => {
     var ouncesPerCan = require('../js/sum');
    expect(ouncesPerCan()).toBeLessThan(20);
  });
});

.toBeLessThanOrEqual

ouncesPerCan()返回的值最多12

describe('ounces per can', () => {
  it('is at most 12', () => {
     var ouncesPerCan = require('../js/sum');
    expect(ouncesPerCan()).toBeLessThanOrEqual(12);
  });
});

.toBeInstanceOf

使用.toBeInstanceOf(类)来检查一个对象是一个类的实例

class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws

.toBeNull

.toBeNull 和 .toBe(null)是一样的,使用.toBeNull有点更好的错误消息。当你想检查null时所以使用.toBeNull()

function bloop() {
  return null;
}
describe('bloop', () => {
  it('returns null', () => {
    expect(bloop()).toBeNull();
  });
})

.toBeTruthy

你可能不关心thirstInfo回报,特别是,它可能会返回true或一个复杂的对象,和代码仍然工作 可能一开始的代码是这样

drinkSomeLaCroix();
if (thirstInfo()) {
  drinkMoreLaCroix();
}
describe('drinking some La Croix', () => {
  it('leads to having thirst info', () => {
 var thirstInfo = require('../js/sum');
    expect(thirstInfo()).toBeTruthy();
  });
});

.toContain

使用 .toContain当你想检查一个项目列表。测试列表中的项目,它使用===,检查是否对等

describe('the list of all flavors', () => {
  it('contains haha', () => {
     var getAllFlavors = require('../js/sum');
    expect(getAllFlavors()).toContain('haha');
  });
});

.toEqual(value)

使用.toEqual当您想要检查两个对象具有相同的值。递归检查所有的字段是否相等,而不是检查对象的属性。例如,toEqual和toBr这个测试组件的反应是不同的

const can1 = {
  flavor: 'grapefruit',
  ounces: 12,
};
const can2 = {
  flavor: 'grapefruit',
  ounces: 12,
};

describe('the La Croix cans on my desk', () => {
  it('have all the same properties', () => {
    expect(can1).toEqual(can2);
  });
  it('are not the exact same can', () => {
    expect(can1).not.toBe(can2);
  });
});

.toHaveLength(number)

长度属性,设置一定的数值,这是特别有用的检查数组或字符串的大小。

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

.toHaveLength(number)

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

.toMatch(regexp)

describe('an essay on the best flavor', () => {
  it('mentions grapefruit', () => {
    expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
    expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
  })
})

describe('grapefruits are healthy', () => {
  it('grapefruits are a fruit', () => {
    expect('grapefruits').toMatch('fruit');
  })
})

.toMatchObject(object)

const houseForSale = {
    bath: true,
    kitchen: {
        amenities: ['oven', 'stove', 'washer'],
        area: 20,
        wallColor: 'white'
    },
  bedrooms: 4
};
const desiredHouse = {
    bath: true,
    kitchen: {
        amenities: ['oven', 'stove', 'washer'],
        wallColor: 'white'
    }
};

describe('looking for a new house', () => {
    it('the house has my desired features', () => {
        expect(houseForSale).toMatchObject(desiredHouse);
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

‘画卷フ

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文