chai-like
一個用於 Chai 的 JSON 匹配器。當您測試 API 並想忽略某些屬性(例如:updatedAt、createdAt、id)時,這非常有用。
安裝
使用 npm 安裝
npm install --save-dev chai-like
斷言
like(value)
比較兩個 JSON 並根據期望忽略某些鍵。
var object = {
id: 1,
name: 'test',
updatedAt: 'now'
};
object.should.like({
name: 'test'
});
object.should.not.like({
name: 'test1'
});
深度比較。
var object = {
id: 1,
name: 'test',
product: {
id: 1,
name: 'product'
},
updatedAt: 'now'
};
object.should.like({
name: 'test',
product: {
name: 'product'
}
});
object.should.not.like({
name: 'test',
product: {
name: 'product1'
}
});
比較陣列。
var array = [{
id: 1,
name: 'test',
product: {
id: 1,
name: 'product'
},
updatedAt: 'now'
}];
array.should.like([{
name: 'test',
product: {
name: 'product'
}
}]);
array.should.not.like([{
name: 'test',
product: {
name: 'product1'
}
}]);
比較具有陣列子節點的 JSON。
var object = {
id: 1,
name: 'test',
products: [{
id: 1,
name: 'product'
}],
updatedAt: 'now'
};
object.should.like({
name: 'test',
products: [{
name: 'product'
}]
});
object.should.not.like({
name: 'test',
products: [{
name: 'product1'
}]
});
外掛
您可以按照以下格式使用外掛擴展 chai-like
var chai = require('chai');
var like = require('chai-like');
var numberStringPlugin = {
match: function(object) {
return !isNaN(Number(object));
},
assert: function(object, expected) {
return object === Number(expected);
}
};
like.extend(numberStringPlugin);
chai.use(like);
然後我們可以如下斷言
var object = {
number: 123
};
object.should.like({
number: '123'
});
object.should.not.like({
number: 'not a number'
});
用於使用 RegExp 測試字串的外掛
如果某些字串需要模糊匹配,我們可以透過以下外掛來實現
var chai = require('chai');
var like = require('chai-like');
var regexPlugin = like.extend({
match: function(object, expected) {
return typeof object === 'string' && expected instanceof RegExp;
},
assert: function(object, expected) {
return expected.test(object);
}
});
like.extend(regexPlugin);
chai.use(like);
然後我們可以如下斷言
var object = {
text: 'the quick brown fox jumps over the lazy dog'
};
object.should.like({
text: /.* jumps over .*/
});
object.should.not.like({
text: /\d/
});