2017-04-20 63 views
0

我是web worker的新手。我已經寫了一個Web工作人員獲取消息並讀取onmessage事件的數據,然後它進行ajax/http調用以獲取數據。一旦從ajax/http調用返回數據,就會使用postMessage事件回發消息。 現在我想知道如何使用茉莉花和噶瑪單元測試這個Web Worker。我嘗試過測試它,但無法模擬web worker內部的http調用。以下是我的代碼。提前致謝。單元測試Javascript 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(); 
      } 
     }); 

    }); 
});}); 
+0

什麼是你測試的輸出? – myfashionhub

+0

預計產量

null
等於
45
。由於web worker實際上正在進行http調用,但我們的服務需要在標頭中傳遞令牌。由於它是單元測試,因此未傳遞實際令牌。由於我只是測試網絡工作者的行爲,我不想讓htpp調用,而是我需要模擬http並返回一些我需要的值。感謝您的回覆 – pavan

回答

0

原因輸出<div id="openOrdersTile" class="tileContent">null</div>是因爲postOpenOrdersTile參數爲null。我不確定你是否真的測試了任何有用的東西,因爲你必須嘲笑一切。但嘗試嘲笑http.get的返回值:{TotalOpenOrders: 45}

可以使職工的構造和HTTP連接到它:

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

在測試: spyOn(worker.http, 'get').and.returnValue({});

+0

嗨,謝謝你的回覆。其實我有一些其他的功能,它處理http.get數據的輸出。我沒有在這裏添加它,對不起我的壞。我實際上需要模擬http.get函數並檢查所有其他函數後處理我的數據。你能否建議我怎樣才能在這個場景中模擬http.get – pavan

+0

你應該能夠使用'spyOn(object,'function')。和.returnValue({})來模擬任何爲postOpenOrdersTile()提供數據的函數。 '。我還建議檢查嘲笑承諾https://volaresystems.com/blog/post/2014/12/09/Testing-async-calls-with-Jasmine。而不是$ .defer,你可以使用原生Promise。 – myfashionhub

+0

嗨,由於我在我的測試規範中實例化一個新的工作者實例,它實際上觸發了網絡工作者。那麼SpyOn可能會在Web Worker中獲取請求。我試圖這樣做,但它沒有奏效。請告訴我,如果有可能窺探網絡工作者的功能 – pavan