Search code examples
javascriptajaxfunctionjasminejasmine-jquery

Jasmine not recognizing my (global) functions


First time using Jasmine, still trying to get a handle on things. Using 2.0.0 standalone version. I've got the following lines in my 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 ...

So I am definitely including my admin.js file, in which I declare the following set of functions:

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

I'm trying to test this functionality (which works in the browser exactly as I expect it to) with the suggested format for testing AJAX callbacks:

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

However, the test always fails with this error:

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

I'm currently testing functions in other jasmine/spec files that aren't declared explicitly in those files. I thought that was the point of including the scripts in the SpecRunner.html file, right? Any ideas as to what's going on here?


Solution

  • The deleteLink function is not global. It's declared inside a closure (in your case it's a self calling function). If you want to have that function global, you need to add this in your "admin.js" file inside the closure :

    window.deleteLink = deleteLink;