我需要编写一个Jasmine.js测试来测试菜单图标在被单击时会发生什么(菜单栏在第一次单击时滑入,在第二次单击时滑出,但我的测试未能演示它)。
我想出了这个想法,但spec-runner显示(预计false为true)。有什么可以解决的问题吗?
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);
});
});发布于 2018-05-17 00:06:21
看起来您已经在使用Jasmine和JQuery了,所以我建议您也使用jasmine-jquery.js库来帮助您跟踪状态?
这是一个很好的参考:Testing That A DOM Event Was Fired
要让下面的代码正常工作,只需在项目文件夹中包含jasmine-jquery.js,通过index.html的<\head>和set链接<\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');
});
});https://stackoverflow.com/questions/48872864
复制相似问题