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

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

View File

@@ -1,43 +1,38 @@
import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
import { EventSubscriptionCollectionStub } from '@tests/unit/shared/Stubs/EventSubscriptionCollectionStub';
import { EventSubscriptionStub } from '@tests/unit/shared/Stubs/EventSubscriptionStub';
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
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('event collection handling', () => {
it('returns the provided event collection when initialized', () => {
// arrange
const expectedEvents = new EventSubscriptionCollectionStub();
const context = new TestContext()
.withEvents(expectedEvents);
// act
const { events: actualEvents } = useAutoUnsubscribedEvents(expectedEvents);
const { events: actualEvents } = context.use();
// assert
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', () => {
// arrange
const expectedError = 'there are existing subscriptions, this may lead to side-effects';
const events = new EventSubscriptionCollectionStub();
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]);
const context = new TestContext()
.withEvents(events);
// act
const act = () => useAutoUnsubscribedEvents(events);
const act = () => context.use();
// assert
expect(act).to.throw(expectedError);
@@ -48,21 +43,44 @@ describe('UseAutoUnsubscribedEvents', () => {
// arrange
const events = new EventSubscriptionCollectionStub();
const expectedCall: FunctionKeys<EventSubscriptionCollection> = 'unsubscribeAll';
const stubComponent = shallowMount({
setup() {
useAutoUnsubscribedEvents(events);
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]);
},
template: '<div></div>',
});
events.callHistory.length = 0;
const onTeardown = new LifecycleHookStub();
const context = new TestContext()
.withEvents(events)
.withOnTeardown(onTeardown.getHook());
// act
stubComponent.unmount();
context.use();
events.register([new EventSubscriptionStub(), new EventSubscriptionStub()]);
events.callHistory.length = 0;
onTeardown.executeAllCallbacks();
// assert
expect(onTeardown.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(events.callHistory).to.have.lengthOf(1);
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 type { IconName } from '@/presentation/components/Shared/Icon/IconName';
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', () => {
beforeEach(() => {

View File

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

View File

@@ -182,7 +182,7 @@ function mountComponent(options: {
},
[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 { 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 type { AnimationFrameLimiter } from '@/presentation/components/Shared/Hooks/Resize/UseAnimationFrameLimiter';
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', () => {
it('registers observer once mounted', async () => {
@@ -30,18 +31,16 @@ describe('UseResizeObserver', () => {
resizeObserverStub.disconnect = () => {
isObserverDisconnected = true;
};
let teardownCallback: (() => void) | undefined;
const teardownHook = new LifecycleHookStub();
// act
new TestContext()
.withResizeObserver(resizeObserverStub)
.withOnTeardown((callback) => {
teardownCallback = callback;
})
.withOnTeardown(teardownHook.getHook())
.useResizeObserver();
await flushPromiseResolutionQueue();
expectExists(teardownCallback);
teardownCallback();
teardownHook.executeAllCallbacks();
// assert
expect(teardownHook.totalRegisteredCallbacks).to.be.greaterThan(0);
expect(isObserverDisconnected).to.equal(true);
});
});
@@ -66,9 +65,12 @@ class TestContext {
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 {
this.resizeObserver = resizeObserver;
@@ -80,12 +82,12 @@ class TestContext {
return this;
}
public withOnSetup(onSetup: LifecycleHookRegistration): this {
public withOnSetup(onSetup: LifecycleHook): this {
this.onSetup = onSetup;
return this;
}
public withOnTeardown(onTeardown: LifecycleHookRegistration): this {
public withOnTeardown(onTeardown: LifecycleHook): this {
this.onTeardown = onTeardown;
return this;
}