4

我有一个这样定义的插件

(function($){


    $.fn.robodisco = function(callerSettings) {

        var findVideos = function(params){ ... }

        $(".track").click(function(){
            ....
            findVideos(data) });

        ....

在我的测试中,我想监视findVideos并检查它是否被调用。然而,Jasmine 一直抱怨找不到方法。这是我的规格:

it("searches for videos for track", function(){
      spyOn($.fn.robodisco, "findVideos");
      $lastTrack.click();
      expect($.fn.robodisco.findVideos).toHaveBeenCalled();
});

我的语法错了吗?

4

2 回答 2

2

我知道这是一篇较旧的帖子,但我想我会回答,因为我找到了今天帮助我解决同样问题的解决方案。我有一个 jasmine 单元测试,可确保 dcjqaccordion 插件在包装手风琴插件的 AngularJS 提供程序中使用一组默认值进行初始化。我所做的是我用一个间谍来模拟我传递给插件的元素,该间谍将预期的插件调用的函数存根。

测试代码:

var mockElement = jasmine.createSpyObj('mockElement', ['dcAccordion']);

it('should initialize with prescribed defaults', function(){

        var expectedDefaults = {
            eventType: 'click',
            autoClose: false,
            saveState: true,
            disableLink: true,
            speed: 'slow',
            showCount: false,
            autoExpand: true,
            classExpand: 'dcjq-current-parent'
        };

        testDcjqaccordionProvider.initialize(mockElement);

        expect(mockElement.dcAccordion).toHaveBeenCalledWith(expectedDefaults);

    });

生产代码:

app.provider('dcjqaccordionWrapper', function(){

    //Lazy load our dependency on the plugin
    function getAccordionPlugin(){
        $.getScript('scripts/jquery.dcjqaccordion.2.7.js')
            .done(function(){
                console.log("Successfully loaded the dcjqaccordion plugin.");
            })
            .fail(function(){
                console.log("There was a problem loading the dcjqaccordion plugin.");
            });
    }


    var defaults = {
        eventType: 'click',
        autoClose: false,
        saveState: true,
        disableLink: true,
        speed: 'slow',
        showCount: false,
        autoExpand: true,
        classExpand: 'dcjq-current-parent'
    };

    this.initialize = function(inElement){
      inElement.dcAccordion(defaults);
    };

    this.$get = function(){
        getAccordionPlugin();
        return this;
    };
})
于 2015-01-16T19:32:55.620 回答
1

The problem is that you're looking for findVideos to be a property of the robodisco method which it is not. It's a local variable within that method, so trying to access it via robodisco.findVideos isn't going to work.

I don't really have a fix for you as I'm having a similar problem and am currently researching how to solve it. The methods I am trying to spy on are defined outside of the namespace of my jQuery plugin as recommended the plugin authoring docs.

I'll update if i find a solution. I can't find much and I'm thinking that it won't be possible for me to grab my methods since they're wrapped in an anonymous function call, but we'll see.

于 2011-08-26T16:27:10.087 回答