3

I'm writing tests using Teaspoon and Jasmine for my Rails app. I understand, for the most part, how to test standalone js modules but I'm not sure how to go about testing a module that binds to a DOM ready event like with JQuery's $(document).ready().

Ideally I could set up a fixture before requiring the JS file, but if I don't put the require as the first statement, then it is ignored.

How does one usually go about testing this?

I would've wanted to do something like:

cool.js:

$(document).ready(function() {
  $(".stuff").click(stuffClickHandler);
}

cool_spec.js:

fixture.load("fixture_with_stuffs.html");
//= require cool
describe("on ready", function() {
  it("should bind handlers to all stuffs", function() {
    // test stuffs for handlers
  });
});

But that doesn't work, because if the //= require comes after anything, it doesn't seem to load the js.

Even if we make it minimal like $(document).ready(initFunction) how do we write a test that ensures the initFunction is called without mocking it before the require?

rewolf
  • 5,561
  • 4
  • 40
  • 51

2 Answers2

0

I had some issues with this as well, the best I could come up with was just defining a function to perform all the .ready() stuff, and calling that from the tests:

cool.js:

var onReady = function() {
    $(".stuff").click(stuffClickHandler);
}

$(document).ready(function() {
    onReady();
}

cool_spec.js:

//= require cool
fixture.load("fixture_with_stuffs.html");
onReady();
describe("on ready", function() {
  it("should bind handlers to all stuffs", function() {
    // test stuffs for handlers
  });
});
TimP
  • 210
  • 2
  • 11
-2

You can include your cool.js at the very top of you test like this:

//= require cool.js
mrgreenfur
  • 84
  • 11
  • The original asker said that that won't work, because he wants to bind stuff to the DOM, so the DOM needs to exist _before_ the Javascript is loaded. – TimP Mar 30 '19 at 01:55