Ensure tests do not log warning or errors

This commit increases strictnes of tests by failing on tests (even
though they pass) if `console.warn` or `console.error` is used. This is
used to fix warning outputs from Vue, cleaning up test output and
preventing potential issues with tests.

This commit fixes all of the failing tests, including refactoring in
code to make them more testable through injecting Vue lifecycle
hook function stubs. This removes `shallowMount`ing done on places,
improving the speed of executing unit tests. It also reduces complexity
and increases maintainability by removing `@vue/test-utils` dependency
for these tests.

Changes:

- Register global hook for all tests to fail if console.error or
  console.warn is being used.
- Fix all issues with failing tests.
- Create test helper function for running code in a wrapper component to
  run code in reliable/unified way to surpress Vue warnings about code
  not running inside `setup`.
This commit is contained in:
undergroundwires
2024-07-23 16:08:04 +02:00
parent a6505587bf
commit ae0165f1fe
26 changed files with 359 additions and 205 deletions

View File

@@ -4,6 +4,8 @@ import { useDragHandler, type DragDomModifier } from '@/presentation/components/
import { ThrottleStub } from '@tests/unit/shared/Stubs/ThrottleStub';
import { type ThrottleFunction } from '@/application/Common/Timing/Throttle';
import type { ConstructorArguments } from '@/TypeHelpers';
import type { LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
import { LifecycleHookStub } from '@tests/unit/shared/Stubs/LifecycleHookStub';
describe('useDragHandler', () => {
describe('initially', () => {
@@ -80,7 +82,7 @@ describe('useDragHandler', () => {
const finalDragX = 150;
const expectedDisplacementX = finalDragX - initialDragX;
const mockElement = document.createElement('div');
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
const { displacementX } = initializeDragHandlerWithMocks({
@@ -100,7 +102,7 @@ describe('useDragHandler', () => {
'pointermove',
];
const mockElement = document.createElement('div');
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
initializeDragHandlerWithMocks({
@@ -153,7 +155,7 @@ describe('useDragHandler', () => {
const expectedTotalThrottledEvents = 3;
const throttleStub = new ThrottleStub();
const mockElement = document.createElement('div');
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
initializeDragHandlerWithMocks({
@@ -176,7 +178,7 @@ describe('useDragHandler', () => {
const mockElement = document.createElement('div');
const initialDragX = 100;
const firstDisplacementX = 10;
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
const { displacementX } = initializeDragHandlerWithMocks({
@@ -199,7 +201,7 @@ describe('useDragHandler', () => {
// arrange
const expectedDraggingState = false;
const mockElement = document.createElement('div');
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
const { isDragging } = initializeDragHandlerWithMocks({
@@ -215,7 +217,7 @@ describe('useDragHandler', () => {
it('removes event listeners', () => {
// arrange
const mockElement = document.createElement('div');
const dragDomModifierMock = new DragDomModifierMock();
const dragDomModifierMock = createDragDomModifierMock();
// act
initializeDragHandlerWithMocks({
@@ -225,6 +227,27 @@ describe('useDragHandler', () => {
mockElement.dispatchEvent(createMockPointerEvent('pointerdown', { clientX: 100 }));
dragDomModifierMock.simulateEvent('pointerup', createMockPointerEvent('pointerup'));
// assert
const actualEvents = [...dragDomModifierMock.events];
expect(actualEvents).to.have.lengthOf(0);
});
});
describe('on teardown', () => {
it('removes event listeners', () => {
// arrange
const teardownHook = new LifecycleHookStub();
const mockElement = document.createElement('div');
const dragDomModifierMock = createDragDomModifierMock();
// act
initializeDragHandlerWithMocks({
draggableElementRef: ref(mockElement),
dragDomModifier: dragDomModifierMock,
onTeardown: teardownHook.getHook(),
});
mockElement.dispatchEvent(createMockPointerEvent('pointerdown', { clientX: 100 }));
teardownHook.executeAllCallbacks();
// assert
const actualEvents = [...dragDomModifierMock.events];
expect(actualEvents).to.have.lengthOf(0);
@@ -236,11 +259,13 @@ function initializeDragHandlerWithMocks(mocks?: {
readonly dragDomModifier?: DragDomModifier;
readonly draggableElementRef?: Ref<HTMLElement>;
readonly throttler?: ThrottleFunction,
readonly onTeardown?: LifecycleHook,
}) {
return useDragHandler(
mocks?.draggableElementRef ?? ref(document.createElement('div')),
mocks?.dragDomModifier ?? new DragDomModifierMock(),
mocks?.dragDomModifier ?? createDragDomModifierMock(),
mocks?.throttler ?? new ThrottleStub().withImmediateExecution(true).func,
mocks?.onTeardown ?? new LifecycleHookStub().getHook(),
);
}
@@ -248,22 +273,25 @@ function createMockPointerEvent(...args: ConstructorArguments<typeof PointerEven
return new MouseEvent(...args) as PointerEvent; // jsdom does not support `PointerEvent` constructor, https://github.com/jsdom/jsdom/issues/2527
}
class DragDomModifierMock implements DragDomModifier {
public events = new Map<keyof DocumentEventMap, EventListener>();
public addEventListenerToDocument(type: keyof DocumentEventMap, handler: EventListener): void {
this.events.set(type, handler);
}
public removeEventListenerFromDocument(type: keyof DocumentEventMap): void {
this.events.delete(type);
}
public simulateEvent(type: keyof DocumentEventMap, event: Event) {
const handler = this.events.get(type);
if (!handler) {
throw new Error(`No event handler registered for: ${type}`);
}
handler(event);
}
function createDragDomModifierMock(): DragDomModifier & {
simulateEvent(type: keyof DocumentEventMap, event: Event): void;
readonly events: Map<keyof DocumentEventMap, EventListener>;
} {
const events = new Map<keyof DocumentEventMap, EventListener>();
return {
addEventListenerToDocument: (type, handler) => {
events.set(type, handler);
},
removeEventListenerFromDocument: (type) => {
events.delete(type);
},
simulateEvent: (type, event) => {
const handler = events.get(type);
if (!handler) {
throw new Error(`No event handler registered for: ${type}`);
}
handler(event);
},
events,
};
}

View File

@@ -1,23 +1,25 @@
import { it, describe, expect } from 'vitest';
import {
type Ref, ref, defineComponent, nextTick,
type Ref, ref, nextTick,
} from 'vue';
import { shallowMount } from '@vue/test-utils';
import { type CursorStyleDomModifier, useGlobalCursor } from '@/presentation/components/Scripts/Slider/UseGlobalCursor';
import type { LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
import { LifecycleHookStub } from '@tests/unit/shared/Stubs/LifecycleHookStub';
describe('useGlobalCursor', () => {
it('adds cursor style to head on activation', async () => {
// arrange
const expectedCursorCssStyleValue = 'pointer';
const isActive = ref(false);
const domModifier = new CursorStyleDomModifierStub();
// act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive });
createHookWithStubs({ isActive, domModifier });
isActive.value = true;
await nextTick();
// assert
const { elementsAppendedToHead: appendedElements } = cursorStyleDomModifierMock;
const { elementsAppendedToHead: appendedElements } = domModifier;
expect(appendedElements.length).to.equal(1);
expect(appendedElements[0].innerHTML).toContain(expectedCursorCssStyleValue);
});
@@ -25,75 +27,61 @@ describe('useGlobalCursor', () => {
it('removes cursor style from head on deactivation', async () => {
// arrange
const isActive = ref(true);
const domModifier = new CursorStyleDomModifierStub();
// act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive });
createHookWithStubs({ isActive, domModifier });
await nextTick();
isActive.value = false;
await nextTick();
// assert
expect(cursorStyleDomModifierMock.elementsRemovedFromHead.length).to.equal(1);
expect(domModifier.elementsRemovedFromHead.length).to.equal(1);
});
it('cleans up cursor style on unmount', async () => {
// arrange
const isActive = ref(true);
const domModifier = new CursorStyleDomModifierStub();
const onTeardown = new LifecycleHookStub();
// act
const { wrapper, returnObject } = mountWrapperComponent({ isActive });
wrapper.unmount();
createHookWithStubs({ isActive, domModifier, onTeardown: onTeardown.getHook() });
onTeardown.executeAllCallbacks();
await nextTick();
// assert
const { cursorStyleDomModifierMock } = returnObject;
expect(cursorStyleDomModifierMock.elementsRemovedFromHead.length).to.equal(1);
expect(onTeardown.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(domModifier.elementsRemovedFromHead.length).to.equal(1);
});
it('does not append style to head when initially inactive', async () => {
// arrange
const isActive = ref(false);
const domModifier = new CursorStyleDomModifierStub();
// act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive });
createHookWithStubs({ isActive, domModifier });
await nextTick();
// assert
expect(cursorStyleDomModifierMock.elementsAppendedToHead.length).toBe(0);
expect(domModifier.elementsAppendedToHead.length).toBe(0);
});
});
function mountWrapperComponent(...hookOptions: Parameters<typeof createHookWithStubs>) {
let returnObject: ReturnType<typeof createHookWithStubs> | undefined;
const wrapper = shallowMount(
defineComponent({
setup() {
returnObject = createHookWithStubs(...hookOptions);
},
template: '<div></div>',
}),
);
if (!returnObject) {
throw new Error('missing hook result');
}
return {
wrapper,
returnObject,
};
}
function createHookWithStubs(options?: {
readonly isActive?: Ref<boolean>;
readonly expectedCursorCssStyleValue?: string;
readonly domModifier?: CursorStyleDomModifier;
readonly onTeardown?: LifecycleHook;
}) {
const cursorStyleDomModifierMock = new CursorStyleDomModifierStub();
const hookResult = useGlobalCursor(
options?.isActive ?? ref(true),
options?.expectedCursorCssStyleValue ?? 'pointer',
cursorStyleDomModifierMock,
options?.domModifier ?? new CursorStyleDomModifierStub(),
options?.onTeardown ?? new LifecycleHookStub().getHook(),
);
return {
cursorStyleDomModifierMock,
hookResult,
};
}