foo.testFunc()); var foo = { testFunc:-6ren">
gpt4 book ai didi

javascript - 如何用 Jasmine 测试这个 Javascript

转载 作者:行者123 更新时间:2023-12-03 01:56:21 26 4
gpt4 key购买 nike

我有一个问题,我想测试这个 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

是否无法对此进行测试,或者我做错了什么?

最佳答案

您可以做的是监视 document.getElementById 并使其返回具有 click 功能的对象:

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

jsFiddle

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

jsFiddle

关于javascript - 如何用 Jasmine 测试这个 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50212179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com