Reputation: 83
I am trying to test a piece of my code using Jasmine, but I am stuck on which method to use and how to go about testing this particular function. Here is my code:
const foodInfoToggle1 = () => {
const foodInfo = document.querySelector('#first');
foodInfo.style.display === "none" ? foodInfo.style.display = "block" : foodInfo.style.display = "none";
}
This function encompasses toggle functionality and is assigned to a button. Once the button is clicked, the function runs to see if the paragraph is set to 'none'. If it is, then it switches to 'block' and vice versa. As you can see, my function is not accepting any parameters so I am finding it difficult to use test cases. How exactly would I go about testing this type of code using Jasmine.
Upvotes: 0
Views: 1050
Reputation: 24965
describe('foodInfoToggle1', () => {
let element;
beforeEach(() => {
element = document.createElement('span');
spyOn(document, 'querySelector').and.callFake(selector => {
if (selector === '#first') return element;
});
});
it('Should change the display from none to block', () => {
element.style.display = 'none';
foodInfoToggle1();
expect(element.style.display).toEqual('block');
});
it('Should change the display from block to none', () => {
element.style.display = 'block';
foodInfoToggle1();
expect(element.style.display).toEqual('none');
});
});
I didn't find a quick way to include jasmine in the post, so hopefully all my syntax is correct.
The idea here being for each test, we create a dummy element and mockout the querySelector method. If it is called with the expected selector, return the dummy element.
Then for each of our tests, we put the style display in our expected initial value. We then call the method, and verify that the style display changed.
Upvotes: 1