chai-fuzzy

基於 underscore 並受 jasmine 啟發的 chai 模糊匹配器。

建立斷言,檢查數值是否具有相同的屬性和值,而無需斷言嚴格的物件相等性。

Build Status

使用方法

另請參閱測試範例

瀏覽器端

在 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 風格的相容性