使用 Jasmine 在 JavaScript 中存根 WebSocket

Stubbing WebSocket in JavaScript with Jasmine(使用 Jasmine 在 JavaScript 中存根 WebSocket)
本文介绍了使用 Jasmine 在 JavaScript 中存根 WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试测试 onmessage 是否是一个正确的函数.

I try to test if onmessage is a proper function.

这是一个测试:

  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);
    });
  });

这里是实现:

FL.init = function(address, window) {
  if ('WebSocket' in window) {
    var ws = new WebSocket(address);
    ws.onmessage = function(e) {
      this.handleMessage(e.data);
    };
    return ws;
  }
};

第一个测试通过.第二个,wsundefined.这是为什么?我在控制台中尝试过 new function() {return {onmessage: null}} 看起来应该没问题.

The first test passes. In the second, ws is undefined. Why is that? I tried in a console new function() {return {onmessage: null}} and it looks it should be ok.

推荐答案

我不完全确定你的代码应该如何表现,但如果你需要监视 WebSocket构造函数和存根 .send 方法来模拟一些传入的消息,这里是如何实现的.

I'm not completely sure that I figured out how your code is supposed to behave, but if you need to spy on WebSocket constructor and stub .send method to mock some incoming messages, here is how to achieve it.

要监视 WebSocket,您需要调用 .and.callThrough 而不是 returnValue.然而,它导致抱怨缺少 new 关键字(如 here),所以你需要伪造构造函数:

To spy on WebSocket you will need to call .and.callThrough rather than returnValue. However it result with complains about lack of new keyword (as mentioned in here), so you need to fake the constructor:

var realWS = WebSocket;
var WebSocketSpy = spyOn(window, "WebSocket").and.callFake(function(url,protocols){
  return new realWS(url,protocols);
});

要为传入的消息做一个间谍,你可以简单地做

To make a spy for incoming messages you can simply do

var onmessageCallbackSpy = jasmine.createSpy('onmessageCallback');

您还可以监视 .send 方法,并提供一些模拟响应:

You can also spy on .send method, and provide some mocked responses with:

var sendSpy = spyOn(WebSocket.prototype, "send").and.callFake(function(outMsg){
  // process/check outgoing message
  // setTimeout, or call it immediately
  this.onmessage("mock message goes here");
}); 

但请确保使用 WebSocket.prototype,然后再将其替换为 WebSocketSpy.

But make sure to use WebSocket.prototype, before you replace it with WebSocketSpy.

完整的工作示例应该如下所示:

So full working example, should look like this:

it("should spy and callFake WebSocket constructor, and stub prototype methods", function (done) {
    var realWS= WebSocket;  
    var sendSpy = spyOn(WebSocket.prototype, "send").and.callFake(function(outMsg){
      if(outMsg == "outgoing message"){
        this.onmessage("incoming mocked message goes here");
      }
    });  
    // var messageSpy = spyOn(WebSocket.prototype, "onmessage");//.and.returnValue("mock message goes here");      
    var WSSpy = spyOn(window, "WebSocket").and.callFake(function(url,protocols){
      return new realWS(url,protocols);
    }); 
    var onmessageCallbackSpy = jasmine.createSpy('onmessageCallback');       

    // Your code
    // (function init(url, onmessageCallbackSpy){
        var ws = new WebSocket("ws://some/where");
        ws.onmessage = onmessageCallbackSpy;
        // code that results with receiving a message
        // or mocked send, that calls `.onmessage` immediately
        ws.send("outgoing message");
    // })();    

    expect(WSSpy).toHaveBeenCalledWith("ws://some/where");
    expect(onmessageCallbackSpy).toHaveBeenCalledWith("mock message goes here");
    done();
});

这篇关于使用 Jasmine 在 JavaScript 中存根 WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)