Вот решение для модульного теста:
index.ts
:
export function removeSlot(component: any, selector: string) {
if (component.querySelectorAll(selector).length > 0) {
component.querySelectorAll(selector).forEach((el) => el.remove());
} else {
console.error(`'${selector}' not found in component '${component.tagName.toLowerCase()}'`);
}
}
index.test.ts
:
import { removeSlot } from './';
describe('59886364', () => {
it('should remove each el', () => {
const mNodeList = [{ remove: jest.fn() }];
const mComponent = { querySelectorAll: jest.fn().mockReturnValue(mNodeList) };
const mSelector = 'ol';
removeSlot(mComponent, mSelector);
expect(mComponent.querySelectorAll).toBeCalledTimes(2);
expect(mComponent.querySelectorAll).toBeCalledWith(mSelector);
mNodeList.forEach((el) => {
expect(el.remove).toBeCalled();
});
});
it('should print error if no node found', () => {
jest.spyOn(console, 'error');
const mNodeList = [];
const mComponent = { tagName: 'DIV', querySelectorAll: jest.fn().mockReturnValue(mNodeList) };
const mSelector = 'ol';
removeSlot(mComponent, mSelector);
expect(mComponent.querySelectorAll).toBeCalledTimes(1);
expect(mComponent.querySelectorAll).toBeCalledWith(mSelector);
expect(console.error).toBeCalledWith(`'ol' not found in component 'div'`);
});
});
Результаты модульного теста со 100% покрытием:
PASS src/stackoverflow/59886364/index.test.ts
59886364
✓ should remove each el (6ms)
✓ should print error if no node found (4ms)
console.error node_modules/jest-mock/build/index.js:860
'ol' not found in component 'div'
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 5.377s, estimated 15s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59886364