var assert = require('assert') , collection_json = require('../'); function identity(x) { return x; } function collection1() { return collection_json.fromObject({collection: { items: [ { href: "http://example.com/1", links: [], data: [ { prompt: "prompt1", name: "field-1", value: "1", baz: "woot" }, { prompt: "prompt2", name: "field-2", value: "2", foz: "asdf" }, ] }, { href: "http://example.com/2", links: [], data: [ { prompt: "prompt1", name: "field-1", value: "3" }, { prompt: "prompt2", name: "field-2", value: "4" }, ] } ] }}); } function template1() { return collection_json.fromObject({template: { data: [ { name: 'field-1', value: 'value-1', zap: 'zoot' }, { name: 'field-2' } ] }}); } describe('fromObject', function() { it('Has basic fields on a collection', function() { var collection = collection_json.fromObject({}).collection; assert.deepEqual(collection.items, []); assert.deepEqual(collection.links, []); assert.deepEqual(collection.queries, []); assert.equal(collection.template, undefined); }); // Assert what a template object should look like it('Has basic fields on a template', function() { var template = collection_json.fromObject({template: {}}).template; assert.equal(template.items, undefined); assert.equal(template.links, undefined); assert.equal(template.queries, undefined); assert.equal(typeof template.data, 'object'); }); it('Can map data field in items', function() { assert.deepEqual(collection1().mapItems(identity), [{"field-1": "1", "field-2": "2"} ,{"field-1": "3", "field-2": "4"}]); function f(map) { return parseInt(map["field-1"]) + parseInt(map["field-2"]); } assert.deepEqual(collection1().mapItems(f), [3, 7]); }); /* */ it('Knows the difference between silly objects, collections and templates', function() { var silly = collection_json.fromObject({}); var collection = collection_json.fromObject(collection1()); var template = collection_json.fromObject(template1()); assert.equal(template.isCollection(), false); assert.equal(template.isTemplate(), true); assert.equal(silly.isCollection(), true); assert.equal(silly.isTemplate(), false); assert.equal(collection.isCollection(), true); assert.equal(collection.isTemplate(), false); }); }); describe('collection object', function() { it('Can create objects from items', function() { assert.deepEqual(collection1().collection.items[0].toObject(), { "field-1": "1", "field-2": "2" }); }); });