chai-match-pattern
chai-match-pattern 是一个用于深度匹配 JSON 对象的瑞士军刀。它本质上是 lodash-match-pattern
的 Chai 包装器,关于其模式匹配功能的详细文档可以在那里找到。此功能包括通过以下方式深度匹配 JSON 属性:
- 精确值
- 正则表达式
- 来自
checkit
的任何匹配器(例如_.isURL
、_.isEmail
) - 来自
lodash
的任何匹配器(例如_.isObject
、_.isNaN
) - 部分匹配
- 自定义匹配函数
- 过滤后的值
- 等等…
基本用法
# with npm
npm install chai-match-pattern --save-dev
# or with yarn
yarn add --dev chai-match-pattern
在您的测试文件中插入
const chai = require('chai');
const chaiMatchPattern = require('chai-match-pattern');
chai.use(chaiMatchPattern);
const _ = chaiMatchPattern.getLodashModule(); // recommend using our lodash extension
然后使用模式使用 .matchPattern(pattern)
断言函数检查您的 JSON。例如
chai.expect({a: 1, b: 'abc'}).to.matchPattern({a: 1, b: _.isString});
请参阅 lodash-match-pattern
获取更多详细信息。
此外,任何包含的 isXxxx
函数都可以直接用作断言函数。例如
chai.expect(7.5).isBetween(7, 8);