最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test a function call inside a click event with Jasmine - Stack Overflow

programmeradmin0浏览0评论

I'm fairly new with Jasmine and I'm trying to test a very simple scenario

Code under test

$(function () {

    $("#add_distribution_list").click(function () {
        CommonNs.Utils.setWindowLocationHRef("hello.html");
    });

});

Fixture

<input type='button' value='Add' id='add_distribution_list'/>

Test

describe("Distribution List Page", function () {
    beforeEach(function(){
        loadFixtures('button.html');
        spyOn(CommonNs.Utils, 'setWindowLocationHRef');
    });

    it("button redirects to action2", function () {
        $('#add_distribution_list').click();
        expect( CommonNs.Utils.setWindowLocationHRef).toHaveBeenCalled();
    });
});

Result

Expected spy setWindowLocationHRef to have been called.

My SpecRunner.html imports jquery, jasmine-jquery, and the utility file in which CommonNs.Utils lives.

How can I assert that the method on CommonNs.Utils has been called?

I'm fairly new with Jasmine and I'm trying to test a very simple scenario

Code under test

$(function () {

    $("#add_distribution_list").click(function () {
        CommonNs.Utils.setWindowLocationHRef("hello.html");
    });

});

Fixture

<input type='button' value='Add' id='add_distribution_list'/>

Test

describe("Distribution List Page", function () {
    beforeEach(function(){
        loadFixtures('button.html');
        spyOn(CommonNs.Utils, 'setWindowLocationHRef');
    });

    it("button redirects to action2", function () {
        $('#add_distribution_list').click();
        expect( CommonNs.Utils.setWindowLocationHRef).toHaveBeenCalled();
    });
});

Result

Expected spy setWindowLocationHRef to have been called.

My SpecRunner.html imports jquery, jasmine-jquery, and the utility file in which CommonNs.Utils lives.

How can I assert that the method on CommonNs.Utils has been called?

Share Improve this question asked Dec 19, 2014 at 9:48 Luciano FiandesioLuciano Fiandesio 10.2k10 gold badges51 silver badges58 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

I'd expect that you'll need to trigger click event on 'add_distribution_list' using .trigger()

$('#add_distribution_list').trigger('click');

Then use a jasmine spy to monitor the method being called.

There is a good post here on testing dom events with jasmine 2.x and there is a cheetsheet on using jasmine spies here

There is a similar question relating to .trigger on jasmine test that may also help here

发布评论

评论列表(0)

  1. 暂无评论