From: Patrick Date: Mon, 23 Dec 2019 20:45:06 +0000 (-0300) Subject: test: store.subscribe (#29) X-Git-Tag: 0.0.3~7 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ceb1cd1cac29550411077c932dd4ac0e5811ddfa;p=thirdparty%2Fvuejs%2Fpinia.git test: store.subscribe (#29) * added subscription tests and unsubscribe function * added condition to unsubscribe only if listener exists * added test to multiple unsubscriptions * using spies to watch subscriptions being called --- diff --git a/__tests__/subscriptions.spec.ts b/__tests__/subscriptions.spec.ts new file mode 100644 index 00000000..4dbbb9aa --- /dev/null +++ b/__tests__/subscriptions.spec.ts @@ -0,0 +1,39 @@ +import { createStore } from '../src' + +describe('Subscriptions', () => { + const useStore = createStore('main', () => ({ + name: 'Eduardo', + })).bind(null, true) + + let store: ReturnType + beforeEach(() => { + store = useStore() + }) + + it('fires callback when patch is applied', () => { + const spy = jest.fn() + store.subscribe(spy) + store.state.name = 'Cleiton' + expect(spy).toHaveBeenCalledTimes(1) + }) + + it('unsubscribes callback when unsubscribe is called', () => { + const spy = jest.fn() + const unsubscribe = store.subscribe(spy) + unsubscribe() + store.state.name = 'Cleiton' + expect(spy).not.toHaveBeenCalled() + }) + + it('listeners are not affected when unsubscribe is called multiple times', () => { + const func1 = jest.fn() + const func2 = jest.fn() + const unsubscribe1 = store.subscribe(func1) + store.subscribe(func2) + unsubscribe1() + unsubscribe1() + store.state.name = 'Cleiton' + expect(func1).not.toHaveBeenCalled() + expect(func2).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/store.ts b/src/store.ts index 958f8a33..9cabaef7 100644 --- a/src/store.ts +++ b/src/store.ts @@ -89,9 +89,14 @@ export function buildStore< }) } - function subscribe(callback: SubscriptionCallback): void { + function subscribe(callback: SubscriptionCallback) { subscriptions.push(callback) - // TODO: return function to remove subscription + return () => { + const idx = subscriptions.indexOf(callback) + if (idx > -1) { + subscriptions.splice(idx, 1) + } + } } function reset() { diff --git a/src/types.ts b/src/types.ts index f3c6f51d..58052fb9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -88,9 +88,10 @@ export interface Store { /** * Setups a callback to be called whenever the state changes. - * @param callback callback that is called whenever the state changes + * @param callback callback that is called whenever the state + * @returns function that removes callback from subscriptions */ - subscribe(callback: SubscriptionCallback): void + subscribe(callback: SubscriptionCallback): () => void } export interface DevtoolHook {