driver.spec.ts 12.7 KB
Newer Older
1
2
process.env.LOG_LEVEL = 'silent' // suppress API logs

3
import 'mocha'
4
5
import sinon from 'sinon'
import { expect } from 'chai'
6
import { silence } from './log'
7
import { botUser, mockUser } from '../utils/config'
8
import * as utils from '../utils/testing'
9
import * as driver from './driver'
10
import * as methodCache from './methodCache'
11
const initEnv = process.env // store configs to reset after tests
12
13
const credentials = { username: botUser.username, password: botUser.password }
const delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms))
14
15
let clock

16
17
18
describe('driver', () => {
  silence() // suppress log during tests (disable this while developing tests)
  before(() => utils.setup()) // add user accounts for bot and mock user
19
  
20
21
22
23
24
25
26
27
28
29
30
31
32
  describe('.connect', () => {
    context('with localhost connection', () => {
      it('without args, returns a promise', () => {
        const promise = driver.connect()
        expect(promise.then).to.be.a('function')
        promise.catch((err) => console.error(err))
        return promise
      })
      it('accepts an error-first callback, providing asteroid', (done) => {
        driver.connect({}, (err, asteroid) => {
          expect(err).to.equal(null)
          expect(asteroid).to.be.an('object')
          done()
33
        })
34
      })
35
36
37
38
39
40
41
      it('without url takes localhost as default', (done) => {
        driver.connect({}, (err, asteroid) => {
          expect(err).to.eql(null)
          // const connectionHost = asteroid.endpoint
          const connectionHost = asteroid._host
          expect(connectionHost).to.contain('localhost:3000')
          done()
42
        })
43
44
45
46
47
48
      })
      it('promise resolves with asteroid in successful state', () => {
        return driver.connect({}).then((asteroid) => {
          const isActive = asteroid.ddp.readyState === 1
          // const isActive = asteroid.ddp.status === 'connected'
          expect(isActive).to.equal(true)
49
        })
50
51
52
53
      })
      it('provides the asteroid instance to method cache', () => {
        return driver.connect().then((asteroid) => {
          expect(methodCache.instance).to.eql(asteroid)
54
        })
55
56
57
58
59
60
61
62
63
64
65
      })
    })
    context('with timeout, on expiry', () => {
      before(() => clock = sinon.useFakeTimers(0))
      after(() => clock.restore())
      it('with url, attempts connection at URL', (done) => {
        driver.connect({ host: 'localhost:9999', timeout: 100 }, (err, asteroid) => {
          expect(err).to.be.an('error')
          const connectionHost = asteroid.endpoint || asteroid._host
          expect(connectionHost).to.contain('localhost:9999')
          done()
66
        })
67
68
69
70
71
72
73
74
75
        clock.tick(200)
      })
      it('returns error', (done) => {
        let opts = { host: 'localhost:9999', timeout: 100 }
        driver.connect(opts, (err, asteroid) => {
          const isActive = (asteroid.ddp.readyState === 1)
          expect(err).to.be.an('error')
          expect(isActive).to.eql(false)
          done()
76
        })
77
78
79
80
81
82
83
84
85
86
87
88
        clock.tick(200)
      })
      it('without callback, triggers promise catch', () => {
        const promise = driver.connect({ host: 'localhost:9999', timeout: 100 })
        .catch((err) => expect(err).to.be.an('error'))
        clock.tick(200)
        return promise
      })
      it('with callback, provides error to callback', (done) => {
        driver.connect({ host: 'localhost:9999', timeout: 100 }, (err) => {
          expect(err).to.be.an('error')
          done()
89
        })
90
        clock.tick(200)
91
92
      })
    })
93
  })
94
  
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
  // describe('disconnect', () => {
    // Disabled for now, as only Asteroid v2 has a disconnect method
    // it('disconnects from asteroid', async () => {
    //   await driver.connect()
    //   const asteroid = await driver.connect()
    //   await driver.disconnect()
    //   const isActive = asteroid.ddp.readyState === 1
    //   // const isActive = asteroid.ddp.status === 'connected'
    //   expect(isActive).to.equal(false)
    // })
  // })
  describe('.login', () => {
    it('sets the bot user status to online', async () => {
      await driver.connect()
      await driver.login(credentials)
      const result = await utils.getUserData({ username: botUser.username })
      expect(result.user.status).to.equal('online')
    })
  })
  describe('.subscribeToMessages', () => {
    it('resolves with subscription object', async () => {
      await driver.connect()
      await driver.login(credentials)
      const subscription = await driver.subscribeToMessages()
      expect(subscription).to.have.property('ready')
      // expect(subscription.ready).to.have.property('state', 'fulfilled') ????
    })
  })
  describe('.reactToMessages', () => {
    afterEach(() => delay(500)) // avoid rate limit
    it('calls callback on every subscription update', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const callback = sinon.spy()
      driver.reactToMessages(callback)
      await utils.sendFromUser({ text: 'SDK test `subscribeToMessages` 1' })
      await delay(500)
      await utils.sendFromUser({ text: 'SDK test `subscribeToMessages` 2' })
      expect(callback.callCount).to.equal(2)
    })
    it('calls callback with sent message object', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const callback = sinon.spy()
      driver.reactToMessages(callback)
      await utils.sendFromUser({ text: 'SDK test `subscribeToMessages` 3' })
      const messageArgs = callback.getCall(0).args[1]
      expect(messageArgs.msg).to.equal('SDK test `subscribeToMessages` 3')
    })
  })
