Fix memory leaks via auto-unsubscribing and DI
This commit simplifies event handling, providing a unified and robust
way to handle event lifecycling. This way, it fixes events not being
unsubscribed when state is changed.
Introduce a new function in `EventSubscriptionCollection` to remove
existing events and adding new events. This provides an easier to use
API, which leads to code that's easier to understand. It also prevents
potential bugs that may occur due to forgetting to call both functions.
It fixes `TheScriptsMenu` not unregistering events on state change.
Other improvements include:
- Include a getter to get total amount of registered subcriptions.
This helps in unit testing.
- Have nullish checks to prevent potential errors further down the
execution.
- Use array instead of rest parameters to increase readability and
simplify tests.
Ensure `SliderHandler` stops resizes on unmount, unsubscribing from all
events and resetting state to default.
Update `injectionKeys` to do imports as types to avoid circular
dependencies. Simplify importing `injectionKeys` to enable and strict
typings for iterating injection keys.
Add tests covering new behavior.
This commit is contained in:
@@ -1,21 +1,172 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
|
||||
import { EventSubscriptionStub } from '@tests/unit/shared/Stubs/EventSubscriptionStub';
|
||||
import { itEachAbsentCollectionValue, itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
|
||||
|
||||
describe('EventSubscriptionCollection', () => {
|
||||
it('unsubscribeAll unsubscribes from all registered subscriptions', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const expected = ['unsubscribed1', 'unsubscribed2'];
|
||||
const actual = new Array<string>();
|
||||
const subscriptions: IEventSubscription[] = [
|
||||
{ unsubscribe: () => actual.push(expected[0]) },
|
||||
{ unsubscribe: () => actual.push(expected[1]) },
|
||||
];
|
||||
// act
|
||||
sut.register(...subscriptions);
|
||||
sut.unsubscribeAll();
|
||||
// assert
|
||||
expect(actual).to.deep.equal(expected);
|
||||
describe('register', () => {
|
||||
it('increments `subscriptionCount` for each registration', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const subscriptions = createSubscriptionStubList(2);
|
||||
|
||||
// act
|
||||
sut.register(subscriptions);
|
||||
|
||||
// assert
|
||||
expect(sut.subscriptionCount).to.equal(2);
|
||||
});
|
||||
it('retains the subscribed state of registrations', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const subscriptions = createSubscriptionStubList(2);
|
||||
|
||||
// act
|
||||
sut.register(subscriptions);
|
||||
|
||||
// assert
|
||||
expectAllSubscribed(subscriptions);
|
||||
});
|
||||
describe('validation', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
// act
|
||||
const act = (
|
||||
subscriptions: IEventSubscription[],
|
||||
) => sut.register(subscriptions);
|
||||
/// assert
|
||||
describeSubscriptionValidations(act);
|
||||
});
|
||||
});
|
||||
describe('unsubscribeAll', () => {
|
||||
it('unsubscribes all registrations', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const subscriptions = createSubscriptionStubList(2);
|
||||
|
||||
// act
|
||||
sut.register(subscriptions);
|
||||
sut.unsubscribeAll();
|
||||
|
||||
// assert
|
||||
expectAllUnsubscribed(subscriptions);
|
||||
});
|
||||
it('resets `subscriptionCount` to zero', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const subscriptions = createSubscriptionStubList(2);
|
||||
sut.register(subscriptions);
|
||||
|
||||
// act
|
||||
sut.unsubscribeAll();
|
||||
|
||||
// assert
|
||||
expect(sut.subscriptionCount).to.equal(0);
|
||||
});
|
||||
});
|
||||
describe('unsubscribeAllAndRegister', () => {
|
||||
it('unsubscribes all previous registrations', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const oldSubscriptions = createSubscriptionStubList(2);
|
||||
sut.register(oldSubscriptions);
|
||||
const newSubscriptions = createSubscriptionStubList(1);
|
||||
|
||||
// act
|
||||
sut.unsubscribeAllAndRegister(newSubscriptions);
|
||||
|
||||
// assert
|
||||
expectAllUnsubscribed(oldSubscriptions);
|
||||
});
|
||||
it('retains the subscribed state of new registrations', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const oldSubscriptions = createSubscriptionStubList(2);
|
||||
sut.register(oldSubscriptions);
|
||||
const newSubscriptions = createSubscriptionStubList(2);
|
||||
|
||||
// act
|
||||
sut.unsubscribeAllAndRegister(newSubscriptions);
|
||||
|
||||
// assert
|
||||
expectAllSubscribed(newSubscriptions);
|
||||
});
|
||||
it('updates `subscriptionCount` to match new registration count', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
const initialSubscriptionAmount = 1;
|
||||
const expectedSubscriptionAmount = 3;
|
||||
const oldSubscriptions = createSubscriptionStubList(initialSubscriptionAmount);
|
||||
sut.register(oldSubscriptions);
|
||||
const newSubscriptions = createSubscriptionStubList(expectedSubscriptionAmount);
|
||||
|
||||
// act
|
||||
sut.unsubscribeAllAndRegister(newSubscriptions);
|
||||
|
||||
// assert
|
||||
expect(sut.subscriptionCount).to.equal(expectedSubscriptionAmount);
|
||||
});
|
||||
|
||||
describe('validation', () => {
|
||||
// arrange
|
||||
const sut = new EventSubscriptionCollection();
|
||||
// act
|
||||
const act = (
|
||||
subscriptions: IEventSubscription[],
|
||||
) => sut.unsubscribeAllAndRegister(subscriptions);
|
||||
/// assert
|
||||
describeSubscriptionValidations(act);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function expectAllSubscribed(subscriptions: EventSubscriptionStub[]) {
|
||||
expect(subscriptions.every((subscription) => subscription.isSubscribed)).to.equal(true);
|
||||
}
|
||||
|
||||
function expectAllUnsubscribed(subscriptions: EventSubscriptionStub[]) {
|
||||
expect(subscriptions.every((subscription) => subscription.isUnsubscribed)).to.equal(true);
|
||||
}
|
||||
|
||||
function createSubscriptionStubList(amount: number): EventSubscriptionStub[] {
|
||||
if (amount <= 0) {
|
||||
throw new Error(`unexpected amount of subscriptions: ${amount}`);
|
||||
}
|
||||
return Array.from({ length: amount }, () => new EventSubscriptionStub());
|
||||
}
|
||||
|
||||
function describeSubscriptionValidations(
|
||||
handleValue: (subscriptions: IEventSubscription[]) => void,
|
||||
) {
|
||||
describe('throws error if no subscriptions are provided', () => {
|
||||
itEachAbsentCollectionValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing subscriptions';
|
||||
|
||||
// act
|
||||
const act = () => handleValue(absentValue);
|
||||
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('throws error if nullish subscriptions are provided', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing subscription in list';
|
||||
const subscriptions = [
|
||||
new EventSubscriptionStub(),
|
||||
absentValue,
|
||||
new EventSubscriptionStub(),
|
||||
];
|
||||
|
||||
// act
|
||||
const act = () => handleValue(subscriptions);
|
||||
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe } from 'vitest';
|
||||
import { VueDependencyInjectionApiStub } from '@tests/unit/shared/Stubs/VueDependencyInjectionApiStub';
|
||||
import { InjectionKeys } from '@/presentation/injectionSymbols';
|
||||
import { provideDependencies, VueDependencyInjectionApi } from '@/presentation/bootstrapping/DependencyProvider';
|
||||
import { ApplicationContextStub } from '@tests/unit/shared/Stubs/ApplicationContextStub';
|
||||
import { itIsSingleton } from '@tests/unit/shared/TestCases/SingletonTests';
|
||||
|
||||
describe('DependencyProvider', () => {
|
||||
describe('provideDependencies', () => {
|
||||
const testCases: {
|
||||
readonly [K in keyof typeof InjectionKeys]: (injectionKey: symbol) => void;
|
||||
} = {
|
||||
useCollectionState: createTransientTests(),
|
||||
useApplication: createSingletonTests(),
|
||||
useRuntimeEnvironment: createSingletonTests(),
|
||||
useAutoUnsubscribedEvents: createTransientTests(),
|
||||
};
|
||||
Object.entries(testCases).forEach(([key, runTests]) => {
|
||||
describe(`Key: "${key}"`, () => {
|
||||
runTests(InjectionKeys[key]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function createTransientTests() {
|
||||
return (injectionKey: symbol) => {
|
||||
it('should register a function when transient dependency is resolved', () => {
|
||||
// arrange
|
||||
const api = new VueDependencyInjectionApiStub();
|
||||
// act
|
||||
new ProvideDependenciesBuilder()
|
||||
.withApi(api)
|
||||
.provideDependencies();
|
||||
// expect
|
||||
const registeredObject = api.inject(injectionKey);
|
||||
expect(registeredObject).to.be.instanceOf(Function);
|
||||
});
|
||||
it('should return different instances for transient dependency', () => {
|
||||
// arrange
|
||||
const api = new VueDependencyInjectionApiStub();
|
||||
// act
|
||||
new ProvideDependenciesBuilder()
|
||||
.withApi(api)
|
||||
.provideDependencies();
|
||||
// expect
|
||||
const registeredObject = api.inject(injectionKey);
|
||||
const factory = registeredObject as () => unknown;
|
||||
const firstResult = factory();
|
||||
const secondResult = factory();
|
||||
expect(firstResult).to.not.equal(secondResult);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function createSingletonTests() {
|
||||
return (injectionKey: symbol) => {
|
||||
it('should register an object when singleton dependency is resolved', () => {
|
||||
// arrange
|
||||
const api = new VueDependencyInjectionApiStub();
|
||||
// act
|
||||
new ProvideDependenciesBuilder()
|
||||
.withApi(api)
|
||||
.provideDependencies();
|
||||
// expect
|
||||
const registeredObject = api.inject(injectionKey);
|
||||
expect(registeredObject).to.be.instanceOf(Object);
|
||||
});
|
||||
it('should return the same instance for singleton dependency', () => {
|
||||
itIsSingleton({
|
||||
getter: () => {
|
||||
// arrange
|
||||
const api = new VueDependencyInjectionApiStub();
|
||||
// act
|
||||
new ProvideDependenciesBuilder()
|
||||
.withApi(api)
|
||||
.provideDependencies();
|
||||
// expect
|
||||
const registeredObject = api.inject(injectionKey);
|
||||
return registeredObject;
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
class ProvideDependenciesBuilder {
|
||||
private context = new ApplicationContextStub();
|
||||
|
||||
private api: VueDependencyInjectionApi = new VueDependencyInjectionApiStub();
|
||||
|
||||
public withApi(api: VueDependencyInjectionApi): this {
|
||||
this.api = api;
|
||||
return this;
|
||||
}
|
||||
|
||||
public provideDependencies() {
|
||||
return provideDependencies(this.context, this.api);
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,14 @@ import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue'
|
||||
import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType';
|
||||
import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState';
|
||||
import { UseCollectionStateStub } from '@tests/unit/shared/Stubs/UseCollectionStateStub';
|
||||
import { useApplicationKey, useCollectionStateKey } from '@/presentation/injectionSymbols';
|
||||
import { InjectionKeys } from '@/presentation/injectionSymbols';
|
||||
import { UseApplicationStub } from '@tests/unit/shared/Stubs/UseApplicationStub';
|
||||
import { UserFilterMethod, UserFilterStub } from '@tests/unit/shared/Stubs/UserFilterStub';
|
||||
import { FilterResultStub } from '@tests/unit/shared/Stubs/FilterResultStub';
|
||||
import { FilterChange } from '@/application/Context/State/Filter/Event/FilterChange';
|
||||
import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult';
|
||||
import { IFilterChangeDetails } from '@/application/Context/State/Filter/Event/IFilterChangeDetails';
|
||||
import { UseAutoUnsubscribedEventsStub } from '@tests/unit/shared/Stubs/UseAutoUnsubscribedEventsStub';
|
||||
|
||||
const DOM_SELECTOR_NO_MATCHES = '.search-no-matches';
|
||||
const DOM_SELECTOR_CLOSE_BUTTON = '.search__query__close-button';
|
||||
@@ -404,10 +405,12 @@ function mountComponent(options?: {
|
||||
}) {
|
||||
return shallowMount(TheScriptsView, {
|
||||
provide: {
|
||||
[useCollectionStateKey as symbol]:
|
||||
[InjectionKeys.useCollectionState as symbol]:
|
||||
() => options?.useCollectionState ?? new UseCollectionStateStub().get(),
|
||||
[useApplicationKey as symbol]:
|
||||
[InjectionKeys.useApplication as symbol]:
|
||||
new UseApplicationStub().get(),
|
||||
[InjectionKeys.useAutoUnsubscribedEvents as symbol]:
|
||||
() => new UseAutoUnsubscribedEventsStub().get(),
|
||||
},
|
||||
propsData: {
|
||||
currentView: options?.viewType === undefined ? ViewType.Tree : options.viewType,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
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 { FunctionKeys } from '@/TypeHelpers';
|
||||
|
||||
describe('UseAutoUnsubscribedEvents', () => {
|
||||
describe('event collection handling', () => {
|
||||
it('returns the provided event collection when initialized', () => {
|
||||
// arrange
|
||||
const expectedEvents = new EventSubscriptionCollectionStub();
|
||||
|
||||
// act
|
||||
const { events: actualEvents } = useAutoUnsubscribedEvents(expectedEvents);
|
||||
|
||||
// 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()]);
|
||||
|
||||
// act
|
||||
const act = () => useAutoUnsubscribedEvents(events);
|
||||
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
describe('event unsubscription', () => {
|
||||
it('unsubscribes from all events when the associated component is destroyed', () => {
|
||||
// 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;
|
||||
|
||||
// act
|
||||
stubComponent.destroy();
|
||||
|
||||
// assert
|
||||
expect(events.callHistory).to.have.lengthOf(1);
|
||||
expect(events.callHistory[0].methodName).to.equal(expectedCall);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,30 +6,89 @@ import { IReadOnlyCategoryCollectionState } from '@/application/Context/State/IC
|
||||
import { ApplicationContextChangedEventStub } from '@tests/unit/shared/Stubs/ApplicationContextChangedEventStub';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
||||
import { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
|
||||
import { EventSubscriptionCollectionStub } from '@tests/unit/shared/Stubs/EventSubscriptionCollectionStub';
|
||||
|
||||
describe('UseCollectionState', () => {
|
||||
describe('context is absent', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
describe('parameter validation', () => {
|
||||
describe('absent context', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing context';
|
||||
const contextValue = absentValue;
|
||||
// act
|
||||
const act = () => new UseCollectionStateBuilder()
|
||||
.withContext(contextValue)
|
||||
.build();
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
describe('absent events', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing events';
|
||||
const eventsValue = absentValue;
|
||||
// act
|
||||
const act = () => new UseCollectionStateBuilder()
|
||||
.withEvents(eventsValue)
|
||||
.build();
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('listens to contextChanged event', () => {
|
||||
it('registers new event listener', () => {
|
||||
// arrange
|
||||
const expectedError = 'missing context';
|
||||
const contextValue = absentValue;
|
||||
const events = new EventSubscriptionCollectionStub();
|
||||
const expectedSubscriptionsCount = 1;
|
||||
// act
|
||||
const act = () => useCollectionState(contextValue);
|
||||
new UseCollectionStateBuilder()
|
||||
.withEvents(events)
|
||||
.build();
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
const actualSubscriptionsCount = events.subscriptionCount;
|
||||
expect(actualSubscriptionsCount).to.equal(expectedSubscriptionsCount);
|
||||
});
|
||||
it('does not modify the state after event listener is unsubscribed', () => {
|
||||
// arrange
|
||||
const events = new EventSubscriptionCollectionStub();
|
||||
const oldState = new CategoryCollectionStateStub();
|
||||
const newState = new CategoryCollectionStateStub();
|
||||
const context = new ApplicationContextStub()
|
||||
.withState(oldState);
|
||||
|
||||
// act
|
||||
const { currentState } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.withEvents(events)
|
||||
.build();
|
||||
const stateModifierEvent = events.mostRecentSubscription;
|
||||
stateModifierEvent.unsubscribe();
|
||||
context.dispatchContextChange(
|
||||
new ApplicationContextChangedEventStub().withNewState(newState),
|
||||
);
|
||||
|
||||
// assert
|
||||
expect(currentState.value).to.equal(oldState);
|
||||
});
|
||||
});
|
||||
|
||||
describe('currentContext', () => {
|
||||
it('returns current context', () => {
|
||||
// arrange
|
||||
const expected = new ApplicationContextStub();
|
||||
const expectedContext = new ApplicationContextStub();
|
||||
|
||||
// act
|
||||
const { currentContext } = useCollectionState(expected);
|
||||
const { currentContext } = new UseCollectionStateBuilder()
|
||||
.withContext(expectedContext)
|
||||
.build();
|
||||
|
||||
// assert
|
||||
expect(currentContext).to.equal(expected);
|
||||
expect(currentContext).to.equal(expectedContext);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,24 +100,28 @@ describe('UseCollectionState', () => {
|
||||
.withState(expected);
|
||||
|
||||
// act
|
||||
const { currentState } = useCollectionState(context);
|
||||
const { currentState } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// assert
|
||||
expect(currentState.value).to.equal(expected);
|
||||
});
|
||||
it('returns changed collection state', () => {
|
||||
// arrange
|
||||
const newState = new CategoryCollectionStateStub();
|
||||
const expectedNewState = new CategoryCollectionStateStub();
|
||||
const context = new ApplicationContextStub();
|
||||
const { currentState } = useCollectionState(context);
|
||||
const { currentState } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
context.dispatchContextChange(
|
||||
new ApplicationContextChangedEventStub().withNewState(newState),
|
||||
new ApplicationContextChangedEventStub().withNewState(expectedNewState),
|
||||
);
|
||||
|
||||
// assert
|
||||
expect(currentState.value).to.equal(newState);
|
||||
expect(currentState.value).to.equal(expectedNewState);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,8 +130,7 @@ describe('UseCollectionState', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing state handler';
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder().build();
|
||||
// act
|
||||
const act = () => onStateChange(absentValue);
|
||||
// assert
|
||||
@@ -79,7 +141,9 @@ describe('UseCollectionState', () => {
|
||||
// arrange
|
||||
const expected = true;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
let wasCalled = false;
|
||||
|
||||
// act
|
||||
@@ -94,8 +158,7 @@ describe('UseCollectionState', () => {
|
||||
it('call handler immediately when immediate is true', () => {
|
||||
// arrange
|
||||
const expected = true;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder().build();
|
||||
let wasCalled = false;
|
||||
|
||||
// act
|
||||
@@ -109,8 +172,7 @@ describe('UseCollectionState', () => {
|
||||
it('does not call handler immediately when immediate is false', () => {
|
||||
// arrange
|
||||
const expected = false;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder().build();
|
||||
let wasCalled = false;
|
||||
|
||||
// act
|
||||
@@ -125,7 +187,9 @@ describe('UseCollectionState', () => {
|
||||
// arrange
|
||||
const expected = 5;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
let totalCalled = 0;
|
||||
|
||||
// act
|
||||
@@ -144,7 +208,9 @@ describe('UseCollectionState', () => {
|
||||
const expected = new CategoryCollectionStateStub();
|
||||
let actual: IReadOnlyCategoryCollectionState;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
onStateChange((newState) => {
|
||||
@@ -159,21 +225,57 @@ describe('UseCollectionState', () => {
|
||||
});
|
||||
it('call handler with old state after state changes', () => {
|
||||
// arrange
|
||||
const expected = new CategoryCollectionStateStub();
|
||||
let actual: IReadOnlyCategoryCollectionState;
|
||||
const expectedState = new CategoryCollectionStateStub();
|
||||
let actualState: IReadOnlyCategoryCollectionState;
|
||||
const context = new ApplicationContextStub();
|
||||
const { onStateChange } = useCollectionState(context);
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
onStateChange((_, oldState) => {
|
||||
actual = oldState;
|
||||
actualState = oldState;
|
||||
});
|
||||
context.dispatchContextChange(
|
||||
new ApplicationContextChangedEventStub().withOldState(expected),
|
||||
new ApplicationContextChangedEventStub().withOldState(expectedState),
|
||||
);
|
||||
|
||||
// assert
|
||||
expect(actual).to.equal(expected);
|
||||
expect(actualState).to.equal(expectedState);
|
||||
});
|
||||
describe('listens to contextChanged event', () => {
|
||||
it('registers new event listener', () => {
|
||||
// arrange
|
||||
const events = new EventSubscriptionCollectionStub();
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withEvents(events)
|
||||
.build();
|
||||
const expectedSubscriptionsCount = 1;
|
||||
// act
|
||||
events.unsubscribeAll(); // clean count for event subscriptions before
|
||||
onStateChange(() => { /* NO OP */ });
|
||||
// assert
|
||||
const actualSubscriptionsCount = events.subscriptionCount;
|
||||
expect(actualSubscriptionsCount).to.equal(expectedSubscriptionsCount);
|
||||
});
|
||||
it('onStateChange is not called once event is unsubscribed', () => {
|
||||
// arrange
|
||||
let isCallbackCalled = false;
|
||||
const callback = () => { isCallbackCalled = true; };
|
||||
const context = new ApplicationContextStub();
|
||||
const events = new EventSubscriptionCollectionStub();
|
||||
const { onStateChange } = new UseCollectionStateBuilder()
|
||||
.withEvents(events)
|
||||
.withContext(context)
|
||||
.build();
|
||||
// act
|
||||
onStateChange(callback);
|
||||
const stateChangeEvent = events.mostRecentSubscription;
|
||||
stateChangeEvent.unsubscribe();
|
||||
context.dispatchContextChange();
|
||||
// assert
|
||||
expect(isCallbackCalled).to.equal(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -183,9 +285,13 @@ describe('UseCollectionState', () => {
|
||||
// arrange
|
||||
const expectedError = 'missing state mutator';
|
||||
const context = new ApplicationContextStub();
|
||||
const { modifyCurrentState } = useCollectionState(context);
|
||||
const { modifyCurrentState } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
const act = () => modifyCurrentState(absentValue);
|
||||
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
@@ -198,7 +304,9 @@ describe('UseCollectionState', () => {
|
||||
.withOs(oldOs);
|
||||
const context = new ApplicationContextStub()
|
||||
.withState(state);
|
||||
const { modifyCurrentState } = useCollectionState(context);
|
||||
const { modifyCurrentState } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
modifyCurrentState((mutableState) => {
|
||||
@@ -217,8 +325,7 @@ describe('UseCollectionState', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing context mutator';
|
||||
const context = new ApplicationContextStub();
|
||||
const { modifyCurrentContext } = useCollectionState(context);
|
||||
const { modifyCurrentContext } = new UseCollectionStateBuilder().build();
|
||||
// act
|
||||
const act = () => modifyCurrentContext(absentValue);
|
||||
// assert
|
||||
@@ -233,7 +340,9 @@ describe('UseCollectionState', () => {
|
||||
.withOs(OperatingSystem.macOS);
|
||||
const context = new ApplicationContextStub()
|
||||
.withState(oldState);
|
||||
const { modifyCurrentContext } = useCollectionState(context);
|
||||
const { modifyCurrentContext } = new UseCollectionStateBuilder()
|
||||
.withContext(context)
|
||||
.build();
|
||||
|
||||
// act
|
||||
modifyCurrentContext((mutableContext) => {
|
||||
@@ -247,3 +356,23 @@ describe('UseCollectionState', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class UseCollectionStateBuilder {
|
||||
private context: IApplicationContext = new ApplicationContextStub();
|
||||
|
||||
private events: IEventSubscriptionCollection = new EventSubscriptionCollectionStub();
|
||||
|
||||
public withContext(context: IApplicationContext): this {
|
||||
this.context = context;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withEvents(events: IEventSubscriptionCollection): this {
|
||||
this.events = events;
|
||||
return this;
|
||||
}
|
||||
|
||||
public build(): ReturnType<typeof useCollectionState> {
|
||||
return useCollectionState(this.context, this.events);
|
||||
}
|
||||
}
|
||||
|
||||
24
tests/unit/presentation/injectionSymbols.ts
Normal file
24
tests/unit/presentation/injectionSymbols.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { InjectionKeys } from '@/presentation/injectionSymbols';
|
||||
|
||||
describe('injectionSymbols', () => {
|
||||
Object.entries(InjectionKeys).forEach(([key, symbol]) => {
|
||||
describe(`symbol for ${key}`, () => {
|
||||
it('should be a symbol type', () => {
|
||||
// arrange
|
||||
const expectedType = Symbol;
|
||||
// act
|
||||
// assert
|
||||
expect(symbol).to.be.instanceOf(expectedType);
|
||||
});
|
||||
it(`should have a description matching the key "${key}"`, () => {
|
||||
// arrange
|
||||
const expected = key;
|
||||
// act
|
||||
const actual = symbol.description;
|
||||
// assert
|
||||
expect(expected).to.equal(actual);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,50 @@
|
||||
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
|
||||
import { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class EventSubscriptionCollectionStub implements IEventSubscriptionCollection {
|
||||
export class EventSubscriptionCollectionStub
|
||||
extends StubWithObservableMethodCalls<IEventSubscriptionCollection>
|
||||
implements IEventSubscriptionCollection {
|
||||
private readonly subscriptions = new Array<IEventSubscription>();
|
||||
|
||||
public register(...subscriptions: IEventSubscription[]) {
|
||||
public get mostRecentSubscription(): IEventSubscription | undefined {
|
||||
if (this.subscriptions.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return this.subscriptions[this.subscriptions.length - 1];
|
||||
}
|
||||
|
||||
public get subscriptionCount(): number {
|
||||
return this.subscriptions.length;
|
||||
}
|
||||
|
||||
public register(
|
||||
subscriptions: IEventSubscription[],
|
||||
): void {
|
||||
this.registerMethodCall({
|
||||
methodName: 'register',
|
||||
args: [subscriptions],
|
||||
});
|
||||
this.subscriptions.push(...subscriptions);
|
||||
}
|
||||
|
||||
public unsubscribeAll() {
|
||||
public unsubscribeAll(): void {
|
||||
this.registerMethodCall({
|
||||
methodName: 'unsubscribeAll',
|
||||
args: [],
|
||||
});
|
||||
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
|
||||
this.subscriptions.length = 0;
|
||||
}
|
||||
|
||||
public unsubscribeAllAndRegister(
|
||||
subscriptions: IEventSubscription[],
|
||||
): void {
|
||||
this.registerMethodCall({
|
||||
methodName: 'unsubscribeAllAndRegister',
|
||||
args: [subscriptions],
|
||||
});
|
||||
this.unsubscribeAll();
|
||||
this.register(subscriptions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
|
||||
|
||||
type UnsubscribeCallback = () => void;
|
||||
|
||||
export class EventSubscriptionStub implements IEventSubscription {
|
||||
private currentState = SubscriptionState.Subscribed;
|
||||
|
||||
public get isUnsubscribed(): boolean {
|
||||
return this.currentState === SubscriptionState.Unsubscribed;
|
||||
}
|
||||
|
||||
public get isSubscribed(): boolean {
|
||||
return this.currentState === SubscriptionState.Subscribed;
|
||||
}
|
||||
|
||||
private readonly onUnsubscribe = new Array<UnsubscribeCallback>();
|
||||
|
||||
constructor(unsubscribeCallback?: UnsubscribeCallback) {
|
||||
@@ -15,5 +23,13 @@ export class EventSubscriptionStub implements IEventSubscription {
|
||||
for (const callback of this.onUnsubscribe) {
|
||||
callback();
|
||||
}
|
||||
this.currentState = SubscriptionState.Unsubscribed;
|
||||
}
|
||||
}
|
||||
|
||||
type UnsubscribeCallback = () => void;
|
||||
|
||||
enum SubscriptionState {
|
||||
Subscribed,
|
||||
Unsubscribed,
|
||||
}
|
||||
|
||||
10
tests/unit/shared/Stubs/UseAutoUnsubscribedEventsStub.ts
Normal file
10
tests/unit/shared/Stubs/UseAutoUnsubscribedEventsStub.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
|
||||
import { EventSubscriptionCollectionStub } from './EventSubscriptionCollectionStub';
|
||||
|
||||
export class UseAutoUnsubscribedEventsStub {
|
||||
public get(): ReturnType<typeof useAutoUnsubscribedEvents> {
|
||||
return {
|
||||
events: new EventSubscriptionCollectionStub(),
|
||||
};
|
||||
}
|
||||
}
|
||||
14
tests/unit/shared/Stubs/VueDependencyInjectionApiStub.ts
Normal file
14
tests/unit/shared/Stubs/VueDependencyInjectionApiStub.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { InjectionKey } from 'vue';
|
||||
import { VueDependencyInjectionApi } from '@/presentation/bootstrapping/DependencyProvider';
|
||||
|
||||
export class VueDependencyInjectionApiStub implements VueDependencyInjectionApi {
|
||||
private readonly injections = new Map<unknown, unknown>();
|
||||
|
||||
public provide<T>(key: InjectionKey<T>, value: T): void {
|
||||
this.injections.set(key, value);
|
||||
}
|
||||
|
||||
public inject<T>(key: InjectionKey<T>): T {
|
||||
return this.injections.get(key) as T;
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,18 @@ import { Constructible } from '@/TypeHelpers';
|
||||
|
||||
interface ISingletonTestData<T> {
|
||||
getter: () => T;
|
||||
expectedType: Constructible<T>;
|
||||
expectedType?: Constructible<T>;
|
||||
}
|
||||
|
||||
export function itIsSingleton<T>(test: ISingletonTestData<T>): void {
|
||||
it('gets the expected type', () => {
|
||||
// act
|
||||
const instance = test.getter();
|
||||
// assert
|
||||
expect(instance).to.be.instanceOf(test.expectedType);
|
||||
});
|
||||
if (test.expectedType !== undefined) {
|
||||
it('gets the expected type', () => {
|
||||
// act
|
||||
const instance = test.getter();
|
||||
// assert
|
||||
expect(instance).to.be.instanceOf(test.expectedType);
|
||||
});
|
||||
}
|
||||
it('multiple calls get the same instance', () => {
|
||||
// act
|
||||
const instance1 = test.getter();
|
||||
|
||||
0
tests/unit/shared/TestCases/TransientFacto
Normal file
0
tests/unit/shared/TestCases/TransientFacto
Normal file
Reference in New Issue
Block a user