Build status Coverage Status npm/chai-like version license

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'
  });

用于测试带有正则表达式的字符串的插件

如果某些字符串需要模糊匹配,我们可以使用以下插件来实现

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/
});