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

@@ -3,6 +3,7 @@ import {
} from 'vue'; } from 'vue';
import { throttle } from '@/application/Common/Timing/Throttle'; import { throttle } from '@/application/Common/Timing/Throttle';
import type { Ref } from 'vue'; import type { Ref } from 'vue';
import type { LifecycleHook } from '../../Shared/Hooks/Common/LifecycleHook';
const ThrottleInMs = 15; const ThrottleInMs = 15;
@@ -10,6 +11,7 @@ export function useDragHandler(
draggableElementRef: Readonly<Ref<HTMLElement | undefined>>, draggableElementRef: Readonly<Ref<HTMLElement | undefined>>,
dragDomModifier: DragDomModifier = new GlobalDocumentDragDomModifier(), dragDomModifier: DragDomModifier = new GlobalDocumentDragDomModifier(),
throttler = throttle, throttler = throttle,
onTeardown: LifecycleHook = onUnmounted,
) { ) {
const displacementX = ref(0); const displacementX = ref(0);
const isDragging = ref(false); const isDragging = ref(false);
@@ -52,7 +54,7 @@ export function useDragHandler(
element.addEventListener('pointerdown', startDrag); element.addEventListener('pointerdown', startDrag);
} }
onUnmounted(() => { onTeardown(() => {
stopDrag(); stopDrag();
}); });

View File

@@ -1,9 +1,11 @@
import { watch, type Ref, onUnmounted } from 'vue'; import { watch, type Ref, onUnmounted } from 'vue';
import type { LifecycleHook } from '../../Shared/Hooks/Common/LifecycleHook';
export function useGlobalCursor( export function useGlobalCursor(
isActive: Readonly<Ref<boolean>>, isActive: Readonly<Ref<boolean>>,
cursorCssValue: string, cursorCssValue: string,
documentAccessor: CursorStyleDomModifier = new GlobalDocumentCursorStyleDomModifier(), documentAccessor: CursorStyleDomModifier = new GlobalDocumentCursorStyleDomModifier(),
onTeardown: LifecycleHook = onUnmounted,
) { ) {
const cursorStyle = createCursorStyle(cursorCssValue, documentAccessor); const cursorStyle = createCursorStyle(cursorCssValue, documentAccessor);
@@ -15,7 +17,7 @@ export function useGlobalCursor(
} }
}); });
onUnmounted(() => { onTeardown(() => {
documentAccessor.removeElement(cursorStyle); documentAccessor.removeElement(cursorStyle);
}); });
} }

View File

@@ -0,0 +1,8 @@
/*
These types are used to abstract Vue Lifecycle injection APIs
(e.g., onBeforeMount, onUnmount) for better testability.
*/
export type LifecycleHook = (callback: LifecycleHookCallback) => void;
export type LifecycleHookCallback = () => void;

View File

