So here is curious case of a statement not getting covered by jasmin karma test runner, here is the function under testing
aFunction(fewParams) {
if (fewCondition) {
let elements = document.querySelectorAll(`[id^=${aParam}]`);
let anElement = find(elements, (el) => el.classList.contains('a-class-name'));
if (anElement) {
/* rest of the logic */
}
if (updatedConditions) {
/*rest of the logic*/
}
}
}
and here is the test
describe('aFunction', () => {
it('it should do aFunctionality', () => {
spyOn(document, "querySelectorAll").and.callFake(function() {
return {
value: true,
classList: {
remove: () => {},
add: () => {},
contains: () => { return ["a-class-name"] }
}
}
});
componentInstance.aFunction("test", 1, true);
expect(componentInstance.something).toBe(soemthing);
});
});
So the issue is here the
if (anElement) {
}
statement is not getting covered even if the mock function for querySelectorAll is returning a classlist with required value.
Can you please help me with this?
If you spy on an element it looks like it is swallowing any runtime errors.
This is quite similar to the last issue, where add and remove was undefined. This time the problem is, that you are mocking the querySelectorAll method, which would need to return an array, so that the find
method will be defined. You are returning an object and the find method does not exists on an object.
You would need to return something like this:
spyOn(document, "querySelectorAll").and.callFake(function() {
return [{ // note the array here
value: true,
classList: {
remove: () => {},
add: () => {},
contains: () => { return ["a-class-name"] }
}
}]
});