Jasmine jQuery 测试,用于检查是否已将正确的参数传递给方法

jasmine jquery test to check if correct arguments have been passed to a method

本文关键字:参数传递 方法 测试 jQuery 用于 是否 检查 Jasmine      更新时间:2023-09-26

我是javascript测试的新手。我正在使用茉莉花,需要测试是否已将正确的参数传递给方法。

这是我的方法:

    function myView(){
      if($('.view').is('.list')){
          myWindow('list');
      }else{
          myWindow('random');
      }
      $('.view').toggleClass('my-list');
    }
    function myWindow(list) {
      var url = /test.json;
      $.post(url, {"list": list});
    }
Here are my tests:
  describe('#myView', function() {
    beforeEach(function() {
      fixture.load('myview.html');
    });
    it('sets window to list', function(){
      expect(window.myWindow).toHaveBeenCalledWith('list');
    });
  });

我收到以下错误。

Error: Expected a spy, but got Function.

如果我在期望之前添加此行(这似乎是错误的,因为我指定了应该通过测试识别的正确参数)

spyOn(window, myWindow('list'));

我收到以下错误:

undefined() method does not exist

有人可以告诉我编写上述测试的好方法吗?

spyOn 的第二个参数是您需要监视的属性的名称。当你调用 spyOn(window, myWindow('list')); 时,你的第二个参数是 myWindow('list')返回值,它undefined =>抛出错误:undefined() method does not exist

在您的代码中,只需执行此操作即可:

describe('#myView', function() {
    beforeEach(function() {
      fixture.load('myview.html');
    });
    it('sets window to list', function(){
      spyOn(window, "myWindow");//spy the function
      myView();//call your method that in turn should call your spy
      expect(window.myWindow).toHaveBeenCalledWith('list');//verify
    });
  });

在软件单元测试中,有一些概念称为存根和模拟对象。这些是所测试方法的依赖项。 spyOn是创建您的假对象来测试您的方法。

直接访问全局window对象,这在单元测试中确实是一个问题。虽然Javascript 是一种动态类型语言,我们仍然可以模拟您的 window 对象(这对于某些静态类型语言(如 c# 等静态类型语言)是不可能的)。但是要创建一个好的单元测试代码,我建议你应该重新设计你的代码,从外部注入它。

function myView(awindow){ //any dependency should be injected, this is an example to inject it via parameter
      if($('.view').is('.list')){
          awindow.myWindow('list');
      }else{
          awindow.myWindow('random');
      }
      $('.view').toggleClass('my-list');
    }

试试这个:

describe('#myView', function() {
    beforeEach(function() {
      fixture.load('myview.html');
    });
    it('sets window to list', function(){
      var spy = {myWindow:function(list){}};
      spyOn(spy, "myWindow"); //create a spy
      myView(spy); //call your method that in turn should call your spy
      expect(spy.myWindow).toHaveBeenCalledWith('list'); //verify
    });
  });

还有一件事,像这样的jQuery代码不是单元测试的好候选者,因为它涉及代码中的DOM操作。如果你有时间,你应该看看angularjs框架,它将你的视图(DOM)与你的模型(逻辑)分开,使用依赖注入来使你的代码可测试。