Build status Coverage Status npm/chai-like version license

chai-like

chaiのJSONマッチャーです。これはAPIをテストし、updatedAt、createdAt、idなどの属性を無視する場合に本当に便利です。

インストール

npmを使用してインストールしますnpm

npm install --save-dev chai-like

アサーション

like(value)

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