Jasmine没有认识到我的(全球)功能

时间:2014-01-07 14:22:53

标签: javascript ajax function jasmine jasmine-jquery

第一次使用Jasmine,仍然试图处理事情。使用2.0.0独立版本。我的SpecRunner.html中有以下几行:

//... jasmine js files included here ...
<!-- include source files here... -->
<script type="text/javascript" src="lib/jasmine-jquery.1.3.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="src/admin.js"></script>
//... the rest of my scripts, and then my specs ...

所以我肯定包括我的admin.js文件,其中我声明了以下一组函数:

$(function() {
    function deleteLink(linkHref, callback) {
        $.ajax({
            type: "POST",
            url: "/delete?href=" + linkHref,
            success: callback
        });
    }

    function redirectHome() {
        location.assign("/");
    }

    $('.delete_button').on('click', function() {
        var buttonUrl = $(this).parent().data('link-href');
        if( confirm("Are you sure you want to remove this link?") ) {
            deleteLink(buttonUrl, redirectHome);
        }
    });
});

请原谅凌乱的代码。我还在学习JS技能。和我一起。我尝试使用suggested format测试此功能(在浏览器中完全按照我的预期运行)来测试AJAX回调:

describe("Admin library", function() {
    describe(".delete_button event handling", function() {
        beforeEach(function() {
            loadFixtures("delete_button.html");
        });

        // other tests here...

        it("should set the location to /", function() {
            spyOn($, "ajax").and.callFake(function(e) {
                e.success();
            });
            var callback = jasmine.createSpy();
            deleteLink("http://some.link.href.com", callback);
            expect(callback).toHaveBeenCalled();
        });
    });
});

但是,测试总是因此错误而失败:

Can't find variable: deleteLink in file:///path/to/my/app/jasmine/spec/adminSpec.js

我目前正在测试其他jasmine / spec文件中的函数,这些函数在这些文件中没有明确声明。我认为这是在SpecRunner.html文件中包含脚本的重点,对吧?关于这里发生了什么的任何想法?

1 个答案:

答案 0 :(得分:3)

deleteLink函数不是全局函数。它在closure内声明(在你的情况下,它是一个自我调用函数)。如果你想让这个函数全局化,你需要在闭包内的“admin.js”文件中添加它:

window.deleteLink = deleteLink;