Jasmine jQuery: Using toBeHidden() and toBeVisible()
Asked Answered
C

2

7

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?

Chap answered 29/10, 2013 at 19:10 Comment(0)
C
10

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);
Corduroys answered 13/11, 2013 at 15:39 Comment(0)
E
5

.toBeHidden and .toBeVisible or not opposites, see the Jasmine-jquery docs. I advice you to use .toBeHidden and .not.toBeHidden in conjunction.

Note that .toBeHidden does this.actual.is(':hidden') which means that it consumes no space (https://api.jquery.com/hidden-selector/), so it expects your fixtures to be appended to the body.

.toBeVisible checks for this.actual.is(':visible') which, according to the jQuery docs, means that it checks if the element has visibility: hidden or opacity: 0. So it could consume space, but should has no visibility.

Excurvate answered 16/4, 2015 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.