Unit test web worker code

Taking the sample code from https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage , the web executor runs the following

// in worker.js
onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}

executed by code in Angular / factory service

var myWorker = new Worker("worker.js");

I would like to be able to unit test the code worker.js, ideally, run it as part of the Angular / factory service (in a separate application running in a web worker?), So I can use the DI system to inject dependencies and have unit test code similar for tests for any other service. How can i do this?

+3
source share
1 answer

, , -, , , Angular.

Angular -

  • /, /, Angular - window document
  • Angular importScripts
  • , , importScripts
  • .

, :

// worker.js

// Angular needs a global window object
var window = self;

// Skeleton properties to get Angular to load and bootstrap.
self.history = {};
var document = {
  readyState: 'complete',
  querySelector: function() {},
  createElement: function() {
    return {
      pathname: '',
      setAttribute: function() {}
    }
  }
};

// Load Angular: must be on same domain as this script
importScripts('angular.js');

// Put angular on global scope
angular = window.angular;

// Standard angular module definition
importScripts('worker-app.js');

// No root element seems to work fine
angular.bootstrap(null, ['worker-app']);

Angular : /, . , run ( console.log ).

// worker-app.js
(function() {
  'use strict';

  var app = angular.module('worker-app', []);

  app.run(function($window) {
    $window.onmessage = function(e) {
      var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
      $window.postMessage(workerResult);
    };
  });

})();

, -:

// worker-app-spec.js
describe('worker-app', function() {
  'use strict';

  var $window;

  beforeEach(module('worker-app'));

  beforeEach(inject(function(_$window_) {
    $window = _$window_;
  }));

  beforeEach(function() {
    spyOn($window, 'postMessage');
  })

  it('attaches to $window onmessage', function() {
    var data = [2,3];
    var result = 'Result: ' + (data[0] * data[1]);
    $window.onmessage({data: data});
    expect($window.postMessage).toHaveBeenCalledWith(result);
  });
});

, Angular, , ! AngularJS v1.3.7.

+2

All Articles