@@ -5,14 +5,15 @@ import {
import { throttle, type ThrottleFunction } from '@/application/Common/Timing/Throttle'; import { throttle, type ThrottleFunction } from '@/application/Common/Timing/Throttle';
import { useResizeObserverPolyfill } from './UseResizeObserverPolyfill'; import { useResizeObserverPolyfill } from './UseResizeObserverPolyfill';
import { useAnimationFrameLimiter } from './UseAnimationFrameLimiter'; import { useAnimationFrameLimiter } from './UseAnimationFrameLimiter';
import type { LifecycleHook } from '../Common/LifecycleHook';
export function useResizeObserver( export function useResizeObserver(
config: ResizeObserverConfig, config: ResizeObserverConfig,
usePolyfill = useResizeObserverPolyfill, usePolyfill = useResizeObserverPolyfill,
useFrameLimiter = useAnimationFrameLimiter, useFrameLimiter = useAnimationFrameLimiter,
throttler: ThrottleFunction = throttle, throttler: ThrottleFunction = throttle,
onSetup: LifecycleHookRegistration = onBeforeMount, onSetup: LifecycleHook = onBeforeMount,
onTeardown: LifecycleHookRegistration = onBeforeUnmount, onTeardown: LifecycleHook = onBeforeUnmount,
) { ) {
const { resetNextFrame, cancelNextFrame } = useFrameLimiter(); const { resetNextFrame, cancelNextFrame } = useFrameLimiter();
// This prevents the 'ResizeObserver loop completed with undelivered notifications' error when // This prevents the 'ResizeObserver loop completed with undelivered notifications' error when
@@ -63,5 +64,3 @@ export interface ResizeObserverConfig {
} }
export type ObservedElementReference = Readonly<Ref<HTMLElement | undefined>>; export type ObservedElementReference = Readonly<Ref<HTMLElement | undefined>>;
export type LifecycleHookRegistration = (callback: () => void) => void;

View File

@@ -4,12 +4,17 @@ import {
watch, watch,
type Ref, type Ref,
} from 'vue'; } from 'vue';
import type { LifecycleHook } from './Common/LifecycleHook';
export interface UseEventListener { export interface UseEventListener {
(): TargetEventListener; (
onTeardown?: LifecycleHook,
): TargetEventListener;
} }
export const useAutoUnsubscribedEventListener: UseEventListener = () => ({ export const useAutoUnsubscribedEventListener: UseEventListener = (
onTeardown = onBeforeUnmount,
) => ({
startListening: (eventTargetSource, eventType, eventHandler) => { startListening: (eventTargetSource, eventType, eventHandler) => {
const eventTargetRef = isEventTarget(eventTargetSource) const eventTargetRef = isEventTarget(eventTargetSource)
? shallowRef(eventTargetSource) ? shallowRef(eventTargetSource)
@@ -18,6 +23,7 @@ export const useAutoUnsubscribedEventListener: UseEventListener = () => ({
eventTargetRef, eventTargetRef,
eventType, eventType,
eventHandler, eventHandler,
onTeardown,
); );
}, },
}); });
@@ -42,6 +48,7 @@ function startListeningRef<TEvent extends keyof HTMLElementEventMap>(
eventTargetRef: Readonly<Ref<EventTarget | undefined>>, eventTargetRef: Readonly<Ref<EventTarget | undefined>>,
eventType: TEvent, eventType: TEvent,
eventHandler: (event: HTMLElementEventMap[TEvent]) => void, eventHandler: (event: HTMLElementEventMap[TEvent]) => void,
onTeardown: LifecycleHook,
): void { ): void {
const eventListenerManager = new EventListenerManager(); const eventListenerManager = new EventListenerManager();
watch(() => eventTargetRef.value, (element) => { watch(() => eventTargetRef.value, (element) => {
@@ -52,7 +59,7 @@ function startListeningRef<TEvent extends keyof HTMLElementEventMap>(
eventListenerManager.addListener(element, eventType, eventHandler); eventListenerManager.addListener(element, eventType, eventHandler);
}, { immediate: true }); }, { immediate: true });
onBeforeUnmount(() => { onTeardown(() => {
eventListenerManager.removeListenerIfExists(); eventListenerManager.removeListenerIfExists();
}); });
} }

View File

@@ -1,15 +1,17 @@
import { onUnmounted } from 'vue'; import { onUnmounted } from 'vue';
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection'; import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
import type { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection'; import type { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
import type { LifecycleHook } from './Common/LifecycleHook';
export function useAutoUnsubscribedEvents( export function useAutoUnsubscribedEvents(
events: IEventSubscriptionCollection = new EventSubscriptionCollection(), events: IEventSubscriptionCollection = new EventSubscriptionCollection(),
onTeardown: LifecycleHook = onUnmounted,
) { ) {
if (events.subscriptionCount > 0) { if (events.subscriptionCount > 0) {
throw new Error('there are existing subscriptions, this may lead to side-effects'); throw new Error('there are existing subscriptions, this may lead to side-effects');
} }
onUnmounted(() => { onTeardown(() => {
events.unsubscribeAll(); events.unsubscribeAll();
}); });

View File

@@ -1,10 +1,10 @@
import { it, describe, expect } from 'vitest'; import { it, describe, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils'; import { inject } from 'vue';
import { defineComponent, inject } from 'vue';
import { type InjectionKeySelector, InjectionKeys, injectKey } from '@/presentation/injectionSymbols'; import { type InjectionKeySelector, InjectionKeys, injectKey } from '@/presentation/injectionSymbols';
import { provideDependencies } from '@/presentation/bootstrapping/DependencyProvider'; import { provideDependencies } from '@/presentation/bootstrapping/DependencyProvider';
import { buildContext } from '@/application/Context/ApplicationContextFactory'; import { buildContext } from '@/application/Context/ApplicationContextFactory';
import type { IApplicationContext } from '@/application/Context/IApplicationContext'; import type { IApplicationContext } from '@/application/Context/IApplicationContext';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';
describe('DependencyResolution', () => { describe('DependencyResolution', () => {
describe('all dependencies can be injected', async () => { describe('all dependencies can be injected', async () => {
@@ -16,7 +16,7 @@ describe('DependencyResolution', () => {
// act // act
const resolvedDependency = resolve(() => key, dependencies); const resolvedDependency = resolve(() => key, dependencies);
// assert // assert
expect(resolvedDependency).to.toBeDefined(); expect(resolvedDependency).toBeDefined();
}); });
}); });
}); });
@@ -40,13 +40,14 @@ function resolve<T>(
providedKeys: ProvidedKeys, providedKeys: ProvidedKeys,
): T | undefined { ): T | undefined {
let injectedDependency: T | undefined; let injectedDependency: T | undefined;
shallowMount(defineComponent({ executeInComponentSetupContext({
setup() { setupCallback: () => {
injectedDependency = injectKey(selector); injectedDependency = injectKey(selector);
}, },
}), { mountOptions: {
global: { global: {
provide: providedKeys, provide: providedKeys,
},
}, },
}); });
return injectedDependency; return injectedDependency;

View File

@@ -3,7 +3,7 @@ import {
} from 'vitest'; } from 'vitest';
import { IconNames } from '@/presentation/components/Shared/Icon/IconName'; import { IconNames } from '@/presentation/components/Shared/Icon/IconName';
import { useSvgLoader } from '@/presentation/components/Shared/Icon/UseSvgLoader'; import { useSvgLoader } from '@/presentation/components/Shared/Icon/UseSvgLoader';
import { waitForValueChange } from '@tests/shared/WaitForValueChange'; import { waitForValueChange } from '@tests/shared/Vue/WaitForValueChange';
describe('useSvgLoader', () => { describe('useSvgLoader', () => {
describe('can load all SVGs', () => { describe('can load all SVGs', () => {

View File

@@ -1,8 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { defineComponent } from 'vue';
import { useKeyboardInteractionState } from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState'; import { useKeyboardInteractionState } from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
import { expectExists } from '@tests/shared/Assertions/ExpectExists'; import { expectExists } from '@tests/shared/Assertions/ExpectExists';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';
describe('useKeyboardInteractionState', () => { describe('useKeyboardInteractionState', () => {
describe('isKeyboardBeingUsed', () => { describe('isKeyboardBeingUsed', () => {
@@ -49,12 +48,12 @@ function triggerKeyPress() {
function mountWrapperComponent() { function mountWrapperComponent() {
let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined; let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined;
const wrapper = shallowMount(defineComponent({ const wrapper = executeInComponentSetupContext({
setup() { setupCallback: () => {
returnObject = useKeyboardInteractionState(); returnObject = useKeyboardInteractionState();
}, },
template: '<div></div>', disableAutoUnmount: true,
})); });
expectExists(returnObject); expectExists(returnObject);
return { return {
returnObject, returnObject,

View File

@@ -0,0 +1,27 @@
import { shallowMount, type ComponentMountingOptions } from '@vue/test-utils';
import { defineComponent } from 'vue';
type MountOptions = ComponentMountingOptions<unknown>;
/**
* A test helper utility that provides a component `setup()` context.
* This function allows running code that depends on Vue lifecycle hooks,
* such as `onMounted`, within a component's `setup` function.
*/
export function executeInComponentSetupContext(options: {
readonly setupCallback: () => void;
readonly disableAutoUnmount?: boolean;
readonly mountOptions?: MountOptions,
}): ReturnType<typeof shallowMount> {
const componentWrapper = shallowMount(defineComponent({
setup() {
options.setupCallback();
},
// Component requires a template or render function
template: '<div>Test Component: setup context</div>',
}), options.mountOptions);
if (!options.disableAutoUnmount) {
componentWrapper.unmount(); // Ensure cleanup of callback tasks
}
return componentWrapper;
}

View File

@@ -0,0 +1,23 @@
import {
beforeEach, afterEach, vi, expect,
} from 'vitest';
import type { FunctionKeys } from '@/TypeHelpers';
export function failTestOnConsoleError() {
const consoleMethodsToCheck: readonly FunctionKeys<Console>[] = [
'warn',
'error',
];
beforeEach(() => {
consoleMethodsToCheck.forEach((methodName) => {
vi.spyOn(console, methodName).mockClear();
});
});
afterEach(() => {
consoleMethodsToCheck.forEach((methodName) => {
expect(console[methodName]).not.toHaveBeenCalled();
});
});
}

View File

@@ -1,6 +1,8 @@
import { afterEach } from 'vitest'; import { afterEach } from 'vitest';
import { enableAutoUnmount } from '@vue/test-utils'; import { enableAutoUnmount } from '@vue/test-utils';
import { polyfillBlob } from './BlobPolyfill'; import { polyfillBlob } from './BlobPolyfill';
import { failTestOnConsoleError } from './FailTestOnConsoleError';
enableAutoUnmount(afterEach); enableAutoUnmount(afterEach);
polyfillBlob(); polyfillBlob();
failTestOnConsoleError();

View File

@@ -6,6 +6,7 @@ import { ApplicationContextStub } from '@tests/unit/shared/Stubs/ApplicationCont
import { itIsSingletonFactory } from '@tests/unit/shared/TestCases/SingletonFactoryTests'; import { itIsSingletonFactory } from '@tests/unit/shared/TestCases/SingletonFactoryTests';
import type { IApplicationContext } from '@/application/Context/IApplicationContext'; import type { IApplicationContext } from '@/application/Context/IApplicationContext';
import { itIsTransientFactory } from '@tests/unit/shared/TestCases/TransientFactoryTests'; import { itIsTransientFactory } from '@tests/unit/shared/TestCases/TransientFactoryTests';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';
describe('DependencyProvider', () => { describe('DependencyProvider', () => {
describe('provideDependencies', () => { describe('provideDependencies', () => {
@@ -55,9 +56,14 @@ function createTransientTests() {
.provideDependencies(); .provideDependencies();
// act // act
const getFactoryResult = () => { const getFactoryResult = () => {
const registeredObject = api.inject(injectionKey); const registeredFactory = api.inject(injectionKey) as () => unknown;
const factory = registeredObject as () => unknown; let factoryResult: unknown;
return factory(); executeInComponentSetupContext({
setupCallback: () => {
factoryResult = registeredFactory();
},
});
return factoryResult;
}; };
// assert // assert
itIsTransientFactory({ itIsTransientFactory({
@@ -97,6 +103,7 @@ function createSingletonTests() {
}); });
}; };
} }
class ProvideDependenciesBuilder { class ProvideDependenciesBuilder {
private context: IApplicationContext = new ApplicationContextStub(); private context: IApplicationContext = new ApplicationContextStub();

View File

@@ -13,23 +13,10 @@ describe('CircleRating.vue', () => {
const currentRating = MAX_RATING - 1; const currentRating = MAX_RATING - 1;
// act // act
const wrapper = shallowMount(CircleRating, { const wrapper = mountComponent({
propsData: { rating: currentRating,
rating: currentRating,
},
}); });
// assert
const ratingCircles = wrapper.findAllComponents(RatingCircle);
expect(ratingCircles.length).to.equal(expectedMaxRating);
});
it('renders the correct number of RatingCircle components for default rating', () => {
// arrange
const expectedMaxRating = MAX_RATING;
// act
const wrapper = shallowMount(CircleRating);
// assert // assert
const ratingCircles = wrapper.findAllComponents(RatingCircle); const ratingCircles = wrapper.findAllComponents(RatingCircle);
expect(ratingCircles.length).to.equal(expectedMaxRating); expect(ratingCircles.length).to.equal(expectedMaxRating);
@@ -42,10 +29,8 @@ describe('CircleRating.vue', () => {
const expectedTotalComponents = 3; const expectedTotalComponents = 3;
// act // act
const wrapper = shallowMount(CircleRating, { const wrapper = mountComponent({
propsData: { rating: expectedTotalComponents,
rating: expectedTotalComponents,
},
}); });
// assert // assert
@@ -87,3 +72,13 @@ describe('CircleRating.vue', () => {
}); });
}); });
}); });
function mountComponent(options: {
readonly rating: number,
}) {
return shallowMount(CircleRating, {
props: {
rating: options.rating,
},
});
}

View File

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

View File

@@ -1,23 +1,25 @@
import { it, describe, expect } from 'vitest'; import { it, describe, expect } from 'vitest';
import { import {
type Ref, ref, defineComponent, nextTick, type Ref, ref, nextTick,
} from 'vue'; } from 'vue';
import { shallowMount } from '@vue/test-utils';
import { type CursorStyleDomModifier, useGlobalCursor } from '@/presentation/components/Scripts/Slider/UseGlobalCursor'; 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', () => { describe('useGlobalCursor', () => {
it('adds cursor style to head on activation', async () => { it('adds cursor style to head on activation', async () => {
// arrange // arrange
const expectedCursorCssStyleValue = 'pointer'; const expectedCursorCssStyleValue = 'pointer';
const isActive = ref(false); const isActive = ref(false);
const domModifier = new CursorStyleDomModifierStub();
// act // act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive }); createHookWithStubs({ isActive, domModifier });
isActive.value = true; isActive.value = true;
await nextTick(); await nextTick();
// assert // assert
const { elementsAppendedToHead: appendedElements } = cursorStyleDomModifierMock; const { elementsAppendedToHead: appendedElements } = domModifier;
expect(appendedElements.length).to.equal(1); expect(appendedElements.length).to.equal(1);
expect(appendedElements[0].innerHTML).toContain(expectedCursorCssStyleValue); expect(appendedElements[0].innerHTML).toContain(expectedCursorCssStyleValue);
}); });
@@ -25,75 +27,61 @@ describe('useGlobalCursor', () => {
it('removes cursor style from head on deactivation', async () => { it('removes cursor style from head on deactivation', async () => {
// arrange // arrange
const isActive = ref(true); const isActive = ref(true);
const domModifier = new CursorStyleDomModifierStub();
// act // act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive }); createHookWithStubs({ isActive, domModifier });
await nextTick(); await nextTick();
isActive.value = false; isActive.value = false;
await nextTick(); await nextTick();
// assert // assert
expect(cursorStyleDomModifierMock.elementsRemovedFromHead.length).to.equal(1); expect(domModifier.elementsRemovedFromHead.length).to.equal(1);
}); });
it('cleans up cursor style on unmount', async () => { it('cleans up cursor style on unmount', async () => {
// arrange // arrange
const isActive = ref(true); const isActive = ref(true);
const domModifier = new CursorStyleDomModifierStub();
const onTeardown = new LifecycleHookStub();
// act // act
const { wrapper, returnObject } = mountWrapperComponent({ isActive }); createHookWithStubs({ isActive, domModifier, onTeardown: onTeardown.getHook() });
wrapper.unmount(); onTeardown.executeAllCallbacks();
await nextTick(); await nextTick();
// assert // assert
const { cursorStyleDomModifierMock } = returnObject; expect(onTeardown.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(cursorStyleDomModifierMock.elementsRemovedFromHead.length).to.equal(1); expect(domModifier.elementsRemovedFromHead.length).to.equal(1);
}); });
it('does not append style to head when initially inactive', async () => { it('does not append style to head when initially inactive', async () => {
// arrange // arrange
const isActive = ref(false); const isActive = ref(false);
const domModifier = new CursorStyleDomModifierStub();
// act // act
const { cursorStyleDomModifierMock } = createHookWithStubs({ isActive }); createHookWithStubs({ isActive, domModifier });
await nextTick(); await nextTick();
// assert // 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?: { function createHookWithStubs(options?: {
readonly isActive?: Ref<boolean>; readonly isActive?: Ref<boolean>;
readonly expectedCursorCssStyleValue?: string; readonly expectedCursorCssStyleValue?: string;
readonly domModifier?: CursorStyleDomModifier;
readonly onTeardown?: LifecycleHook;
}) { }) {
const cursorStyleDomModifierMock = new CursorStyleDomModifierStub();
const hookResult = useGlobalCursor( const hookResult = useGlobalCursor(
options?.isActive ?? ref(true), options?.isActive ?? ref(true),
options?.expectedCursorCssStyleValue ?? 'pointer', options?.expectedCursorCssStyleValue ?? 'pointer',
cursorStyleDomModifierMock, options?.domModifier ?? new CursorStyleDomModifierStub(),
options?.onTeardown ?? new LifecycleHookStub().getHook(),
); );
return { return {
cursorStyleDomModifierMock,
hookResult, hookResult,
}; };
} }

View File

@@ -24,7 +24,7 @@ describe('useNodeStateChangeAggregator', () => {
// arrange // arrange
const expectedTreeRootRef = shallowRef(new TreeRootStub()); const expectedTreeRootRef = shallowRef(new TreeRootStub());
const currentTreeNodesStub = new UseCurrentTreeNodesStub(); const currentTreeNodesStub = new UseCurrentTreeNodesStub();
const builder = new UseNodeStateChangeAggregatorBuilder() const builder = new TestContext()
.withCurrentTreeNodes(currentTreeNodesStub.get()) .withCurrentTreeNodes(currentTreeNodesStub.get())
.withTreeRootRef(expectedTreeRootRef); .withTreeRootRef(expectedTreeRootRef);
// act // act
@@ -61,7 +61,7 @@ describe('useNodeStateChangeAggregator', () => {
// arrange // arrange
const nodesStub = new UseCurrentTreeNodesStub() const nodesStub = new UseCurrentTreeNodesStub()
.withQueryableNodes(createFlatCollection(expectedNodes)); .withQueryableNodes(createFlatCollection(expectedNodes));
const { returnObject } = new UseNodeStateChangeAggregatorBuilder() const { returnObject } = new TestContext()
.withCurrentTreeNodes(nodesStub.get()) .withCurrentTreeNodes(nodesStub.get())
.mountWrapperComponent(); .mountWrapperComponent();
const { callback, calledArgs } = createSpyingCallback(); const { callback, calledArgs } = createSpyingCallback();
@@ -81,7 +81,7 @@ describe('useNodeStateChangeAggregator', () => {
it(description, async () => { it(description, async () => {
// arrange // arrange
const nodesStub = new UseCurrentTreeNodesStub(); const nodesStub = new UseCurrentTreeNodesStub();
const { returnObject } = new UseNodeStateChangeAggregatorBuilder() const { returnObject } = new TestContext()
.withCurrentTreeNodes(nodesStub.get()) .withCurrentTreeNodes(nodesStub.get())
.mountWrapperComponent(); .mountWrapperComponent();
const { callback, calledArgs } = createSpyingCallback(); const { callback, calledArgs } = createSpyingCallback();
@@ -104,7 +104,7 @@ describe('useNodeStateChangeAggregator', () => {
// arrange // arrange
const nodesStub = new UseCurrentTreeNodesStub() const nodesStub = new UseCurrentTreeNodesStub()
.withQueryableNodes(createFlatCollection(expectedNodes)); .withQueryableNodes(createFlatCollection(expectedNodes));
const { returnObject } = new UseNodeStateChangeAggregatorBuilder() const { returnObject } = new TestContext()
.withCurrentTreeNodes(nodesStub.get()) .withCurrentTreeNodes(nodesStub.get())
.mountWrapperComponent(); .mountWrapperComponent();
const { callback, calledArgs } = createSpyingCallback(); const { callback, calledArgs } = createSpyingCallback();
@@ -167,7 +167,7 @@ describe('useNodeStateChangeAggregator', () => {
.withQueryableNodes(createFlatCollection(initialNodes)); .withQueryableNodes(createFlatCollection(initialNodes));
const nodeState = new TreeNodeStateAccessStub(); const nodeState = new TreeNodeStateAccessStub();
changedNode.withState(nodeState); changedNode.withState(nodeState);
const { returnObject } = new UseNodeStateChangeAggregatorBuilder() const { returnObject } = new TestContext()
.withCurrentTreeNodes(nodesStub.get()) .withCurrentTreeNodes(nodesStub.get())
.mountWrapperComponent(); .mountWrapperComponent();
const { callback, calledArgs } = createSpyingCallback(); const { callback, calledArgs } = createSpyingCallback();
@@ -216,7 +216,7 @@ describe('useNodeStateChangeAggregator', () => {
const nodesStub = new UseCurrentTreeNodesStub() const nodesStub = new UseCurrentTreeNodesStub()
.withQueryableNodes(createFlatCollection(initialNodes)); .withQueryableNodes(createFlatCollection(initialNodes));
const eventsStub = new UseAutoUnsubscribedEventsStub(); const eventsStub = new UseAutoUnsubscribedEventsStub();
const { returnObject } = new UseNodeStateChangeAggregatorBuilder() const { returnObject } = new TestContext()
.withCurrentTreeNodes(nodesStub.get()) .withCurrentTreeNodes(nodesStub.get())
.withEventsStub(eventsStub) .withEventsStub(eventsStub)
.mountWrapperComponent(); .mountWrapperComponent();
@@ -290,7 +290,7 @@ function createFlatCollection(nodes: readonly TreeNode[]): QueryableNodesStub {
return new QueryableNodesStub().withFlattenedNodes(nodes); return new QueryableNodesStub().withFlattenedNodes(nodes);
} }
class UseNodeStateChangeAggregatorBuilder { class TestContext {
private treeRootRef: Readonly<Ref<TreeRoot>> = shallowRef(new TreeRootStub()); private treeRootRef: Readonly<Ref<TreeRoot>> = shallowRef(new TreeRootStub());
private currentTreeNodes: typeof useCurrentTreeNodes = new UseCurrentTreeNodesStub().get(); private currentTreeNodes: typeof useCurrentTreeNodes = new UseCurrentTreeNodesStub().get();

View File

@@ -1,9 +1,9 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick, shallowRef } from 'vue'; import { nextTick, shallowRef } from 'vue';
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener'; import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync'; import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
import type { LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
import { LifecycleHookStub } from '@tests/unit/shared/Stubs/LifecycleHookStub';
describe('UseAutoUnsubscribedEventListener', () => { describe('UseAutoUnsubscribedEventListener', () => {
describe('startListening', () => { describe('startListening', () => {
@@ -17,9 +17,10 @@ describe('UseAutoUnsubscribedEventListener', () => {
const callback = (event: Event) => { const callback = (event: Event) => {
actualEvent = event; actualEvent = event;
}; };
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
returnObject.startListening(eventTarget, eventType, callback); startListening(eventTarget, eventType, callback);
eventTarget.dispatchEvent(expectedEvent); eventTarget.dispatchEvent(expectedEvent);
// assert // assert
expect(actualEvent).to.equal(expectedEvent); expect(actualEvent).to.equal(expectedEvent);
@@ -33,13 +34,16 @@ describe('UseAutoUnsubscribedEventListener', () => {
}; };
const eventTarget = new EventTarget(); const eventTarget = new EventTarget();
const eventType: keyof HTMLElementEventMap = 'abort'; const eventType: keyof HTMLElementEventMap = 'abort';
const teardownHook = new LifecycleHookStub();
const context = new TestContext()
.withOnTeardown(teardownHook.getHook());
// act // act
const { wrapper } = mountWrapper({ const { startListening } = context.use();
setup: (listener) => listener.startListening(eventTarget, eventType, callback), startListening(eventTarget, eventType, callback);
}); teardownHook.executeAllCallbacks();
wrapper.unmount();
eventTarget.dispatchEvent(new CustomEvent(eventType)); eventTarget.dispatchEvent(new CustomEvent(eventType));
// assert // assert
expect(teardownHook.totalRegisteredCallbacks).to.greaterThan(0);
expect(isCallbackCalled).to.equal(expectedCallbackCall); expect(isCallbackCalled).to.equal(expectedCallbackCall);
}); });
}); });
@@ -54,9 +58,10 @@ describe('UseAutoUnsubscribedEventListener', () => {
const callback = (event: Event) => { const callback = (event: Event) => {
actualEvent = event; actualEvent = event;
}; };
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
returnObject.startListening(eventTargetRef, eventType, callback); startListening(eventTargetRef, eventType, callback);
eventTarget.dispatchEvent(expectedEvent); eventTarget.dispatchEvent(expectedEvent);
// assert // assert
expect(actualEvent).to.equal(expectedEvent); expect(actualEvent).to.equal(expectedEvent);
@@ -72,9 +77,10 @@ describe('UseAutoUnsubscribedEventListener', () => {
const callback = (event: Event) => { const callback = (event: Event) => {
actualEvent = event; actualEvent = event;
}; };
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
returnObject.startListening(targetRef, eventType, callback); startListening(targetRef, eventType, callback);
targetRef.value = newValue; targetRef.value = newValue;
await nextTick(); await nextTick();
newValue.dispatchEvent(expectedEvent); newValue.dispatchEvent(expectedEvent);
@@ -84,10 +90,11 @@ describe('UseAutoUnsubscribedEventListener', () => {
it('does not throw if initial element is undefined', () => { it('does not throw if initial element is undefined', () => {
// arrange // arrange
const targetRef = shallowRef(undefined); const targetRef = shallowRef(undefined);
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
const act = () => { const act = () => {
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ }); startListening(targetRef, 'abort', () => { /* NO OP */ });
}; };
// assert // assert
expect(act).to.not.throw(); expect(act).to.not.throw();
@@ -95,9 +102,10 @@ describe('UseAutoUnsubscribedEventListener', () => {
it('does not throw when reference becomes undefined', async () => { it('does not throw when reference becomes undefined', async () => {
// arrange // arrange
const targetRef = shallowRef<EventTarget | undefined>(new EventTarget()); const targetRef = shallowRef<EventTarget | undefined>(new EventTarget());
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ }); startListening(targetRef, 'abort', () => { /* NO OP */ });
const act = async () => { const act = async () => {
targetRef.value = undefined; targetRef.value = undefined;
await nextTick(); await nextTick();
@@ -117,9 +125,10 @@ describe('UseAutoUnsubscribedEventListener', () => {
const targetRef = shallowRef(oldValue); const targetRef = shallowRef(oldValue);
const eventType: keyof HTMLElementEventMap = 'abort'; const eventType: keyof HTMLElementEventMap = 'abort';
const expectedEvent = new CustomEvent(eventType); const expectedEvent = new CustomEvent(eventType);
const context = new TestContext();
// act // act
const { returnObject } = mountWrapper(); const { startListening } = context.use();
returnObject.startListening(targetRef, eventType, callback); startListening(targetRef, eventType, callback);
targetRef.value = newValue; targetRef.value = newValue;
await nextTick(); await nextTick();
oldValue.dispatchEvent(expectedEvent); oldValue.dispatchEvent(expectedEvent);
@@ -136,11 +145,13 @@ describe('UseAutoUnsubscribedEventListener', () => {
const target = new EventTarget(); const target = new EventTarget();
const targetRef = shallowRef(target); const targetRef = shallowRef(target);
const eventType: keyof HTMLElementEventMap = 'abort'; const eventType: keyof HTMLElementEventMap = 'abort';
const teardownHook = new LifecycleHookStub();
const context = new TestContext()
.withOnTeardown(teardownHook.getHook());
// act // act
const { wrapper } = mountWrapper({ const { startListening } = context.use();
setup: (listener) => listener.startListening(targetRef, eventType, callback), startListening(targetRef, eventType, callback);
}); teardownHook.executeAllCallbacks();
wrapper.unmount();
target.dispatchEvent(new CustomEvent(eventType)); target.dispatchEvent(new CustomEvent(eventType));
// assert // assert
expect(isCallbackCalled).to.equal(expectedCallbackCall); expect(isCallbackCalled).to.equal(expectedCallbackCall);
@@ -149,24 +160,18 @@ describe('UseAutoUnsubscribedEventListener', () => {
}); });
}); });
function mountWrapper(options?: { class TestContext {
readonly constructorArgs?: Parameters<typeof useAutoUnsubscribedEventListener>, private onTeardown: LifecycleHook = new LifecycleHookStub()
/** Running inside `setup` allows simulating lifecycle events like unmounting. */ .getHook();
readonly setup?: (returnObject: ReturnType<typeof useAutoUnsubscribedEventListener>) => void,
}) { public withOnTeardown(onTeardown: LifecycleHook): this {
let returnObject: ReturnType<typeof useAutoUnsubscribedEventListener> | undefined; this.onTeardown = onTeardown;
const wrapper = shallowMount({ return this;
setup() { }
returnObject = useAutoUnsubscribedEventListener(...(options?.constructorArgs ?? []));
if (options?.setup) { public use(): ReturnType<typeof useAutoUnsubscribedEventListener> {
options.setup(returnObject); return useAutoUnsubscribedEventListener(
} this.onTeardown,
}, );
template: '<div></div>', }
});
expectExists(returnObject);
return {
wrapper,
returnObject,
};
} }

View File

@@ -1,43 +1,38 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents'; import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
import { EventSubscriptionCollectionStub } from '@tests/unit/shared/Stubs/EventSubscriptionCollectionStub'; import { EventSubscriptionCollectionStub } from '@tests/unit/shared/Stubs/EventSubscriptionCollectionStub';
import { EventSubscriptionStub } from '@tests/unit/shared/Stubs/EventSubscriptionStub'; import { EventSubscriptionStub } from '@tests/unit/shared/Stubs/EventSubscriptionStub';
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection'; import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
import type { FunctionKeys } from '@/TypeHelpers'; import type { FunctionKeys } from '@/TypeHelpers';
import type { LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
import { LifecycleHookStub } from '@tests/unit/shared/Stubs/LifecycleHookStub';
import type { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
describe('UseAutoUnsubscribedEvents', () => { describe('UseAutoUnsubscribedEvents', () => {
describe('event collection handling', () => { describe('event collection handling', () => {
it('returns the provided event collection when initialized', () => { it('returns the provided event collection when initialized', () => {
// arrange // arrange
const expectedEvents = new EventSubscriptionCollectionStub(); const expectedEvents = new EventSubscriptionCollectionStub();
const context = new TestContext()
.withEvents(expectedEvents);
// act // act
const { events: actualEvents } = useAutoUnsubscribedEvents(expectedEvents); const { events: actualEvents } = context.use();
// assert // assert
expect(actualEvents).to.equal(expectedEvents); expect(actualEvents).to.equal(expectedEvents);
}); });
it('uses a default event collection when none is provided during initialization', () => {
// arrange
const expectedType = EventSubscriptionCollection;
// act
const { events: actualEvents } = useAutoUnsubscribedEvents();
// assert
expect(actualEvents).to.be.instanceOf(expectedType);
});
it('throws error when there are existing subscriptions', () => { it('throws error when there are existing subscriptions', () => {
// arrange // arrange
const expectedError = 'there are existing subscriptions, this may lead to side-effects'; const expectedError = 'there are existing subscriptions, this may lead to side-effects';
const events = new EventSubscriptionCollectionStub(); const events = new EventSubscriptionCollectionStub();
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]); events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]);
const context = new TestContext()
.withEvents(events);
// act // act
const act = () => useAutoUnsubscribedEvents(events); const act = () => context.use();
// assert // assert
expect(act).to.throw(expectedError); expect(act).to.throw(expectedError);
@@ -48,21 +43,44 @@ describe('UseAutoUnsubscribedEvents', () => {
// arrange // arrange
const events = new EventSubscriptionCollectionStub(); const events = new EventSubscriptionCollectionStub();
const expectedCall: FunctionKeys<EventSubscriptionCollection> = 'unsubscribeAll'; const expectedCall: FunctionKeys<EventSubscriptionCollection> = 'unsubscribeAll';
const stubComponent = shallowMount({ const onTeardown = new LifecycleHookStub();
setup() { const context = new TestContext()
useAutoUnsubscribedEvents(events); .withEvents(events)
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]); .withOnTeardown(onTeardown.getHook());
},
template: '<div></div>',
});
events.callHistory.length = 0;
// act // act
stubComponent.unmount(); context.use();
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]);
events.callHistory.length = 0;
onTeardown.executeAllCallbacks();
// assert // assert
expect(onTeardown.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(events.callHistory).to.have.lengthOf(1); expect(events.callHistory).to.have.lengthOf(1);
expect(events.callHistory[0].methodName).to.equal(expectedCall); expect(events.callHistory[0].methodName).to.equal(expectedCall);
}); });
}); });
}); });
class TestContext {
private onTeardown: LifecycleHook = new LifecycleHookStub().getHook();
private events: IEventSubscriptionCollection = new EventSubscriptionCollectionStub();
public withOnTeardown(onTeardown: LifecycleHook): this {
this.onTeardown = onTeardown;
return this;
}
public withEvents(events: IEventSubscriptionCollection): this {
this.events = events;
return this;
}
public use(): ReturnType<typeof useAutoUnsubscribedEvents> {
return useAutoUnsubscribedEvents(
this.events,
this.onTeardown,
);
}
}

View File

@@ -4,7 +4,7 @@ import {
import { ref } from 'vue'; import { ref } from 'vue';
import type { IconName } from '@/presentation/components/Shared/Icon/IconName'; import type { IconName } from '@/presentation/components/Shared/Icon/IconName';
import { type FileLoaders, clearIconCache, useSvgLoader } from '@/presentation/components/Shared/Icon/UseSvgLoader'; import { type FileLoaders, clearIconCache, useSvgLoader } from '@/presentation/components/Shared/Icon/UseSvgLoader';
import { waitForValueChange } from '@tests/shared/WaitForValueChange'; import { waitForValueChange } from '@tests/shared/Vue/WaitForValueChange';
describe('useSvgLoader', () => { describe('useSvgLoader', () => {
beforeEach(() => { beforeEach(() => {

View File

@@ -1,8 +1,8 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils'; import { ref, nextTick } from 'vue';
import { ref, nextTick, defineComponent } from 'vue';
import { useLockBodyBackgroundScroll } from '@/presentation/components/Shared/Modal/Hooks/ScrollLock/UseLockBodyBackgroundScroll'; import { useLockBodyBackgroundScroll } from '@/presentation/components/Shared/Modal/Hooks/ScrollLock/UseLockBodyBackgroundScroll';
import type { ScrollDomStateAccessor } from '@/presentation/components/Shared/Modal/Hooks/ScrollLock/ScrollDomStateAccessor'; import type { ScrollDomStateAccessor } from '@/presentation/components/Shared/Modal/Hooks/ScrollLock/ScrollDomStateAccessor';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';
import { DomStateChangeTestScenarios } from './DomStateChangeTestScenarios'; import { DomStateChangeTestScenarios } from './DomStateChangeTestScenarios';
describe('useLockBodyBackgroundScroll', () => { describe('useLockBodyBackgroundScroll', () => {
@@ -13,7 +13,7 @@ describe('useLockBodyBackgroundScroll', () => {
const isInitiallyActive = true; const isInitiallyActive = true;
// act // act
createComponent(isInitiallyActive, dom); mountWrapperComponent(isInitiallyActive, dom);
await nextTick(); await nextTick();
}); });
}); });
@@ -22,7 +22,7 @@ describe('useLockBodyBackgroundScroll', () => {
const isInitiallyActive = false; const isInitiallyActive = false;
// act // act
const { initialDomState, actualDomState } = createComponent(isInitiallyActive); const { initialDomState, actualDomState } = mountWrapperComponent(isInitiallyActive);
await nextTick(); await nextTick();
// assert // assert
@@ -34,7 +34,7 @@ describe('useLockBodyBackgroundScroll', () => {
itEachScrollBlockEffect(async (dom) => { itEachScrollBlockEffect(async (dom) => {
// arrange // arrange
const isInitiallyActive = false; const isInitiallyActive = false;
const { isActive } = createComponent(isInitiallyActive, dom); const { isActive } = mountWrapperComponent(isInitiallyActive, dom);
// act // act
isActive.value = true; isActive.value = true;
@@ -44,7 +44,9 @@ describe('useLockBodyBackgroundScroll', () => {
it('reverts to initial styles when deactivated', async () => { it('reverts to initial styles when deactivated', async () => {
// arrange // arrange
const isInitiallyActive = true; const isInitiallyActive = true;
const { isActive, initialDomState, actualDomState } = createComponent(isInitiallyActive); const {
isActive, initialDomState, actualDomState,
} = mountWrapperComponent(isInitiallyActive);
// act // act
isActive.value = false; isActive.value = false;
@@ -57,7 +59,9 @@ describe('useLockBodyBackgroundScroll', () => {
it('restores original styles on unmount', async () => { it('restores original styles on unmount', async () => {
// arrange // arrange
const isInitiallyActive = true; const isInitiallyActive = true;
const { component, initialDomState, actualDomState } = createComponent(isInitiallyActive); const {
component, initialDomState, actualDomState,
} = mountWrapperComponent(isInitiallyActive);
// act // act
component.unmount(); component.unmount();
@@ -68,19 +72,19 @@ describe('useLockBodyBackgroundScroll', () => {
}); });
}); });
function createComponent( function mountWrapperComponent(
initialIsActiveValue: boolean, initialIsActiveValue: boolean,
dom?: ScrollDomStateAccessor, dom?: ScrollDomStateAccessor,
) { ) {
const actualDomState = dom ?? createMockDomStateAccessor(); const actualDomState = dom ?? createMockDomStateAccessor();
const initialDomState = { ...actualDomState }; const initialDomState = { ...actualDomState };
const isActive = ref(initialIsActiveValue); const isActive = ref(initialIsActiveValue);
const component = shallowMount(defineComponent({ const component = executeInComponentSetupContext({
setup() { setupCallback: () => {
useLockBodyBackgroundScroll(isActive, actualDomState); useLockBodyBackgroundScroll(isActive, actualDomState);
}, },
template: '<div></div>', disableAutoUnmount: true,
})); });
return { return {
component, isActive, initialDomState, actualDomState, component, isActive, initialDomState, actualDomState,
}; };

View File

@@ -182,7 +182,7 @@ function mountComponent(options: {
}, },
[COMPONENT_MODAL_CONTENT_NAME]: { [COMPONENT_MODAL_CONTENT_NAME]: {
name: COMPONENT_MODAL_CONTENT_NAME, name: COMPONENT_MODAL_CONTENT_NAME,
template: '<slot />', template: '<div><slot /></div>',
}, },
}, },
}, },

View File

@@ -1,9 +1,10 @@
import { shallowRef } from 'vue'; import { shallowRef } from 'vue';
import { useResizeObserver, type LifecycleHookRegistration, type ObservedElementReference } from '@/presentation/components/Shared/Hooks/Resize/UseResizeObserver'; import { useResizeObserver, type ObservedElementReference } from '@/presentation/components/Shared/Hooks/Resize/UseResizeObserver';
import { flushPromiseResolutionQueue } from '@tests/unit/shared/PromiseInspection'; import { flushPromiseResolutionQueue } from '@tests/unit/shared/PromiseInspection';
import type { AnimationFrameLimiter } from '@/presentation/components/Shared/Hooks/Resize/UseAnimationFrameLimiter'; import type { AnimationFrameLimiter } from '@/presentation/components/Shared/Hooks/Resize/UseAnimationFrameLimiter';
import { ThrottleStub } from '@tests/unit/shared/Stubs/ThrottleStub'; import { ThrottleStub } from '@tests/unit/shared/Stubs/ThrottleStub';
import { expectExists } from '@tests/shared/Assertions/ExpectExists'; import type { LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
import { LifecycleHookStub } from '@tests/unit/shared/Stubs/LifecycleHookStub';
describe('UseResizeObserver', () => { describe('UseResizeObserver', () => {
it('registers observer once mounted', async () => { it('registers observer once mounted', async () => {
@@ -30,18 +31,16 @@ describe('UseResizeObserver', () => {
resizeObserverStub.disconnect = () => { resizeObserverStub.disconnect = () => {
isObserverDisconnected = true; isObserverDisconnected = true;
}; };
let teardownCallback: (() => void) | undefined; const teardownHook = new LifecycleHookStub();
// act // act
new TestContext() new TestContext()
.withResizeObserver(resizeObserverStub) .withResizeObserver(resizeObserverStub)
.withOnTeardown((callback) => { .withOnTeardown(teardownHook.getHook())
teardownCallback = callback;
})
.useResizeObserver(); .useResizeObserver();
await flushPromiseResolutionQueue(); await flushPromiseResolutionQueue();
expectExists(teardownCallback); teardownHook.executeAllCallbacks();
teardownCallback();
// assert // assert
expect(teardownHook.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(isObserverDisconnected).to.equal(true); expect(isObserverDisconnected).to.equal(true);
}); });
}); });
@@ -66,9 +65,12 @@ class TestContext {
private observedElementRef: ObservedElementReference = shallowRef(document.createElement('div')); private observedElementRef: ObservedElementReference = shallowRef(document.createElement('div'));
private onSetup: LifecycleHookRegistration = (callback) => { callback(); }; private onSetup: LifecycleHook = new LifecycleHookStub()
.withInvokeCallbackImmediately(true)
.getHook();
private onTeardown: LifecycleHookRegistration = () => { }; private onTeardown: LifecycleHook = new LifecycleHookStub()
.getHook();
public withResizeObserver(resizeObserver: ResizeObserver): this { public withResizeObserver(resizeObserver: ResizeObserver): this {
this.resizeObserver = resizeObserver; this.resizeObserver = resizeObserver;
@@ -80,12 +82,12 @@ class TestContext {
return this; return this;
} }
public withOnSetup(onSetup: LifecycleHookRegistration): this { public withOnSetup(onSetup: LifecycleHook): this {
this.onSetup = onSetup; this.onSetup = onSetup;
return this; return this;
} }
public withOnTeardown(onTeardown: LifecycleHookRegistration): this { public withOnTeardown(onTeardown: LifecycleHook): this {
this.onTeardown = onTeardown; this.onTeardown = onTeardown;
return this; return this;
} }

View File

@@ -0,0 +1,31 @@
import type { LifecycleHookCallback, LifecycleHook } from '@/presentation/components/Shared/Hooks/Common/LifecycleHook';
export class LifecycleHookStub {
private registeredCallbacks = new Array<LifecycleHookCallback>();
private invokeCallbackImmediately = false;
public withInvokeCallbackImmediately(callImmediatelyOnRegistration: boolean): this {
this.invokeCallbackImmediately = callImmediatelyOnRegistration;
return this;
}
public get totalRegisteredCallbacks(): number {
return this.registeredCallbacks.length;
}
public executeAllCallbacks() {
for (const callback of this.registeredCallbacks) {
callback();
}
}
public getHook(): LifecycleHook {
return (callback: LifecycleHookCallback) => {
this.registeredCallbacks.push(callback);
if (this.invokeCallbackImmediately) {
callback();
}
};
}
}

View File

@@ -9,6 +9,10 @@ export class VueDependencyInjectionApiStub implements VueDependencyInjectionApi
} }
public inject<T>(key: InjectionKey<T>): T { public inject<T>(key: InjectionKey<T>): T {
return this.injections.get(key) as T; const providedValue = this.injections.get(key);
if (providedValue === undefined) {
throw new Error(`[VueDependencyInjectionApiStub] No value provided for key: ${String(key)}`);
}
return providedValue as T;
} }
} }