test.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict'
  2. var mqtt = require('../../lib/connect')
  3. var _URL = require('url')
  4. var xtend = require('xtend')
  5. var parsed = _URL.parse(document.URL)
  6. var isHttps = parsed.protocol === 'https:'
  7. var port = parsed.port || (isHttps ? 443 : 80)
  8. var host = parsed.hostname
  9. var protocol = isHttps ? 'wss' : 'ws'
  10. function clientTests (buildClient) {
  11. var client
  12. beforeEach(function () {
  13. client = buildClient()
  14. client.on('offline', function () {
  15. console.log('client offline')
  16. })
  17. client.on('connect', function () {
  18. console.log('client connect')
  19. })
  20. client.on('reconnect', function () {
  21. console.log('client reconnect')
  22. })
  23. })
  24. afterEach(function (done) {
  25. client.once('close', function () {
  26. done()
  27. })
  28. client.end()
  29. })
  30. it('should connect', function (done) {
  31. client.on('connect', function () {
  32. done()
  33. })
  34. })
  35. it('should publish and subscribe', function (done) {
  36. client.subscribe('hello', function () {
  37. done()
  38. }).publish('hello', 'world')
  39. })
  40. }
  41. function suiteFactory (configName, opts) {
  42. function setVersion (base) {
  43. return xtend(base || {}, opts)
  44. }
  45. var suiteName = 'MqttClient(' + configName + '=' + JSON.stringify(opts) + ')'
  46. describe(suiteName, function () {
  47. this.timeout(10000)
  48. describe('specifying nothing', function () {
  49. clientTests(function () {
  50. return mqtt.connect(setVersion())
  51. })
  52. })
  53. if (parsed.hostname === 'localhost') {
  54. describe('specifying a port', function () {
  55. clientTests(function () {
  56. return mqtt.connect(setVersion({ protocol: protocol, port: port }))
  57. })
  58. })
  59. }
  60. describe('specifying a port and host', function () {
  61. clientTests(function () {
  62. return mqtt.connect(setVersion({ protocol: protocol, port: port, host: host }))
  63. })
  64. })
  65. describe('specifying a URL', function () {
  66. clientTests(function () {
  67. return mqtt.connect(protocol + '://' + host + ':' + port, setVersion())
  68. })
  69. })
  70. describe('specifying a URL with a path', function () {
  71. clientTests(function () {
  72. return mqtt.connect(protocol + '://' + host + ':' + port + '/mqtt', setVersion())
  73. })
  74. })
  75. })
  76. }
  77. suiteFactory('v3', {protocolId: 'MQIsdp', protocolVersion: 3})
  78. suiteFactory('default', {})