chai-fuzzy
基于 underscore 并受 jasmine 启发的 chai 模糊匹配器。
执行断言,确认值具有相同的属性和值,而不断言严格的 객체 相等性。
使用
浏览器端
在 chai 和 underscore 之后包含 chai fuzzy
<script src="underscore.js"></script>
<script src="chai.js"></script>
<script src="chai-fuzzy.js"></script>
服务器端
让 chai 使用 chai-fuzzy
var chai = require('chai');
chai.use(require('chai-fuzzy'));
断言
like(value)
比较对象属性和值,而不是检查它们是否为相同的引用
var subject = {a: 'a'};
subject.should.be.like({a: 'a'});
subject.should.not.be.like({x: 'x'});
subject.should.not.be.like({a: 'a', b: 'b'});
expect(subject).to.be.like({a: 'a'});
expect(subject).not.to.be.like({x: 'x'});
expect(subject).not.to.be.like({a: 'a', b: 'b'});
assert.like(subject, {a: 'a'});
assert.notLike(subject, {x: 'x'});
assert.notLike(subject, {a: 'a', b: 'b'});
var subject = ['a'];
subject.should.be.like(['a']);
subject.should.not.be.like(['x']);
subject.should.not.be.like(['a', 'b']);
expect(subject).to.be.like(['a']);
expect(subject).not.to.be.like(['x']);
expect(subject).not.to.be.like(['a', 'b']);
assert.like(subject, ['a']);
assert.notLike(subject, ['x']);
assert.notLike(subject, ['a', 'b']);
containOneLike(value)
检查容器的第一级,以查找与提供的值类似的值
var subject = {
a: 'alphabet'
, b: 'butternut'
, c: {
name: 'chowder'
, attributes: [
'scales'
, 'fins'
]
}
, x: 'xylophone'
, z: 'xylophone'
};
subject.should.containOneLike({
name: 'chowder'
, attributes: [
'scales', 'fins'
]
});
subject.should.not.containOneLike({
name: 'chowder'
, attributes: [
'scales', 'fins', 'cream'
]
});
subject.should.containOneLike('xylophone');
subject.should.not.containOneLike('cow patties');
expect(subject).to.containOneLike('xylophone');
expect(subject).to.not.containOneLike('cow patties');
assert.containOneLike(subject, 'xylophone');
assert.notContainOneLike(subject, 'cow patties');
// same for arrays
jsonOf(value)
检查给定的 javascript 对象是否与 JSON 化的预期值类似。这对于检查对象的字符串化和解析很有用。
var apple = {
skin: 'thin'
, colors: ['red', 'green', 'yellow']
, isFruit: true
, picked: new Date()
};
var orange = {
skin: 'thin'
, colors: ['red', 'green', 'yellow']
, isFruit: true
, picked: new Date()
};
// here appleJSON would be the json result of some process like a JSON api
var appleJSON = JSON.parse(JSON.stringify(apple));
appleJSON.should.be.jsonOf(apple);
appleJSON.should.not.be.jsonOf(orange);
expect(appleJSON).to.be.jsonOf(apple);
expect(appleJSON).to.not.be.jsonOf(orange);
assert.jsonOf(appleJSON, apple);
assert.notJsonOf(appleJSON, orange);
致谢
感谢 Davis 传递了使用 underscore 而不是从 jasmine 中借用部分的想法。
感谢 Bart van der Schoor 添加 assert 风格的兼容性