UNPKG

3.01 kBJavaScriptView Raw
1// test changing properties
2
3var assert = require('assert');
4var after = require('after');
5
6var Model = require('../model');
7
8suite('events');
9
10// placeholder for the Post model
11var Post = Model({
12 title: String,
13 author: {
14 name: String,
15 email: String
16 }
17});
18
19test('top level changes', function(done) {
20 var post = Post();
21
22 post.once('change title', function(val) {
23 assert.equal(val, 'foobar');
24 assert.equal(post.title, 'foobar');
25 done();
26 });
27
28 post.title = 'foobar';
29});
30
31// changing the primary should trigger event on primary
32// and on subfield
33// then you should still be able to change the subfield
34// and trigger event only on subfield
35test('nested change - primary', function(done) {
36 var post = Post();
37
38 // because author is a nested object
39 // but will start out undefined
40 assert.ok(post.author === undefined);
41
42 done = after(2, done);
43
44 post.once('change author', function(val) {
45 assert.deepEqual(val, { name: undefined, email: undefined });
46 assert.equal(post.author.name, undefined);
47 done();
48 });
49
50 // need to set author to something first
51 post.author = {};
52
53 post.once('change author.name', function(val) {
54 assert.equal(val, 'Edgar Poe');
55 assert.equal(post.author.name, 'Edgar Poe');
56 done();
57 });
58
59 // setting this will trigger above change
60 post.author.name = 'Edgar Poe';
61});
62
63// changing entire subobject should trigger change in primary
64// and subfield
65test('nested change - field', function(done) {
66 var post = Post();
67
68 // because author is a nested object
69 // but will start out undefined
70 assert.ok(post.author === undefined);
71
72 post.once('change author', function(val) {
73 assert.equal(val.name, 'Edgar Poe');
74 assert.equal(post.author.name, 'Edgar Poe');
75 done();
76 });
77
78 // setting the author should trigger property change too
79 post.author = {
80 name: 'Edgar Poe'
81 };
82});
83
84// we change the entire sub object
85// then we expect to be able to change inner properties and events will fire
86test('obj change then trigger', function(done) {
87 var post = Post({
88 author: {
89 name: 'foobar'
90 }
91 });
92
93 assert.ok(post.author);
94 assert.equal(post.author.name, 'foobar');
95
96 post.once('change author', function(val) {
97 assert.equal(val.name, 'Poe');
98 assert.equal(post.author.name, 'Poe');
99 assert.equal(val.email, 'poe@example.com');
100 assert.equal(post.author.email, 'poe@example.com');
101 });
102
103 post.author = {
104 name: 'Poe',
105 email: 'poe@example.com'
106 };
107
108 // now we should still be able to alter an internal property on author
109
110 post.once('change author.email', function(val) {
111 assert.equal(val, 'edgar@example.com');
112 assert.equal(post.author.email, 'edgar@example.com');
113 done();
114 });
115
116 // same as post.author.email
117 post.author.email = 'edgar@example.com';
118});