Search code examples
javascriptjqueryajaxunit-testingjasmine

ReferenceError: $ is not defined - Jasmine


I never used Jasmine before but I'm required for this little project that I'm working on. Can't quite figure it out, any help would be appreciated. I have looked at various tutorials and googeled the problem but being new to this does not help.

JS source file

> $(document).ready(function(){
>    
> 
> $.ajax({ type: 'GET', dataType: "json", url: "db.php/realmadrids", 
> success: showResponse,  error: showError });
> 
> 
> 
>  
> 
> 
> console.debug("error");   function showResponse(responseData){
> 
>   //$("#get1").click(function getPlayers(responseData) { 
>   console.log('Image is clicked');    console.log(responseData);
>     $.each(responseData.realmadrid, function(index, realmadrid){
>       console.log(' is ');
>         $("#playercontentRealMadrid").append("</br><strong> Full Name: </strong>" +realmadrid.PlayerName+ " "+realmadrid.PlayerLastName+"
> </br> <strong>Player Position: </strong>" +realmadrid.PlayerPosition+"
> </br><strong>Player Age: </strong>" +realmadrid.Age+"
> </br><strong>Player Height: </strong>" +realmadrid.Height+"
> </br><strong>Player Weight: </strong>" +realmadrid.Weight+"
> </br><strong>Team Name: </strong>" +realmadrid.TeamName+"</br>");
>     
>         console.log('Data should output'); // });   });
> 
> console.log(responseData);
>     }
>     console.debug("hello");
> 
> function showError(){ alert("Sorry, but something went wrong. Fix
> it!!!!") }
> 
> });

Here is my test code:

//Test Suite
describe("Spy on my own AJAX call", function(){
    
    it("should make AJAX request with successful setting", function() {
    
        spyOn($, "ajax");
        
        expect($.ajax).toHaveBeenCalledWith({
            url:'db.php/realmadrids',
            type:'GET',
            dataType: "json",
            sucess: showResponse,
            error: showError
        });
    
    });
   
});

Solution

  • You need to include jQuery.

    In this case $ is actually a function (from the jQuery library) and because jQuery hasn't been loaded your getting the error that this function is not defined.

    Include jQuery in the same manner that you are including the Jasmine library. One approach would be to use the CDN:

    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>