summaryrefslogtreecommitdiff
path: root/test/streaming.ts
blob: 63ee1e884597d5c708455cd5fda109801e87a736 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * Tests of streaming API
 *
 * How to run the tests:
 * > mocha test/streaming.ts --require ts-node/register
 *
 * To specify test:
 * > mocha test/streaming.ts --require ts-node/register -g 'test name'
 */

import * as http from 'http';
import * as WebSocket from 'ws';
import * as assert from 'chai';
import { _signup, _request, _uploadFile, _post, _react, resetDb } from './utils';

assert.use(require('chai-http'));
const expect = assert.expect;

//#region process
Error.stackTraceLimit = Infinity;

// During the test the env variable is set to test
process.env.NODE_ENV = 'test';

// Display detail of unhandled promise rejection
process.on('unhandledRejection', console.dir);
//#endregion

const app = require('../built/server/api').default;
const server = require('../built/server').startServer();
const db = require('../built/db/mongodb').default;

const apiServer = http.createServer(app.callback());

//#region Utilities
const request = _request(apiServer);
const signup = _signup(request);
//#endregion

describe('Streaming', () => {
	// Reset database each test
	beforeEach(resetDb(db));

	before(() => {
		server.close();
	});

	it('投稿がタイムラインに流れる', done => {
		const post = {
			text: 'foo'
		};

		signup().then(me => {
			const ws = new WebSocket(`ws://localhost/streaming?i=${me.token}`);

			ws.on('open', () => {
				ws.on('message', data => {
					const msg = JSON.parse(data.toString());
					if (msg.type == 'channel' && msg.body.id == 'a') {
						if (msg.body.type == 'note') {
							expect(msg.body.body.text).eql(post.text);
							ws.close();
							done();
						}
					} else if (msg.type == 'connected' && msg.body.id == 'a') {
						request('/notes/create', post, me);
					}
				});

				ws.send(JSON.stringify({
					type: 'connect',
					body: {
						channel: 'homeTimeline',
						id: 'a',
						pong: true
					}
				}));
			});
		});
	});
});