你如何使用Jasmine测试jquery点击功能,看看它是否称为自定义方法?

cod*_*der 4 jquery unit-testing jasmine

我正在编写一个Jasmine测试来确定function是否通过JQueryclick()方法调用了a .我的逻辑在哪里不正确?我是否监视jquery函数或自定义函数?

我收到的错误是:

-错误

Expected a spy, but got undefined. in http://localhost:8080/...etc.../jasmine.js (line 1253)
Run Code Online (Sandbox Code Playgroud)

-码

describe("funtionCalled", function() {
it("calls the click() function", function() {
    var cc = new CustomClass();
    spyOn($.fn, "click");
    $( '#fieldID' ).click();
    expect(cc.clickFunction()).toHaveBeenCalled();
   });
});
Run Code Online (Sandbox Code Playgroud)

- 正在测试的代码

var CustomClass = function(){};

$(document).ready(function(){
    var cf = new CustomClass();

    $( '#fieldID' ).click(function() {  
        cf.clickFunction();
    });
});

CustomClass.prototype.clickFunction = function() {
     //some javascript code
};
Run Code Online (Sandbox Code Playgroud)

Igo*_*yev 6

据我所知,你有两件事是错的.首先你监视一个错误的对象,然后你将clickFunction方法的结果传递给expect,而不是实际的方法.

试试这个:

describe("funtionCalled", function() {
    it("calls the click() function", function() {
        var cc = new CustomClass();

        spyOn(cc, "clickFunction"); 
        // Notice how you pass a real object and a method name to spyOn

        $('#fieldID').click();

        expect(cc.clickFunction).toHaveBeenCalled();
        // Notice how you pass the method, and not the method call result
    });
});
Run Code Online (Sandbox Code Playgroud)

你可以在茉莉花维基上找到关于间谍的更多信息.