summaryrefslogtreecommitdiffstats
path: root/test/client-reconnect.js
blob: ae1a206de638671d1c7532704efe2e253a6cd453 (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
'use strict'

const { test } = require('tap')
const { Client } = require('..')
const { createServer } = require('http')
const FakeTimers = require('@sinonjs/fake-timers')
const timers = require('../lib/timers')

test('multiple reconnect', (t) => {
  t.plan(5)

  let n = 0
  const clock = FakeTimers.install()
  t.teardown(clock.uninstall.bind(clock))

  const orgTimers = { ...timers }
  Object.assign(timers, { setTimeout, clearTimeout })
  t.teardown(() => {
    Object.assign(timers, orgTimers)
  })

  const server = createServer((req, res) => {
    n === 0 ? res.destroy() : res.end('ok')
  })
  t.teardown(server.close.bind(server))

  server.listen(0, () => {
    const client = new Client(`http://localhost:${server.address().port}`)
    t.teardown(client.destroy.bind(client))

    client.request({ path: '/', method: 'GET' }, (err, data) => {
      t.ok(err)
      t.equal(err.code, 'UND_ERR_SOCKET')
    })

    client.request({ path: '/', method: 'GET' }, (err, data) => {
      t.error(err)
      data.body
        .resume()
        .on('end', () => {
          t.pass()
        })
    })

    client.on('disconnect', () => {
      if (++n === 1) {
        t.pass()
      }
      process.nextTick(() => {
        clock.tick(1000)
      })
    })
  })
})