Jasmine jQuery: Using toBeHidden() and toBeVisible()

cantera picture cantera · Oct 29, 2013 · Viewed 12.2k times · Source

I need help working with the toBeHidden() and toBeVisible() methods of jQuery-Jasmine.

When a user checks a checkbox, a text field should slide down -- and unchecking slides it up. The text field is hidden when the page loads.

The code is working fine in my application, but I'm confused by the results I'm getting in my tests.

The first two are working -- checking if the field is hidden by default and visible on first change:

expect($('#text-field')).toBeHidden(); // passes

$('#checkbox').prop('checked', true).change();
expect($('#text-field')).toBeVisible(); // passes

But when the checkbox is unchecked, the text field slides up in the real version but fails in my test:

$('#checkbox').prop('checked', false).change();
expect($('#text-field')).toBeHidden(); // fails

I've also tried:

expect($('#text-field')).not.toBeVisible(); // fails
expect($('#text-field')).toHaveCss({display: "none"}); // fails

Does anyone know what I'm doing wrong or know what else I need to do to help Jasmine see that the text field slid up?

Answer

Daan picture Daan · Nov 13, 2013

You probably have the same problem that I did, your view is standard invisible in your tests because it is not attached to the DOM. Try this in your test:

$('body').append(view);