Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Bug? Trying to .trigger() an event within a test

$
0
0
I have a test where I need to manually trigger an event, to ensure a controller updates the page appropriately in response.

My test effectively boiled down to something like this, which does not work:
  1. // It doesn't matter who adds this event listener: a controller, the page, or the test itself.
  2. S('.foo').on('test', function() {
  3.     console.log('test event caught', arguments, this);
  4. });

  5. S('.foo').trigger('test');  // nobody sees/handles this

I'm using the latest master of FuncUnit (from github, last commit was 3 months ago).

The Underlying Problem

Tracing through FuncUnit, the problem appears to originate from browser/actions.js:152 : it creates a jQuery collection using the test window's instance of jQuery, by reusing the original selector used with funcunit. From what I can tell, there are two problems with this:
  • If Funcunit's jQuery collection wasn't created with a selector -- as can happen within a loop, if you use S(this) for each element of the loop -- then that code always results in an empty collection, so we don't have anything to trigger events on.
  • As near as I can tell, events triggered via the test window's jQuery are never seen by any code which came from outside the test window -- such as the control being invoked by the test. I manually tested using Firebug and Chrome's js consoles in the test window itself (left over after the test finished), and events created via the console were not picked up by the controller created in my test script, even though the controller was still alive and well and responding to normal mouse clicks. (Edit: subsequent testing suggests that this isn't true after all. I'm not quite sure why neither the controller nor the created-by-test event listeners pick up the event.)

A Possible Fix


Both of these issues were fixed by updating the method for .trigger(), replacing:
  1. FuncUnit.win.jQuery(this.bind.selector).trigger(evName)
with:
  1. $(this.bind).trigger(evName);
(That $ is the local variable from steal, so it works even if the test window doesn't include its own copy of jQuery).

For my tests, that one change was sufficient to make all FuncUnit's .trigger() work as expected: My controller receives and responds to the event, and I can set up my own listeners within the test itself, if needed. They all receive the event, where previously nobody received it.


I've only tested this in-browser (we don't use PhantomJS), and I haven't tested thoroughly to see whether there might be side effects elsewhere, but for our tests that one-line change did exactly what we needed.

Can anybody confirm whether this is indeed the bug I think it is? If so, I can create an issue and/or pull request on github if desired.

Thanks,
Steven

Viewing all articles
Browse latest Browse all 3491

Trending Articles