【发布时间】:2019-10-23 05:58:43
【问题描述】:
我目前正在创建我的第一个 JS 项目,并且是第一次尝试 Jasmine 单元测试。
在我的代码中,我想在我的一个类中测试该函数,该类将 css 类应用于按钮元素。但是我很难通过 Jasmine 测试,我不知道为什么。
测试失败,因为测试没有在目标按钮中看到 css 类“.btn-active”,这告诉我该功能没有运行,但我不确定如何实现这一点。
JS 类:
class ModeSelection {
constructor() {
this.easyBtn = $('#easy-mode');
this.mediumBtn = $('#medium-mode');
this.hardBtn = $('#hard-mode');
}
//applies the active class depending upon the button selected
easyMode() {
this.easyBtn.on('click', () => {
this.easyBtn.addClass('btn-active');
this.mediumBtn.removeClass('btn-active');
this.hardBtn.removeClass('btn-active');
$('.card-med').addClass('remove');
$('.card-hard').addClass('remove');
});
}
请注意,我在每个测试之前设置了一个夹具,其中包含我希望应用该类的 html 按钮。
夹具:
beforeEach(function() {
setFixtures(`
<div class="mode-select row">
<div class="col-sm-12 mode-header">
<h4>Select your difficulty</h4>
</div>
<div class="col-xs-12 col-sm-4">
<button id="easy-mode" class="btn btn-mode btn-easy">Easy</button>
</div>
<div class="col-xs-12 col-sm-4">
<button id="medium-mode" class="btn btn-mode btn-med">Medium</button>
</div>
<div class="col-xs-12 col-sm-4">
<button id="hard-mode" class="btn btn-mode btn-hard btn-active">Hard</button>
</div>
</div>
`)
});
茉莉花测试:
describe('Check easy mode functions', function() {
beforeEach(function() {
this.mode = new ModeSelection();
});
it('btn-active to be applied when easy function activated', function() {
var spy = spyOn(this.mode, 'easyMode').and.callThrough();
expect($('#easy-mode')).toHaveClass('btn-active')
});
});
抱歉,如果这是相当基本的,但是我对 Jasmine 很陌生,只是在寻找让这个测试正常工作的最佳方法。
谢谢
山姆
【问题讨论】:
-
你能在每个包含 HTML 按钮的测试之前显示夹具吗?
-
@CastroRoy 抱歉,我应该包括这个。我已将其添加到主要问题中。
-
我已经有一段时间没有这样做了...但是...您实际上在哪里触发了测试中的 onclick 事件? Spy 只是将方法包装在侦听器中,但不会调用它。
-
嗯,你为什么要在
this上声明mode,你可能应该使用在 beforeEach 上重新声明的mode的全局变量:let mode; beforeEach(() => { mode = new ModelSelection(); })而且你正在添加间谍而不是使用它然后你没有在测试用例中调用mode.easyMode()
标签: javascript jquery unit-testing testing jasmine