gpt4 book ai didi

javascript - 用 Jasmine 测试点击事件?

转载 作者:行者123 更新时间:2023-11-29 11:00:02 24 4
gpt4 key购买 nike

我需要编写一个 Jasmine.js 测试来测试单击菜单图标时会发生什么,(第一次单击时菜单栏滑入,第二次单击时滑出)第二次它确实如此,但我的测试未能证明它)

我想出了这个主意,但 spec-runner 显示(预期为假)。对可能出现的问题有什么帮助吗?

describe('The menu', function () {
/* TODO: Write a test that ensures the menu changes
* visibility when the menu icon is clicked. This test
* should have two expectations: does the menu display when
* clicked and does it hide when clicked again.
*/

it('the menu changes visibility when the menu icon is clicked', function () {

var menuIconClicked, menuChangesWhenClicked = false,
menuChangesWhenClickedAgain = false;

$(".menu-icon-link").click(function(){
var $this = $(this);
$(this).data('clicked', true);
if($(this).data('clicked')) {
menuIconClicked=true // if menu icon is clicked, set the menuIconClicked value to true
if (menuIconClicked && $('body').hasClass(null)) {
menuChangesWhenClicked=true;

}
}
if($this.data('clicked') && menuIconClicked===true) {
menuIconClicked=false // if menu icon is clicked when it already has been clicked aka menuIconClicked===true
if (!menuIconClicked && $('body').hasClass('menu-hidden')) {
menuChangesWhenClickedAgain=true;

}
}

});
expect(menuChangesWhenClicked).toBe(true);

expect(menuChangesWhenClickedAgain).toBe(true);

});

});

最佳答案

看起来您已经在使用 Jasmine 和 JQuery,所以我建议您也使用 jasmine-jquery.js库来帮助您跟踪状态?

这是一个很好的引用:Testing That A DOM Event Was Fired

要使下面的代码起作用,只需在项目文件夹中包含 jasmine-jquery.js,通过 index.html 的 <\head> 和您的集合链接 <\script>。希望这可以帮助。

describe('The menu', function() {
// Add a spyOnEvent
let spyEvent, menu;

beforeEach(function() {
// I assumed your menu icon has a unique ID of 'menuIconID'
// so I passed onto a spy listener.
spyEvent = spyOnEvent('#menuIconID', 'click');
});
it('the menu changes visibility when the menu icon is clicked', function() {

// Click once
$("#menuIconID").trigger("click");
expect('click').toHaveBeenTriggeredOn('#menuIconID');
expect(spyEvent).toHaveBeenTriggered();
menu = $('body').attr('class'); // assign the new class
expect(menu).toBe('');

// Click again
$("#menuIconID").trigger("click");
expect('click').toHaveBeenTriggeredOn('#menuIconID');
expect(spyEvent).toHaveBeenTriggered();
menu = $('body').attr('class'); // update the new class
expect(menu).toBe('menu-hidden');
});
});

关于javascript - 用 Jasmine 测试点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48872864/

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