diff-obj
Version:
108 lines (92 loc) • 3.21 kB
JavaScript
const diff = require('../lib/diff');
const assert = require('assert');
describe('比较对象 #diff', function() {
describe('比较正常对象', function() {
it('比较单层对象', function() {
const from = {
productId: 10043,
name: '大大泡泡糖',
price: '11.10',
recommends: [11, 22, 33],
};
const to = {
productId: 10043,
name: '大大泡泡糖(香草拿铁)',
count: 20,
recommends: [11, 22, 33],
};
const result = diff(from, to);
const {added, removed, changed, unchanged} = result;
assert.equal(added.count.from, undefined);
assert.equal(added.count.to, to.count);
assert.equal(removed.price.from, from.price);
assert.equal(removed.price.to, undefined);
assert.equal(changed.name.from, from.name);
assert.equal(changed.name.to, to.name);
assert.equal(unchanged.productId.from, from.productId);
assert.equal(unchanged.productId.to, to.productId);
assert.equal(unchanged.recommends.from, from.recommends);
assert.equal(unchanged.recommends.to, to.recommends);
});
it('比较多层对象', function() {
const from = {
productId: 10043,
name: '大大泡泡糖',
photo: {
url: 'http://apple/a.png',
title: 'apple',
size: {
width: 120,
height: 60,
},
},
comment: {
content: '啦啦啦',
},
price: {
amount: '120.00',
},
recommends: [11, 22, 33],
};
const to = {
productId: 10043,
name: '大大泡泡糖(香草拿铁)',
photo: {
url: 'http://apple/b.png',
title: 'apple',
size: {
width: 120,
height: 120,
},
},
price: '120.00',
stock: {
sellable: 99,
locked: 1,
},
recommends: ['11', 22, 33],
};
const result = diff(from, to);
const {added, removed, changed, unchanged} = result;
console.log(result);
assert.equal(added.stock.from, undefined);
assert.equal(added.stock.to, to.stock);
assert.equal(removed.comment.from, from.comment);
assert.equal(removed.comment.to, undefined);
assert.equal(changed.name.from, from.name);
assert.equal(changed.name.to, to.name);
assert.equal(changed['photo.url'].from, from.photo.url);
assert.equal(changed['photo.url'].to, to.photo.url);
assert.equal(changed['photo.size.height'].from, from.photo.size.height);
assert.equal(changed['photo.size.height'].to, to.photo.size.height);
assert.equal(changed.price.from, from.price);
assert.equal(changed.price.to, to.price);
assert.equal(changed.recommends.from, from.recommends);
assert.equal(changed.recommends.to, to.recommends);
assert.equal(unchanged.productId.from, from.productId);
assert.equal(unchanged.productId.to, to.productId);
assert.equal(unchanged['photo.title'].from, from.photo.title);
assert.equal(unchanged['photo.title'].to, to.photo.title);
});
});
});