Initial commit
[yaffs-website] / node_modules / unique-stream / test / index.js
1 var expect = require('chai').expect
2   , unique = require('..')
3   , Stream = require('stream')
4   , after = require('after')
5   , setImmediate = global.setImmediate || process.nextTick;
6
7 describe('unique stream', function() {
8
9   function makeStream(type) {
10     var s = new Stream();
11     s.readable = true;
12
13     var n = 10;
14     var next = after(n, function () {
15       setImmediate(function () {
16         s.emit('end');
17       });
18     });
19
20     for (var i = 0; i < n; i++) {
21       var o = {
22         type: type,
23         name: 'name ' + i,
24         number: i * 10
25       };
26
27       (function (o) {
28         setImmediate(function () {
29           s.emit('data', o);
30           next();
31         });
32       })(o);
33     }
34     return s;
35   }
36
37   it('should be able to uniqueify objects based on JSON data', function(done) {
38     var aggregator = unique();
39     makeStream('a')
40       .pipe(aggregator);
41     makeStream('a')
42       .pipe(aggregator);
43
44     var n = 0;
45     aggregator
46       .on('data', function () {
47         n++;
48       })
49       .on('end', function () {
50         expect(n).to.equal(10);
51         done();
52       });
53   });
54
55   it('should be able to uniqueify objects based on a property', function(done) {
56     var aggregator = unique('number');
57     makeStream('a')
58       .pipe(aggregator);
59     makeStream('b')
60       .pipe(aggregator);
61
62     var n = 0;
63     aggregator
64       .on('data', function () {
65         n++;
66       })
67       .on('end', function () {
68         expect(n).to.equal(10);
69         done();
70       });
71   });
72
73   it('should be able to uniqueify objects based on a function', function(done) {
74     var aggregator = unique(function (data) {
75       return data.name;
76     });
77
78     makeStream('a')
79       .pipe(aggregator);
80     makeStream('b')
81       .pipe(aggregator);
82
83     var n = 0;
84     aggregator
85       .on('data', function () {
86         n++;
87       })
88       .on('end', function () {
89         expect(n).to.equal(10);
90         done();
91       });
92   });
93
94   it('should be able to handle uniqueness when not piped', function(done) {
95     var stream = unique();
96     var count = 0;
97     stream.on('data', function (data) {
98       expect(data).to.equal('hello');
99       count++;
100     });
101     stream.on('end', function() {
102       expect(count).to.equal(1);
103       done();
104     });
105     stream.write('hello');
106     stream.write('hello');
107     stream.end();
108   });
109 });