Coffeescript calling function inside jQuery docment.ready
-
26-10-2019 - |
题
Jasmine Test:
describe 'Toolbar', ->
beforeEach ->
jasmine.getFixtures().fixturesPath = "../spec/javascript/fixtures"
loadFixtures("canvas_fixture.html")
describe 'Rectangle Button Click', ->
it 'adds the selected class to rectangle button', ->
toolbar = new Toolbar()
expect(toolbar).toBeDefined
console.log $('#rectangle')
toolbar.rectangle
expect($('#rectangle').hasClass("selected")).toBeTruthy()
console.log $('#rectangle')
Class:
class window.Toolbar
jQuery ->
rectangle: $('#rectangle').click ->
$('#toolbar button').removeClass("selected")
$('#rectangle').addClass("selected")
This test is failing for me as the selected class is not being added to the fixture, and I think I'm not calling the function correctly. How do I call the
$('#rectangle').click
function in my test? Thanks.
解决方案
I don't know the whole context, but some things I see:
toolbar.rectangle
in your test is not calling a function, you need to saytoolbar.rectangle()
to actually call itYour class as written is not defining a method on the Toolbar class, you should write something like this:
class Toolbar rectangle: -> $('#rectangle').click -> $('#toolbar button').removeClass("selected") $('#rectangle').addClass("selected")
When you write this
$('#rectangle').click -> ...
, you are defining an event handler that will get called when you click in#rectangle
. If you want to have it have action immediately (i.e. when you calltoolbar.rectangle()
, you need something like this:class Toolbar rectangle: -> $('#toolbar button').removeClass("selected") $('#rectangle').addClass("selected")
Of course, you need to make sure all this happens after the page loads correctly, not familiar with Jasmine to say whether that will happen.
Hope this helps.