Jasmine spyOn - 方法在jQuery匿名函数中不存在 [英] Jasmine spyOn - method does not exist in jQuery anonymous function

查看:180
本文介绍了Jasmine spyOn - 方法在jQuery匿名函数中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SO和其他论坛上搜索过此问题的答案。没有找到解决方案。

我遇到了一个问题,Jasmine无法在jQuery代码块中找到函数,无论Jasmine代码是在jQuery函数内部与否。

I'm running into a problem where Jasmine cannot find a function inside of a jQuery code block, whether the Jasmine code is inside the jQuery function or not.

$(function() {
    function foo(param1, param2) {
        // some code
    }

    describe("Foo function", function () {

        spyOn(window, 'foo');

        foo(1, 2);

        it("Should be found by Jasmine", function(){
            expect(window.foo).toHaveBeenCalled();
        });
    });
});

Error: foo() method does not exist

我也尝试过 spyOn($,'foo') spyOn($。fn,'foo')等等。

此外,以下代码也不起作用。

Also, the following code does not work either.

$(function() {
    function foo(param1, param2) {
        // some code
    }
});

describe("Foo function", function () {

    spyOn(window, 'foo');

    foo(1, 2);

    it("Should be found by Jasmine", function(){
        expect(window.foo).toHaveBeenCalled();
    });
});

那么如何让这两个代码块都能正常工作(即Jasmine代码在哪里? jQuery函数,以及它在jQuery函数之外的地方)?

So how would one make both of these code blocks work (i.e. where the Jasmine code is inside of the jQuery function, and where it is outside of the jQuery function)?

推荐答案

我不想回答我自己的问题,但我宁愿比其他人没有从我的错误中吸取教训。

I hate to answer my own question, but I rather that than other people not learning from my mistakes.

这里有2个问题:


  1. Jasmine需要一个包含对象

  2. 您无法访问JS函数范围之外的函数/变量

1 - Jasmine间谍需要使用一个包含对象,如果找不到,你只需要自己制作。所以下面的代码可以工作:

1 - Jasmine spies need to use a containing object, and if one can't be found, you just need to make it yourself. So the following code works:

// Using Jasmine inside of a jQuery anon function
$(function () {

    function foo() {
        // Some code
    }

    describe("Foo function", function () {

        it("Should be findable by Jasmine", function () {
            var Thing = {}
            Thing.foo = foo;
            spyOn(Thing, 'foo');
            Thing.foo(2)
            expect(Thing.foo).toHaveBeenCalled();
        });
    });
});

2 - 如果你有 describe 块在jQuery anon函数之外,它将无法访问jQuery块中的任何值,因此无论你做什么,上面的第二个代码示例都不起作用。

2 - If you have the describe block outside of the jQuery anon function, it won't be able to access any values from within the jQuery block, hence the second code example above won't work, no matter what you do.

这篇关于Jasmine spyOn - 方法在jQuery匿名函数中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