Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 1 | (function () { |
| 2 | 'use strict'; |
| 3 | |
| 4 | const chai = require('chai'); |
| 5 | const expect = chai.expect; |
| 6 | const sinon = require('sinon'); |
| 7 | const sinonChai = require('sinon-chai'); |
| 8 | const mockery = require('mockery'); |
| 9 | chai.use(sinonChai); |
| 10 | const fakeredis = require('fakeredis'); |
| 11 | |
| 12 | const client = fakeredis.createClient('test-client'); |
| 13 | const publisher = fakeredis.createClient('test-client'); |
| 14 | |
| 15 | const socketSpy = sinon.spy(); |
| 16 | const mockSocket = { |
| 17 | get: () => { |
| 18 | return { |
| 19 | emit: socketSpy |
| 20 | } |
| 21 | } |
| 22 | }; |
| 23 | const channelName = 'Site'; |
| 24 | |
| 25 | describe('The event system', () => { |
| 26 | |
| 27 | before((done) => { |
| 28 | |
| 29 | // Enable mockery to mock objects |
| 30 | mockery.enable({ |
| 31 | warnOnReplace: false, |
| 32 | warnOnUnregistered: false |
| 33 | }); |
| 34 | |
| 35 | // Stub the createClient method to *always* return the client created above |
| 36 | sinon.stub(fakeredis, 'createClient', () => client); |
| 37 | |
| 38 | // Override the redis module with our fakeredis instance |
| 39 | mockery.registerMock('redis', fakeredis); |
| 40 | |
| 41 | // mock the socketIo client to have a spy |
| 42 | mockery.registerMock('./websocket.js', mockSocket); |
| 43 | |
| 44 | require('../src/controllers/redis.js'); |
| 45 | setTimeout(() => { |
| 46 | done(); |
| 47 | }, 1000); |
| 48 | }); |
| 49 | |
| 50 | after(() => { |
| 51 | mockery.disable(); |
| 52 | fakeredis.createClient.restore(); |
| 53 | }); |
| 54 | |
| 55 | // run after each test |
| 56 | beforeEach(() => { |
| 57 | client.unsubscribe(channelName); |
| 58 | client.subscribe(channelName); |
| 59 | publisher.flushdb(); |
| 60 | }); |
| 61 | |
| 62 | it('should send a websocket event when it receive a redis event that is not JSON', (done) => { |
| 63 | publisher.publish(channelName, 'I am sending a message.'); |
| 64 | setTimeout(() => { |
| 65 | expect(socketSpy).to.have.been.called; |
| 66 | expect(socketSpy).to.have.been.calledWith('event', { |
| 67 | model: channelName, |
| 68 | msg: 'I am sending a message.' |
| 69 | }); |
| 70 | done(); |
| 71 | }, 500) |
| 72 | }); |
| 73 | |
| 74 | it('should send a websocket event when it receive a redis event that is JSON', (done) => { |
| 75 | publisher.publish(channelName, JSON.stringify({msg: 'Json Message'})); |
| 76 | setTimeout(() => { |
| 77 | expect(socketSpy).to.have.been.called; |
| 78 | expect(socketSpy).to.have.been.calledWith('event', { |
| 79 | model: channelName, |
| 80 | msg: {msg: 'Json Message'} |
| 81 | }); |
| 82 | done(); |
| 83 | }, 1000) |
| 84 | }); |
| 85 | }); |
| 86 | })(); |