Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect
and window.scrollTo
? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0.
Function that needs testing:
export default function scrollToEl(el) {
let elRect = el.getBoundingClientRect();
return window.scrollTo(
elRect.left + document.documentElement.scrollLeft,
elRect.top + document.documentElement.scrollTop
);
}
Existing Jest test with incomplete coverage:
import * as scroll from "../scrollToEl";
describe("scrollToEl test", () => {
let element;
let ev = jest.fn();
scroll.scrollToEl = jest.fn(() => {
ev;
});
beforeEach(() => {
element = document.createElement("div");
});
it("should be called", () => {
ev(element)
expect(ev).toHaveBeenCalled();
});
});
Any suggestions on achieving full 100% coverage in all categories? All help is appreciated.
UPDATE - achieved 100% coverage in all areas: https://i.stack.imgur.com/SxDSg.png
Updated JavaScript function:
I made changes to the initial export default function
statement by converting it to
export const scrollToEl = function (el)
export const scrollToEl = function (el) {
// ...
};
Revised Test:
To attain complete coverage, I simplified the test setup. The focus was on including and validating window.scrollTo
behavior while executing the function on a newly generated element (el)
.
import * as scroll from "../scrollToEl";
describe("scrollToEl test", () => {
beforeEach(() => {
window.scrollTo = jest.fn();
});
it("`window.scrollTo` should be called", () => {
const el = document.createElement("span");
scroll.scrollToEl(el);
expect(window.scrollTo).toHaveBeenCalled();
});
});