/
test_socketdelay.js
141 lines (110 loc) · 2.9 KB
/
test_socketdelay.js
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
82
83
84
85
86
87
88
89
90
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
'use strict'
const http = require('http')
const { expect } = require('chai')
const sinon = require('sinon')
const nock = require('..')
require('./setup')
describe('`socketDelay()`', () => {
it('socketDelay', done => {
nock('http://example.test')
.get('/')
.socketDelay(200)
.reply(200, '<html></html>')
const req = http.get('http://example.test')
const onTimeout = sinon.spy()
req.on('socket', socket => {
if (!socket.connecting) {
req.setTimeout(100, onTimeout)
return
}
socket.on('connect', () => {
req.setTimeout(100, onTimeout)
})
})
req.on('response', () => {
expect(onTimeout).to.have.been.calledOnce()
done()
})
})
it('emits a timeout - with setTimeout', done => {
nock('http://example.test')
.get('/')
.socketDelay(10000)
.reply(200, 'OK')
const onEnd = sinon.spy()
const req = http.request('http://example.test', res => {
res.setEncoding('utf8')
res.once('end', onEnd)
})
req.setTimeout(5000, () => {
expect(onEnd).not.to.have.been.called()
done()
})
req.end()
})
it('emits a timeout - with options.timeout', done => {
nock('http://example.test')
.get('/')
.socketDelay(10000)
.reply(200, 'OK')
const onEnd = sinon.spy()
const req = http.request('http://example.test', { timeout: 5000 }, res => {
res.setEncoding('utf8')
res.once('end', onEnd)
})
req.on('timeout', function() {
expect(onEnd).not.to.have.been.called()
done()
})
req.end()
})
it('does not emit a timeout when timeout > socketDelay', done => {
const responseText = 'okeydoke!'
const scope = nock('http://example.test')
.get('/')
.socketDelay(10000)
.reply(200, responseText)
const req = http.request('http://example.test', res => {
res.setEncoding('utf8')
let body = ''
res.on('data', chunk => {
body += chunk
})
res.once('end', () => {
expect(body).to.equal(responseText)
done()
})
})
req.setTimeout(60000, () => {
expect.fail('socket timed out unexpectedly')
})
req.end()
scope.done()
})
})
describe('`Socket#setTimeout()`', () => {
it('adds callback as a one-time listener for parity with a real socket', done => {
nock('http://example.test')
.get('/')
.socketDelay(100)
.reply(200, '<html></html>')
const onTimeout = () => {
done()
}
http.get('http://example.test').on('socket', socket => {
socket.setTimeout(50, onTimeout)
})
})
it('can be called without a callback', done => {
nock('http://example.test')
.get('/')
.socketDelay(100)
.reply()
http.get('http://example.test').on('socket', socket => {
socket.setTimeout(50)
socket.on('timeout', () => {
done()
})
})
})
})