How to check that jQuery methods (fadeOut, hide, etc) have been called with Jasmine
-
07-04-2021 - |
Question
I'm trying to clean up my Javascript by employing the same TDD methods that work for me in Ruby, but the jump to Jasmine has been throwing me for a curve.
For a simple example, I'd like to specify that a given element fades out on click:
$('.position-details').live 'click', ->
$this = $(this)
$this.fadeOut 'fast', ->
$this.closest('.fields').find('.position-search').fadeIn('fast').focus()
My specs:
describe "Position picker", ->
beforeEach ->
loadFixtures("position_picker.html")
@details = $('.position-details')
@picker = $('.position-picker')
jasmine.Clock.useMock()
it "the position details are initially shown", ->
expect(@details).toBeVisible()
describe "when the position details are clicked", ->
it "fades out the position details", ->
@details.trigger('click')
jasmine.Clock.tick(1000)
expect(@details).not.toBeVisible()
My fixture:
<div id='position-data' data-positions="[{"value":35,"label":"Accountant","division":"North","job_class":"Headquarters"}]"></div>
<div class='position-details'>
<div class='position-name'></div>
<br />
</div>
<div class='position-picker'>
<label>Position<abbr title="required">*</abbr></label>
<span class="error" />
<input class="position-search" type="text" />
<div>
<input class="position_id" type="text" />
</div>
</div>
The first spec passes and I'm not sure why the second doesn't. Once I get a few of these under my belt I'm sure it'll feel second nature. Thanks for any help or advice!
OTHER TIPS
You can use spyOn
check this:
it("fades out the element", function() {
spyOn($.fn, 'fadeOut');
fadeOutElem();
expect($.fn.fadeOut).toHaveBeenCalled();
});
Also you can use a timeout like this:
it("fades out the element", function(done) {
fadeOutElem();
setTimeout(300, function() {
expect($(".position-details").css('display').toEqual('none');
done();
});
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow