介绍
chai-things 是一个用于扩展 chai.js 断言库的插件,它允许我们查询集合中是否包含目标元素、是否存在特定属性等等。这个插件在处理包含数组和对象的集合时非常方便。
安装
在使用 chai-things 插件前,需要先安装 Chai 断言库。
$ npm install chai --save-dev
然后安装 chai-things 插件:
$ npm install chai-things --save-dev
使用
在测试文件中引入 Chai 断言库和 chai-things 插件:
const chai = require('chai');
const chaiThings = require('chai-things');
chai.use(chaiThings);
const expect = chai.expect;include.something
include.something 用于判断一个集合中是否包含目标元素。
const array = ['foo', 'bar', 'baz'];
expect(array).to.include.something.that.equals('foo');include.all.members
include.all.members 用于判断一个集合中是否包含所有指定元素。
const array = ['foo', 'bar', 'baz']; expect(array).to.include.all.members(['foo', 'bar']);
contain.a.thing.with.property
contain.a.thing.with.property 用于判断一个集合中是否存在元素,该元素拥有指定的属性。
const array = [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}];
expect(array).to.contain.a.thing.with.property('name', 'baz');注意事项
当使用
include或contain时,集合中的元素顺序不影响测试结果。当使用
include.something进行测试,如果集合中存在多个目标元素,则仅仅会测试到第一个目标元素。当使用
contain.a.thing.with.property进行测试,如果集合中存在多个拥有指定属性的元素,则仅仅会测试到第一个元素。
示例代码
假设我们有一个名为 getUsers 的方法,用于获取用户列表:
function getUsers() {
return [
{username: 'tom', age: 20},
{username: 'jack', age: 30},
{username: 'tim', age: 25}
];
}我们可以使用 chai-things 插件测试该方法的返回值:
-- -------------------- ---- -------
-------------------- -- -- -
---------- ------ -- ----- ---- -------- --------- ---- -------- ---------- ---- ------ ------- -- -- -
----- ----- - -----------
--------------------------------
---------------------------------------------------------------- -------
---
---------- ------ -- ----- ---- -------- --- ------- ------- --------- -- -- -
----- --------- - ------- --------
----- ----- - -----------
--------------------------------
------------------------------------------------
---
---------- ------ -- ----- ---- -------- - ----- ---- -------- ---------- ---- ------ ------ --- -------- ----- ---- ------ ---- -- -- -
----- ----- - -----------
--------------------------------
---------------------------------------------------------- --------------------------- ----
---
---运行测试:
-- -------------------- ---- -------
- ----- -------
--------
- ------ ------ -- ----- ---- -------- --------- ---- -------- ---------- ---- ------ -----
- ------ ------ -- ----- ---- -------- --- ------- ------- -------
- ------ ------ -- ----- ---- -------- - ----- ---- -------- ---------- ---- ------ ------ --- -------- ----- ---- ------ --
- ------- ------总结
chai-things 插件为 chai.js 断言库提供了方便的集合测试方法。我们可以使用 include.something、include.all.members 和 contain.a.thing.with.property 等方法进行测试,实现方便高效的集合测试。在使用过程中需要注意注意事项,避免出现误判的情况。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/64703a78968c7c53b0e5bd1b