I am currently creating my first JS project and am trying Jasmine unit testing for the first time.
In my code, I want to test the function in one of my classes which applies a css class to a button element. However I am having difficulty getting the Jasmine test to pass and I am not sure why.
The test fails due to the test not seeing the class '.btn-active' in the targeted button, which is telling me that the function is not running, however I am unsure as to how to achieve this.
JS Class:
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');
});
}
Please note, I have set a fixture before each test which contains the html button that I am looking to apply the class too.
Fixture:
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>
`)
});
Jasmine Test:
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')
});
});
Apologies if this is fairly basic, however I am quite new to Jasmine and was just seeking the best way to get this test to work.
Thank
Sam
This should work if you include your fixtures befor it:
let mode;
describe('ModeSelection', () => { // tested class name
beforeEach(() => {
mode = new ModeSelection(); // setup
});
describe('call easyMode()', () => { // tested method name
it('should add btn-active class to #easy-mode element', () => {
mode.easyMode(); // call tested method
expect($('#easy-mode')).toHaveClass('btn-active')// assert it ran correctly
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.