ReferenceError: Can't find variable: $ when running JasmineHeadlessWebkit

↘锁芯ラ 提交于 2019-12-11 08:27:34

问题


I've been trying to find an answer to this at least for the last two hours without any luck. I hope someone here might be able to help.

I'm getting this ReferenceError: Can't find variable: $ when running my Jasmine specs using the JasmineHeadlessWebkit.

The weird thing is, this only happens when I say

$ ->
  game.init()

in my game.coffee file.

I can use the $ without any problems further down game.coffee. For example:

window.game =
  init: ->
    $('.gamelayer').hide()
    $('#gamestartscreen').show()

This is no problem at all.

Also, the tests work okay in Chrome.

So, I'm assuming this has to do with jQuery not being loaded in time but I can't figure out why.

I have jQuery in specs/javascripts/helpers/ and in jasmine.yml i'm mentioning the helpers before the spec_files and src_files but that doesn't seem to really make a difference.

So, if anyone has any idea how I can make sure that jQuery is completely loaded when Jasmine's specs are run, I would really appreciate any help.

Also, please let me know if you need any additional information.

Thank you.


回答1:


you can try two solution:

the first one delay the game.init() waiting for jQuery to be loaded:

function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        setTimeout("initJQuery()", 50);
    } else {
        game.init();
    }
}

the second one calls a jQuery function that prevent conflicts with the library (run it at the beginning of your code):

jQuery.noConflict()

you can try but i'm not sure it's the best solution in your case. Pay attention to use this solution, you'll have to change all '$' to 'jQuery'




回答2:


I ran into this problem also. I fixed it by changing my jasmine.yml to load jquery before it loads the rest of the javascript files:

src_files:
  - public/js/jquery.js
  - public/js/**/*.js


来源:https://stackoverflow.com/questions/16156679/referenceerror-cant-find-variable-when-running-jasmineheadlesswebkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!