如何用Jasmine测试这个Javascript

时间:2018-05-07 10:35:50

标签: javascript json jasmine karma-jasmine

我有一个问题,我想测试这个javascript

$("#ShootBtn").on('click', () => foo.testFunc());

var foo = {
    testFunc: function() {
        hub.server.shoot(true, username, gameCode);
   }
}

我使用Jasmine作为我的测试框架,我尝试过Karma和Chutzpah作为我的测试运行员。

在我的测试项目中,我尝试参考上面的文件,我尝试尝试了很多不同的东西,但我似乎无法理解它。测试看起来像这个atm。

/// <reference path="../../TankWebApplication/Scripts/jquery-3.3.1.js"/>
/// <reference path="../../TankWebApplication/Scripts/virtualjoystick.js"/>
/// <reference path="../../TankWebApplication/Scripts/gameController.js"/>


describe("DefaultTest",
function () {

    beforeEach(function() {

    })

    it("Test",
        function() {
            spyOn(foo, 'testFunc');
            document.getElementById('ShootBtn').click();
            expect(foo.testFunc).toHaveBeenCalled();

        });


});

testFunc尚未被称为:

TypeError: Cannot read property 'click' of null

我认为这意味着它无法点击我的shootBtn

不可能测试这个,或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

你可以做的是监视document.getElementById并让它返回一个具有click功能的对象:

   spyOn(document, "getElementById").andCallFake(() => ({
       click: () => foo.testFunc()
   })); 

jsFiddle

否则,创建一个id = ShootBtn的元素,附加一个点击处理程序然后将其添加到正文中(所有这些都应该在测试中完成)

jsFiddle