Skip to content

Commit 4facb18

Browse files
authored
fix: improve worker tests (#1757)
1 parent 38fb6ae commit 4facb18

File tree

4 files changed

+87
-49
lines changed

4 files changed

+87
-49
lines changed

src/lib/PingTimer.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,15 @@ export default class PingTimer {
88

99
private checkPing: () => void
1010

11-
private setTimeout = isBrowser ? setT : setTimeout
11+
// dont directly assign globals to class props otherwise this throws in web workers: Uncaught TypeError: Illegal invocation
12+
// See: https://stackoverflow.com/questions/9677985/uncaught-typeerror-illegal-invocation-in-chrome
13+
private _setTimeout: typeof setT =
14+
isBrowser && !isWebWorker
15+
? setT
16+
: (func, time) => setTimeout(func, time)
1217

13-
private clearTimeout = isBrowser ? clearT : clearTimeout
18+
private _clearTimeout: typeof clearT =
19+
isBrowser && !isWebWorker ? clearT : (timer) => clearTimeout(timer)
1420

1521
constructor(keepalive: number, checkPing: () => void) {
1622
this.keepalive = keepalive * 1000
@@ -19,15 +25,15 @@ export default class PingTimer {
1925
}
2026

2127
private setup() {
22-
this.timer = this.setTimeout(() => {
28+
this.timer = this._setTimeout(() => {
2329
this.checkPing()
2430
this.reschedule()
2531
}, this.keepalive)
2632
}
2733

2834
clear() {
2935
if (this.timer) {
30-
this.clearTimeout(this.timer)
36+
this._clearTimeout(this.timer)
3137
this.timer = null
3238
}
3339
}

test/browser/test.js

Lines changed: 52 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,14 @@ import { expect } from '@esm-bundle/chai';
22
import mqtt from '../../'; // this will resolve to mqtt/dist/mqtt.esm.js
33

44
// needed to test no-esm version /dist/mqtt.js
5-
/** @type { import('../../src').MqttClient }*/
5+
/** @type { import('../../src') }*/
66
const mqtt2 = window.mqtt
77

88
// get browser name
99
const userAgent = navigator.userAgent.toLowerCase().replace(/ /g, '_').replace(/\//g, '_')
1010

1111
let browser = 'unknown'
1212

13-
console.log('userAgent:', userAgent)
14-
1513
if (userAgent.includes('chrome')) {
1614
browser = 'chrome'
1715
} else if (userAgent.includes('firefox')) {
@@ -21,40 +19,50 @@ if (userAgent.includes('chrome')) {
2119
}
2220

2321
const browserTopic = `test/${browser}`
22+
console.log('User Agent:', userAgent)
23+
console.log('Browser:', browser)
2424

25-
console.log('browser:', browser)
26-
27-
function run(proto, port, cb) {
28-
25+
function testProto(proto, port, cb = () => { }) {
2926
const testTopic = `${browserTopic}/${proto}`
3027

3128
describe('MQTT.js browser test with ' + proto.toUpperCase(), () => {
3229
after(() => {
33-
if (cb) {
30+
if (client) {
31+
client.end(() => {
32+
cb()
33+
client = null;
34+
});
35+
} else {
3436
cb()
3537
}
3638
})
3739

38-
const client = mqtt.connect(`${proto}://localhost:${port}`, {
39-
// log: console.log.bind(console),
40-
})
41-
client.on('offline', () => {
42-
console.log('client offline')
43-
})
44-
client.on('connect', () => {
45-
console.log('client connect')
46-
})
47-
client.on('reconnect', () => {
48-
console.log('client reconnect')
49-
})
40+
/** @type { import('../../src').MqttClient }*/
41+
let client = null;
5042

5143
it('should connect-publish-subscribe', (done) => {
44+
client = mqtt.connect(`${proto}://localhost:${port}`, {
45+
// log: console.log.bind(console),
46+
clientId: `testClient-${browser}-${proto}`,
47+
})
48+
client.on('offline', () => {
49+
console.log('client offline')
50+
done(new Error('client offline'))
51+
})
52+
client.on('connect', () => {
53+
console.log('client connect')
54+
})
55+
client.on('reconnect', () => {
56+
console.log('client reconnect')
57+
})
58+
5259
const payload = 'Hello World!'
5360
client.on('connect', () => {
5461
client.on('message', (topic, msg) => {
5562
expect(topic).to.equal(testTopic);
5663
expect(msg.toString()).to.equal(payload);
5764
client.end(() => {
65+
client = null;
5866
done();
5967
});
6068
});
@@ -76,30 +84,32 @@ function run(proto, port, cb) {
7684
})
7785
}
7886

79-
it('should work with non-ESM version', () => {
80-
expect(mqtt2).to.exist
81-
expect(mqtt2.connect).to.exist
82-
expect(mqtt2.connect).to.be.a('function')
83-
})
87+
describe('MQTT.js browser tests', () => {
88+
it('should work with ESM version', (done) => {
89+
expect(mqtt2).to.exist
90+
expect(mqtt2.connect).to.be.a('function')
91+
expect(mqtt2.Client).to.be.a('function')
92+
done()
93+
})
8494

95+
it('should work in a Web Worker', (done) => {
96+
const worker = new Worker('test/browser/worker.js')
97+
worker.onmessage = (e) => {
98+
if (e.data === 'worker ready') {
99+
done()
100+
} else {
101+
done(Error(e.data))
102+
}
103+
}
85104

86-
run('ws', window.wsPort, () => {
87-
run('wss', window.wssPort, () => {
88-
describe('MQTT.js browser test with web worker', () => {
89-
it('should work with web worker', async () => {
90-
const worker = new Worker('test/browser/worker.js')
91-
const ready = new Promise((resolve, reject) => {
92-
worker.onmessage = (e) => {
93-
if (e.data === 'worker ready') {
94-
resolve()
95-
} else {
96-
reject(e.data)
97-
}
98-
}
99-
})
100-
await ready
101-
})
102-
})
105+
worker.onerror = (e) => {
106+
done(Error(e.message))
107+
}
108+
})
109+
110+
testProto('ws', window.wsPort, () => {
111+
testProto('wss', window.wssPort)
103112
})
104113
})
105114

115+

test/browser/worker.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
1-
// test mqttjs in worker
2-
31
importScripts('/dist/mqtt.js');
42

53
/** @type { import('../../src').MqttClient }*/
64
const MQTT = mqtt;
75

8-
postMessage(typeof MQTT?.connect === 'function' ? 'worker ready' : 'worker error');
6+
const client = MQTT.connect(`ws://localhost:4000`, {
7+
clientId: `testClient-worker_` + Math.random().toString(16).substr(2, 8),
8+
});
9+
10+
client.on('offline', () => {
11+
console.log('worker client offline');
12+
})
13+
14+
client.on('reconnect', () => {
15+
console.log('worker client reconnect');
16+
})
17+
18+
client.on('error', (err) => {
19+
console.log('worker client error', err);
20+
})
21+
22+
client.on('connect', () => {
23+
console.log('worker client connect');
24+
client.end(() => {
25+
console.log('worker client end');
26+
postMessage('worker ready');
27+
});
28+
})

web-test-runner.config.mjs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ await start({
1111
wssPort,
1212
key: './test/certs/server-key.pem',
1313
cert: './test/certs/server-cert.pem',
14+
verbose: true,
15+
stats: false
1416
})
1517

1618
console.log('Broker setup done')

0 commit comments

Comments
 (0)