Вот решение для модульного теста:
index.js
:
class SomeClass {
skipToBotHandler() {
const skipNav = document.querySelector('.skipnav');
skipNav.addEventListener('click', () => {
this.skipLinkFocusHandler();
});
}
skipLinkFocusHandler() {}
}
export { SomeClass };
index.test.js
:
import { SomeClass } from './';
describe('60014903', () => {
afterEach(() => {
jest.restoreAllMocks();
jest.resetAllMocks();
});
it('should pass', () => {
jest.spyOn(SomeClass.prototype, 'skipLinkFocusHandler');
const mSkipNav = {
addEventListener: jest.fn().mockImplementationOnce((event, handler) => {
handler();
}),
};
document.querySelector = jest.fn().mockReturnValueOnce(mSkipNav);
const instance = new SomeClass();
instance.skipToBotHandler();
expect(document.querySelector).toBeCalledWith('.skipnav');
expect(mSkipNav.addEventListener).toBeCalledWith('click', expect.any(Function));
expect(instance.skipLinkFocusHandler).toBeCalledTimes(1);
});
});
Результаты модульного теста со 100% покрытием:
PASS src/stackoverflow/60014903/index.test.js (10.203s)
60014903
✓ should pass (9ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.538s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/60014903