feat: Reconnect logic (#9453)
Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com> Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
This commit is contained in:
20
app/javascript/dashboard/composables/emitter.js
Normal file
20
app/javascript/dashboard/composables/emitter.js
Normal file
@@ -0,0 +1,20 @@
|
||||
import { emitter } from 'shared/helpers/mitt';
|
||||
import { onMounted, onBeforeUnmount } from 'vue';
|
||||
|
||||
// this will automatically add event listeners to the emitter
|
||||
// and remove them when the component is destroyed
|
||||
const useEmitter = (eventName, callback) => {
|
||||
const cleanup = () => {
|
||||
emitter.off(eventName, callback);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
emitter.on(eventName, callback);
|
||||
});
|
||||
|
||||
onBeforeUnmount(cleanup);
|
||||
|
||||
return cleanup;
|
||||
};
|
||||
|
||||
export { useEmitter };
|
||||
51
app/javascript/dashboard/composables/spec/emitter.spec.js
Normal file
51
app/javascript/dashboard/composables/spec/emitter.spec.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import { emitter } from 'shared/helpers/mitt';
|
||||
import { useEmitter } from '../emitter';
|
||||
|
||||
jest.mock('shared/helpers/mitt', () => ({
|
||||
emitter: {
|
||||
on: jest.fn(),
|
||||
off: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('useEmitter', () => {
|
||||
let wrapper;
|
||||
const eventName = 'my-event';
|
||||
const callback = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
wrapper = shallowMount({
|
||||
template: `
|
||||
<div>
|
||||
Hello world
|
||||
</div>
|
||||
`,
|
||||
setup() {
|
||||
return {
|
||||
cleanup: useEmitter(eventName, callback),
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it('should add an event listener on mount', () => {
|
||||
expect(emitter.on).toHaveBeenCalledWith(eventName, callback);
|
||||
});
|
||||
|
||||
it('should remove the event listener when the component is unmounted', () => {
|
||||
wrapper.destroy();
|
||||
expect(emitter.off).toHaveBeenCalledWith(eventName, callback);
|
||||
});
|
||||
|
||||
it('should return the cleanup function', () => {
|
||||
const cleanup = wrapper.vm.cleanup;
|
||||
expect(typeof cleanup).toBe('function');
|
||||
cleanup();
|
||||
expect(emitter.off).toHaveBeenCalledWith(eventName, callback);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user