1

In my Rails app there is a whole lot of front-end js, and I'd like to check is a specific event is attached to a DOM element.

An example of the JS that adds the event is here:

$('.nextCard')[0].addEventListener('click',nextCard);

I'd like to write something like:

     expect(page).evaluate_script('​$._data( $(".nextCard")[0], "events" )').to eq('nextCard');

I know it's a bit cryptic, and I could test the JS separately ... but I would like to do all the testing with Ruby / Capybara if possible.

How to return a value when using execute_script in capybara?

Can I find events bound on an element with jQuery?

Community
  • 1
  • 1
port5432
  • 5,889
  • 10
  • 60
  • 97

1 Answers1

1

Since you state the event is added using plain DOM methods (addEventListener) there is no way (cross browser/unprivileged code) to enumerate the listeners. However, if the handlers are attached via jQuery#on then you could check for the presence of a click handler with something like

expect(page.evaluate_script('​"click" in $._data( $(".nextCard")[0], "events" )')).to be true

That being said, what you're trying to do is not really a great idea, and will end up with really brittle tests. What you should be doing in your feature tests is verifying the behaviors those click handlers facilitate work.

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78