Tôi thử kiểm tra xem onmessage
có phải là một chức năng thích hợp không.Chèn WebSocket bằng JavaScript với Jasmine
Dưới đây là một thử nghiệm:
describe(".init(address, window)", function() {
beforeEach(function() {
address = 'ws://test.address';
window = {};
e = {
data: {}
}
spyOn(window, 'WebSocket').and.returnValue(function() {return {onmessage: null}});
spyOn(subject, 'handleMessage');
});
it("should create a WebSocket client which connects to the given address", function() {
subject.init(address, window);
expect(window.WebSocket).toHaveBeenCalledWith(address);
});
it("should have onmessage method overriden with a function which handles message", function() {
ws = subject.init(address, window);
alert(JSON.stringify(ws));
ws.onmessage(e);
expect(subject.handleMessage).toHaveBeenCalledWith(e.data);
});
});
Đây là việc thực hiện:
FL.init = function(address, window) {
if ('WebSocket' in window) {
var ws = new WebSocket(address);
ws.onmessage = function(e) {
this.handleMessage(e.data);
};
return ws;
}
};
Các thử nghiệm đầu tiên trôi qua. Trong giây, ws
là undefined
. Tại sao vậy? Tôi đã thử trong một giao diện điều khiển new function() {return {onmessage: null}}
và có vẻ như nó sẽ là ok.