events.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict'
  2. const expect = require('expect.js')
  3. const EventEmitter = require('events').EventEmitter
  4. const describe = require('mocha').describe
  5. const it = require('mocha').it
  6. const Pool = require('../')
  7. describe('events', function () {
  8. it('emits connect before callback', function (done) {
  9. const pool = new Pool()
  10. let emittedClient = false
  11. pool.on('connect', function (client) {
  12. emittedClient = client
  13. })
  14. pool.connect(function (err, client, release) {
  15. if (err) return done(err)
  16. release()
  17. pool.end()
  18. expect(client).to.be(emittedClient)
  19. done()
  20. })
  21. })
  22. it('emits "connect" only with a successful connection', function () {
  23. const pool = new Pool({
  24. // This client will always fail to connect
  25. Client: mockClient({
  26. connect: function (cb) {
  27. process.nextTick(() => {
  28. cb(new Error('bad news'))
  29. })
  30. },
  31. }),
  32. })
  33. pool.on('connect', function () {
  34. throw new Error('should never get here')
  35. })
  36. return pool.connect().catch((e) => expect(e.message).to.equal('bad news'))
  37. })
  38. it('emits acquire every time a client is acquired', function (done) {
  39. const pool = new Pool()
  40. let acquireCount = 0
  41. pool.on('acquire', function (client) {
  42. expect(client).to.be.ok()
  43. acquireCount++
  44. })
  45. for (let i = 0; i < 10; i++) {
  46. pool.connect(function (err, client, release) {
  47. if (err) return done(err)
  48. release()
  49. })
  50. pool.query('SELECT now()')
  51. }
  52. setTimeout(function () {
  53. expect(acquireCount).to.be(20)
  54. pool.end(done)
  55. }, 100)
  56. })
  57. it('emits error and client if an idle client in the pool hits an error', function (done) {
  58. const pool = new Pool()
  59. pool.connect(function (err, client) {
  60. expect(err).to.equal(undefined)
  61. client.release()
  62. setImmediate(function () {
  63. client.emit('error', new Error('problem'))
  64. })
  65. pool.once('error', function (err, errClient) {
  66. expect(err.message).to.equal('problem')
  67. expect(errClient).to.equal(client)
  68. done()
  69. })
  70. })
  71. })
  72. })
  73. function mockClient(methods) {
  74. return function () {
  75. const client = new EventEmitter()
  76. Object.assign(client, methods)
  77. return client
  78. }
  79. }