aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/test/javascript/src/test_helpers/consumer_test_helper.coffee
blob: a9e95c37f0d4f4b82b8fff8edd30964f55053be4 (plain) (blame)
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
#= require mock-socket

{TestHelpers} = ActionCable

TestHelpers.consumerTest = (name, options = {}, callback) ->
  unless callback?
    callback = options
    options = {}

  options.url ?= TestHelpers.testURL

  QUnit.test name, (assert) ->
    doneAsync = assert.async()

    ActionCable.WebSocket = MockWebSocket
    server = new MockServer options.url
    consumer = ActionCable.createConsumer(options.url)

    server.on "connection", ->
      clients = server.clients()
      assert.equal clients.length, 1
      assert.equal clients[0].readyState, WebSocket.OPEN

    server.broadcastTo = (subscription, data = {}, callback) ->
      data.identifier = subscription.identifier

      if data.message_type
        data.type = ActionCable.INTERNAL.message_types[data.message_type]
        delete data.message_type

      server.send(JSON.stringify(data))
      TestHelpers.defer(callback)

    done = ->
      consumer.disconnect()
      server.close()
      doneAsync()

    testData = {assert, consumer, server, done}

    if options.connect is false
      callback(testData)
    else
      server.on "connection", ->
        testData.client = server.clients()[0]
        callback(testData)
      consumer.connect()