单元测试Javascript Web worker。并在Web Worker中模拟http调用

时间:2017-04-20 22:21:56

标签: javascript http jasmine mocking web-worker

我是网络工作者的新手。我写了一个web worker,它获取消息并读取onmessage事件的数据,然后进行ajax / http调用以获取数据。一旦从ajax / http调用返回数据,它就会使用postMessage事件将消息发回。 现在我想知道如何使用Jasmine和Karma对这个Web Worker进行单元测试。我试过测试它但无法在web worker中模拟http调用。以下是我的代码。提前致谢。

worker.js

(function () {
'use strict';  var startDate, endDate, token, initialized;

var http = {};

/*  Code To make http request - Starts */
http.x = function () {
    if (typeof XMLHttpRequest !== 'undefined') {
        return new XMLHttpRequest();
    }
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"
    ];

    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
    return xhr;
};

http.send = function (url, callback, method, data, async, headerToken) {
    if (async === undefined) {
        async = true;
    }
    var x = http.x();
    x.open(method, url, async);
    if (headerToken !== null && headerToken !== "") {
        x.setRequestHeader("Authorization", "Bearer " + headerToken);
    }
    x.onreadystatechange = function () {
        if (x.readyState === 4 && x.responseText !== "" && x.responseText !== undefined && x.responseText !== null) {
            callback(JSON.parse(x.responseText));
        }
    };
    x.send(data);
};

http.get = function (url, data, callback, async, headerToken) {
    var query = [];
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
    }
    http.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async, headerToken);
};
/*  Code To make http request  - ends */


var postOpenOrdersTile = function (result) {
    if (result) {
        postMessage('<div id="openOrdersTile" class="tileContent">' +result.TotalOpenOrders +'</div>');
    }

};

function run(url) {
    var baseUrl = url;
    var openOrdersTilesUrl = baseUrl + "/DashboardTiles/GetOpenOrderTileValues";
    http.get(openOrdersTilesUrl, createDashboardTileInput(startDate, endDate), postOpenOrdersTile, true, token);
}

var load = function (response) {
    var baseUrl = response.base + response.api;
    run(baseUrl);
}

/* Code To triggere Worker - onmessage */
self.onmessage = function (msg) {
    if (msg.data.baseUrl && !initialized) {
        self.importScripts(msg.data.baseUrl + '/BaseApp/Scripts/moment.js');
        startDate = msg.data.fromDate;
        endDate = msg.data.toDate;
        token = msg.data.token;
        http.get(msg.data.baseUrl + '/CardioDashboard/config.json', '', load, true, '');
    }
};}());

WorkerSpec.js

define([], 

function () {  'use strict'  

 describe('Web Worker : Tiles Sharing web Worker', function () {        .
 var worker, data   ;         

 http = { get: function () { return {} } };
    beforeEach(function () {
        worker = new Worker('path/Worker.js');
        data = {
            baseUrl: "xyz",
            fromDate: '2017-04-13',
            toDate: '2017-04-07',
            token: ''             
        };
        worker.postMessage(data);
    });

    afterEach(function () {

    });


    it('Tests the Webworker', function (done) {
        spyOn(http, 'get').and.returnValue({});
        spyOn(window, 'postOpenOrdersTile').and.callFake(function () {
            return {};
        });
        worker.addEventListener('message', function (e) {
            if (e.data) {
                expect(e.data).toBe('<div id="openOrdersTile" class="tileContent">45</div>');                        
            }
            if (triggerCount === 6) {
                done();
            }
        });

    });
});});

1 个答案:

答案 0 :(得分:0)

输出为<div id="openOrdersTile" class="tileContent">null</div>的原因是因为postOpenOrdersTile的参数为空。我不确定你是否真的在测试任何有用的东西,因为你必须模仿一切。但是请尝试模拟http.get:{TotalOpenOrders: 45}的返回值。

您可以使Worker成为构造函数并将http附加到它:

var Worker = function() {
  this.http = {
    send: function() {
       // do something
    },
    get: function() {
      // do something
    }
  };
}

在测试中:     spyOn(worker.http, 'get').and.returnValue({});