147
148
  describe('.sendToRoomId', () => {
    it('sends string to the given room id', async () => {
149
150
151
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
      const result = await driver.sendToRoomId('SDK test `sendToRoomId`', 'GENERAL')
      expect(result).to.include.all.keys(['msg', 'rid', '_id'])
    })
    it('sends array of strings to the given room id', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const result = await driver.sendToRoomId([
        'SDK test `sendToRoomId` A',
        'SDK test `sendToRoomId` B'
      ], 'GENERAL')
      expect(result).to.be.an('array')
      expect(result[0]).to.include.all.keys(['msg', 'rid', '_id'])
      expect(result[1]).to.include.all.keys(['msg', 'rid', '_id'])
    })
  })
  describe('.sendToRoom', () => {
    it('sends string to the given room name', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const result = await driver.sendToRoom('SDK test `sendToRoom`', 'general')
      expect(result).to.include.all.keys(['msg', 'rid', '_id'])
    })
    it('sends array of strings to the given room name', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const result = await driver.sendToRoom([
        'SDK test `sendToRoom` A',
        'SDK test `sendToRoom` B'
      ], 'general')
      expect(result).to.be.an('array')
      expect(result[0]).to.include.all.keys(['msg', 'rid', '_id'])
      expect(result[1]).to.include.all.keys(['msg', 'rid', '_id'])
    })
  })
  describe('.sendDirectToUser', () => {
    it('sends string to the given room name', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const result = await driver.sendDirectToUser('SDK test `sendDirectToUser`', mockUser.username)
      expect(result).to.include.all.keys(['msg', 'rid', '_id'])
    })
    it('sends array of strings to the given room name', async () => {
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
      const result = await driver.sendDirectToUser([
        'SDK test `sendDirectToUser` A',
        'SDK test `sendDirectToUser` B'
      ], mockUser.username)
      expect(result).to.be.an('array')
      expect(result[0]).to.include.all.keys(['msg', 'rid', '_id'])
      expect(result[1]).to.include.all.keys(['msg', 'rid', '_id'])
208
    })
209
  })
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
  describe('.respondDefaults', () => {
    afterEach(() => process.env = initEnv)
    it('all configs default to false if env undefined', () => {
      delete process.env.LISTEN_ON_ALL_PUBLIC
      delete process.env.RESPOND_TO_DM
      delete process.env.RESPOND_TO_LIVECHAT
      delete process.env.RESPOND_TO_EDITED
      const defaults = driver.respondDefaults()
      expect(defaults).to.eql({
        allPublic: false,
        dm: false,
        livechat: false,
        edited: false
      })
    })
    it('inherits config from env defaults', () => {
      process.env.LISTEN_ON_ALL_PUBLIC = 'false'
      process.env.RESPOND_TO_DM = 'true'
      process.env.RESPOND_TO_LIVECHAT = 'true'
      process.env.RESPOND_TO_EDITED = 'true'
      const defaults = driver.respondDefaults()
      expect(defaults).to.eql({
        allPublic: false,
        dm: true,
        livechat: true,
        edited: true
      })
    })
  })
  describe('.respondToMessages', () => {
    beforeEach(async () => {
      delete process.env.LISTEN_ON_ALL_PUBLIC
      delete process.env.RESPOND_TO_DM
      delete process.env.RESPOND_TO_LIVECHAT
      delete process.env.RESPOND_TO_EDITED
      await driver.connect()
      await driver.login(credentials)
      await driver.subscribeToMessages()
    })
    afterEach(() => process.env = initEnv)
    it('ignores messages sent from bot', async () => {
      const callback = sinon.spy()
      driver.respondToMessages(callback)
253
      await driver.sendToRoomId('SDK test `respondToMessages`', 'GENERAL')
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
      sinon.assert.notCalled(callback)
    })
    it('fires callback on messages in joined rooms', async () => {
      const callback = sinon.spy()
      driver.respondToMessages(callback)
      await utils.sendFromUser({ text: 'SDK test `respondToMessages` 1' })
      sinon.assert.calledOnce(callback)
    })
    it('by default ignores edited messages', async () => {
      const callback = sinon.spy()
      const sentMessage = await utils.sendFromUser({ text: 'SDK test `respondToMessages` sent' })
      driver.respondToMessages(callback)
      const updated = await utils.updateFromUser({
        roomId: 'GENERAL',
        msgId: sentMessage.message._id,
        text: 'SDK test `respondToMessages` edited'
      })
      sinon.assert.notCalled(callback)
    })
    it('fires callback on edited message if configured', async () => {
      const callback = sinon.spy()
      const sentMessage = await utils.sendFromUser({ text: 'SDK test `respondToMessages` sent' })
      driver.respondToMessages(callback, { edited: true })
      const updated = await utils.updateFromUser({
        roomId: 'GENERAL',
        msgId: sentMessage.message._id,
        text: 'SDK test `respondToMessages` edited'
      })
      sinon.assert.calledOnce(callback)
    })
    it('by default ignores DMs', async () => {
      const dmResult = await utils.setupDirectFromUser()
      const callback = sinon.spy()
      driver.respondToMessages(callback)
      await utils.sendFromUser({ text: 'SDK test `respondToMessages` DM', roomId: dmResult.room._id })
      sinon.assert.notCalled(callback)
    })
    it('fires callback on DMs if configured', async () => {
      const dmResult = await utils.setupDirectFromUser()
      const callback = sinon.spy()
      driver.respondToMessages(callback, { dm: true })
      await utils.sendFromUser({ text: 'SDK test `respondToMessages` DM', roomId: dmResult.room._id })
      sinon.assert.calledOnce(callback)
    })
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    it('appends room name to event meta in channels', async () => {
      const callback = sinon.spy()
      driver.respondToMessages(callback, { dm: true })
      await utils.sendFromUser({ text: 'SDK test `respondToMessages` DM' })
      expect(callback.firstCall.args[2].roomName).to.equal('general')
    })
    it('room name is undefined in direct messages', async () => {
      const dmResult = await utils.setupDirectFromUser()
      const callback = sinon.spy()
      driver.respondToMessages(callback, { dm: true })
      await utils.sendFromUser({ text: 'SDK test `respondToMessages` DM', roomId: dmResult.room._id })
      expect(callback.firstCall.args[2].roomName).to.equal(undefined)
    })
  })
  describe('.getRoomName', () => {
    beforeEach(async () => {
      await driver.connect()
      await driver.login(credentials)
    })
    it('returns the name for a channel by ID', async () => {
      const room = await driver.getRoomName('GENERAL')
      expect(room).to.equal('general')
    })
    it('returns undefined for a DM room', async () => {
      const dmResult = await utils.setupDirectFromUser()
      const room = await driver.getRoomName(dmResult.room._id)
      expect(room).to.equal(undefined)
    })
326
  })
327
})