import { Callbacks } from './callbacks'; describe('callbacks tests', () => { const KEY_ONE = 'key_one'; const KEY_TWO = 'key_two'; const CALLBACK_ID = 'cb_id'; const MISSING_CALLBACK_ID = 'missing_cb_id'; const CALLBACK_FN = vi.fn(); const ANOTHER_CALLBACK_FN = vi.fn(); const CALLBACK = { id: CALLBACK_ID, fn: CALLBACK_FN }; const PAYLOAD = { data: 'data' }; let callbacks: Callbacks; beforeEach(() => { callbacks = new Callbacks({ [KEY_ONE]: [CALLBACK], }); }); afterEach(() => { vi.resetAllMocks(); }); describe('when getting callbacks for a key', () => { it('should return the callbacks when the key is found in the store', () => { expect(callbacks.getFrom(KEY_ONE)).toEqual([CALLBACK]); }); it('should default to an empty list when the key is not found in the store', () => { expect(callbacks.getFrom(KEY_TWO)).toEqual([]); }); }); describe('when adding callbacks for a key', () => { it('should add the new callback', () => { callbacks.addTo(KEY_ONE, ANOTHER_CALLBACK_FN); expect(callbacks.getFrom(KEY_ONE)).toHaveLength(2); }); it('should create a new store entry with the callback given an un-exiting story entry', () => { callbacks.addTo(KEY_TWO, ANOTHER_CALLBACK_FN); expect(callbacks.getFrom(KEY_TWO)).toHaveLength(1); }); }); describe('when remove a callback from a store entry', () => { describe('by callback id', () => { it('should be removed when matched', () => { callbacks.removeByCallbackIdFrom(KEY_ONE, CALLBACK_ID); expect(callbacks.getFrom(KEY_ONE)).toEqual([]); }); it('should do nothing when not matched', () => { callbacks.removeByCallbackIdFrom(KEY_ONE, MISSING_CALLBACK_ID); expect(callbacks.getFrom(KEY_ONE)).toEqual([CALLBACK]); }); it('should do nothing when the entry does not exists in the store', () => { callbacks.removeByCallbackIdFrom(KEY_TWO, CALLBACK_ID); expect(callbacks.getFrom(KEY_ONE)).toEqual([CALLBACK]); }); }); describe('by callback function', () => { it('should be removed when matched', () => { callbacks.removeByCallbackFunctionFrom(KEY_ONE, CALLBACK_FN); expect(callbacks.getFrom(KEY_ONE)).toEqual([]); }); it('should do nothing when not matched', () => { callbacks.removeByCallbackFunctionFrom(KEY_ONE, ANOTHER_CALLBACK_FN); expect(callbacks.getFrom(KEY_ONE)).toEqual([CALLBACK]); }); it('should do nothing when the entry does not exists in the store', () => { callbacks.removeByCallbackFunctionFrom(KEY_TWO, CALLBACK_FN); expect(callbacks.getFrom(KEY_ONE)).toEqual([CALLBACK]); }); }); describe('when executing the callback functions in a stack', () => { it('should run each functions with the provided payload', () => { callbacks.addTo(KEY_ONE, ANOTHER_CALLBACK_FN); callbacks.executeFor(KEY_ONE, PAYLOAD); expect(CALLBACK_FN).toHaveBeenCalledWith(PAYLOAD); expect(ANOTHER_CALLBACK_FN).toHaveBeenCalledWith(PAYLOAD); }); it('should not run anything given an empty callback stack', () => { callbacks.executeFor(KEY_TWO, PAYLOAD); expect(CALLBACK_FN).not.toHaveBeenCalled(); expect(ANOTHER_CALLBACK_FN).not.toHaveBeenCalled(); }); }); }); });