nastyklad
nastyklad

Reputation: 329

Protractor : mocking EventSource

Is there remotely any way to mock any SSE (Server Sent Event) from a Protractor test ?

That means mocking EventSource

Angular controller :

angular.module('app').controller('HomeController', function() {

  var monitoringEvents = new window.EventSource('/streams/jobserveur');

  monitoringEvents.addEventListener('monitoring-event', function(e) {
    var json = JSON.parse(e.data);    
    ...
  });
});

Thank you for any insight

Upvotes: 1

Views: 1565

Answers (1)

nastyklad
nastyklad

Reputation: 329

I managed to mock EventSource by the solution I mentionned (angular module/protractor addMockModule).

  1. Externalize EventSource calls into a dedicated angular module

    angular.module('app.sse', [])
    .value('$sse', {
      sources : [],
      addEventSource : function(name, url) {
        this.sources[name] = new window.EventSource(url);
      },
      addEventListener : function(name, eventName, callback) {
        this.sources[name].addEventListener(eventName, callback);
      }
    });
    
  2. Referencing the module in the app

    angular.module('app', ['app.sse', ...])
    
  3. Use the $sse module in the app

    angular.module('app').controller('HomeController', ['$sse' , function($sse) {
      $sse.addEventSource('jobserveur', '/streams/jobserveur');
    
      $sse.addEventListener('jobserveur', 'monitoring-event', function(e) {
        var js = JSON.parse(e.data);
      }
    }]);
    

    From here, make sure your app still work before moving onto the testing

  4. Mock the app.sse module in your test

    describe('SSE Fixture', function() {
      beforeEach(function() {
        browser.addMockModule('app.sse', function() {
          angular.module('app.sse', []).value('$sse', {
            addEventSource: function(name, url) {
    
            },
            addEventListener: function(name, event, callback) {
    
            }
          });
      });
    }
    

    And you're done ! Obviously, the two methods are not implemented here nor is the app.sse module in anyway robust but you get the picture.

Hope it helps anyone

Cheers

Upvotes: 1

Related Questions