Skip to content

Commit

Permalink
Ensure tests do not log warning or errors
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
undergroundwires committed Jul 23, 2024
1 parent a650558 commit ae0165f
Show file tree
Hide file tree
Showing 26 changed files with 359 additions and 205 deletions.
4 changes: 3 additions & 1 deletion src/presentation/components/Scripts/Slider/UseDragHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import {
} from 'vue';
import { throttle } from '@/application/Common/Timing/Throttle';
import type { Ref } from 'vue';
import type { LifecycleHook } from '../../Shared/Hooks/Common/LifecycleHook';

const ThrottleInMs = 15;

export function useDragHandler(
draggableElementRef: Readonly<Ref<HTMLElement | undefined>>,
dragDomModifier: DragDomModifier = new GlobalDocumentDragDomModifier(),
throttler = throttle,
onTeardown: LifecycleHook = onUnmounted,
) {
const displacementX = ref(0);
const isDragging = ref(false);
Expand Down Expand Up @@ -52,7 +54,7 @@ export function useDragHandler(
element.addEventListener('pointerdown', startDrag);
}

onUnmounted(() => {
onTeardown(() => {
stopDrag();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { watch, type Ref, onUnmounted } from 'vue';
import type { LifecycleHook } from '../../Shared/Hooks/Common/LifecycleHook';

export function useGlobalCursor(
isActive: Readonly<Ref<boolean>>,
cursorCssValue: string,
documentAccessor: CursorStyleDomModifier = new GlobalDocumentCursorStyleDomModifier(),
onTeardown: LifecycleHook = onUnmounted,
) {
const cursorStyle = createCursorStyle(cursorCssValue, documentAccessor);

Expand All @@ -15,7 +17,7 @@ export function useGlobalCursor(
}
});

onUnmounted(() => {
onTeardown(() => {
documentAccessor.removeElement(cursorStyle);
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import {
import { throttle, type ThrottleFunction } from '@/application/Common/Timing/Throttle';
import { useResizeObserverPolyfill } from './UseResizeObserverPolyfill';
import { useAnimationFrameLimiter } from './UseAnimationFrameLimiter';
import type { LifecycleHook } from '../Common/LifecycleHook';

export function useResizeObserver(
config: ResizeObserverConfig,
usePolyfill = useResizeObserverPolyfill,
useFrameLimiter = useAnimationFrameLimiter,
throttler: ThrottleFunction = throttle,
onSetup: LifecycleHookRegistration = onBeforeMount,
onTeardown: LifecycleHookRegistration = onBeforeUnmount,
onSetup: LifecycleHook = onBeforeMount,
onTeardown: LifecycleHook = onBeforeUnmount,
) {
const { resetNextFrame, cancelNextFrame } = useFrameLimiter();
// This prevents the 'ResizeObserver loop completed with undelivered notifications' error when
Expand Down Expand Up @@ -63,5 +64,3 @@ export interface ResizeObserverConfig {
}

export type ObservedElementReference = Readonly<Ref<HTMLElement | undefined>>;

export type LifecycleHookRegistration = (callback: () => void) => void;
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import {
watch,
type Ref,
} from 'vue';
import type { LifecycleHook } from './Common/LifecycleHook';

export interface UseEventListener {
(): TargetEventListener;
(
onTeardown?: LifecycleHook,
): TargetEventListener;
}

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

onBeforeUnmount(() => {
onTeardown(() => {
eventListenerManager.removeListenerIfExists();
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { onUnmounted } from 'vue';
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
import type { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
import type { LifecycleHook } from './Common/LifecycleHook';

export function useAutoUnsubscribedEvents(
events: IEventSubscriptionCollection = new EventSubscriptionCollection(),
onTeardown: LifecycleHook = onUnmounted,
) {
if (events.subscriptionCount > 0) {
throw new Error('there are existing subscriptions, this may lead to side-effects');
}

onUnmounted(() => {
onTeardown(() => {
events.unsubscribeAll();
});

Expand Down
17 changes: 9 additions & 8 deletions tests/integration/composite/DependencyResolution.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { it, describe, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { defineComponent, inject } from 'vue';
import { inject } from 'vue';
import { type InjectionKeySelector, InjectionKeys, injectKey } from '@/presentation/injectionSymbols';
import { provideDependencies } from '@/presentation/bootstrapping/DependencyProvider';
import { buildContext } from '@/application/Context/ApplicationContextFactory';
import type { IApplicationContext } from '@/application/Context/IApplicationContext';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';

describe('DependencyResolution', () => {
describe('all dependencies can be injected', async () => {
Expand All @@ -16,7 +16,7 @@ describe('DependencyResolution', () => {
// act
const resolvedDependency = resolve(() => key, dependencies);
// assert
expect(resolvedDependency).to.toBeDefined();
expect(resolvedDependency).toBeDefined();
});
});
});
Expand All @@ -40,13 +40,14 @@ function resolve<T>(
providedKeys: ProvidedKeys,
): T | undefined {
let injectedDependency: T | undefined;
shallowMount(defineComponent({
setup() {
executeInComponentSetupContext({
setupCallback: () => {
injectedDependency = injectKey(selector);
},
}), {
global: {
provide: providedKeys,
mountOptions: {
global: {
provide: providedKeys,
},
},
});
return injectedDependency;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
} from 'vitest';
import { IconNames } from '@/presentation/components/Shared/Icon/IconName';
import { useSvgLoader } from '@/presentation/components/Shared/Icon/UseSvgLoader';
import { waitForValueChange } from '@tests/shared/WaitForValueChange';
import { waitForValueChange } from '@tests/shared/Vue/WaitForValueChange';

describe('useSvgLoader', () => {
describe('can load all SVGs', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
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 { expectExists } from '@tests/shared/Assertions/ExpectExists';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';

describe('useKeyboardInteractionState', () => {
describe('isKeyboardBeingUsed', () => {
Expand Down Expand Up @@ -49,12 +48,12 @@ function triggerKeyPress() {

function mountWrapperComponent() {
let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined;
const wrapper = shallowMount(defineComponent({
setup() {
const wrapper = executeInComponentSetupContext({
setupCallback: () => {
returnObject = useKeyboardInteractionState();
},
template: '<div></div>',
}));
disableAutoUnmount: true,
});
expectExists(returnObject);
return {
returnObject,
Expand Down
27 changes: 27 additions & 0 deletions tests/shared/Vue/ExecuteInComponentSetupContext.ts
Original file line number Diff line number Diff line change
@@ -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;
}
File renamed without changes.
23 changes: 23 additions & 0 deletions tests/shared/bootstrap/FailTestOnConsoleError.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
}
2 changes: 2 additions & 0 deletions tests/shared/bootstrap/setup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { afterEach } from 'vitest';
import { enableAutoUnmount } from '@vue/test-utils';
import { polyfillBlob } from './BlobPolyfill';
import { failTestOnConsoleError } from './FailTestOnConsoleError';

enableAutoUnmount(afterEach);
polyfillBlob();
failTestOnConsoleError();
13 changes: 10 additions & 3 deletions tests/unit/presentation/bootstrapping/DependencyProvider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ApplicationContextStub } from '@tests/unit/shared/Stubs/ApplicationCont
import { itIsSingletonFactory } from '@tests/unit/shared/TestCases/SingletonFactoryTests';
import type { IApplicationContext } from '@/application/Context/IApplicationContext';
import { itIsTransientFactory } from '@tests/unit/shared/TestCases/TransientFactoryTests';
import { executeInComponentSetupContext } from '@tests/shared/Vue/ExecuteInComponentSetupContext';

describe('DependencyProvider', () => {
describe('provideDependencies', () => {
Expand Down Expand Up @@ -55,9 +56,14 @@ function createTransientTests() {
.provideDependencies();
// act
const getFactoryResult = () => {
const registeredObject = api.inject(injectionKey);
const factory = registeredObject as () => unknown;
return factory();
const registeredFactory = api.inject(injectionKey) as () => unknown;
let factoryResult: unknown;
executeInComponentSetupContext({
setupCallback: () => {
factoryResult = registeredFactory();
},
});
return factoryResult;
};
// assert
itIsTransientFactory({
Expand Down Expand Up @@ -97,6 +103,7 @@ function createSingletonTests() {
});
};
}

class ProvideDependenciesBuilder {
private context: IApplicationContext = new ApplicationContextStub();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,10 @@ describe('CircleRating.vue', () => {
const currentRating = MAX_RATING - 1;

// act
const wrapper = shallowMount(CircleRating, {
propsData: {
rating: currentRating,
},
const wrapper = mountComponent({
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
const ratingCircles = wrapper.findAllComponents(RatingCircle);
expect(ratingCircles.length).to.equal(expectedMaxRating);
Expand All @@ -42,10 +29,8 @@ describe('CircleRating.vue', () => {
const expectedTotalComponents = 3;

// act
const wrapper = shallowMount(CircleRating, {
propsData: {
rating: expectedTotalComponents,
},
const wrapper = mountComponent({
rating: expectedTotalComponents,
});

// assert
Expand Down Expand Up @@ -87,3 +72,13 @@ describe('CircleRating.vue', () => {
});
});
});

function mountComponent(options: {
readonly rating: number,
}) {
return shallowMount(CircleRating, {
props: {
rating: options.rating,
},
});
}
Loading

0 comments on commit ae0165f

Please sign in to comment.