gpt4 book ai didi

javascript - jasmine jquery 测试以检查是否已将正确的参数传递给方法

转载 作者:行者123 更新时间:2023-11-29 17:14:11 28 4
gpt4 key购买 nike

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

这是我的方法:

    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.

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

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

我收到以下错误:

undefined() method does not exist

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

最佳答案

spyOn 的第二个参数是您需要监视的属性的名称。当您调用 spyOn(window, myWindow('list')); 时,您的第二个参数是 myWindow( 'list')undefined => 抛出错误:undefined() 方法不存在

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

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

在软件单元测试中,有一个概念叫做stub and mock objects。 .这些是被测方法的依赖项。 spyOn 是创建您的假对象来测试您的方法。

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

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将 View (DOM) 与模型(逻辑)分开的框架,使用 dependency injection使您的代码可测试。

关于javascript - jasmine jquery 测试以检查是否已将正确的参数传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440865/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com