import { renderHook, RenderHookResult } from '@testing-library/react'; import { getOrCreateSharedImpl } from '../get-shared'; import { init, RumService, type ServiceConfig } from '../init'; import { useRumService } from '../use-rum-service'; jest.mock('../init'); jest.mock('../get-shared'); describe(`[datadog-rum] ${useRumService.name}`, () => { const cleanup = jest.fn(); const setServiceContext = jest.fn(); const initSetServiceContext = jest.fn(); let config: ServiceConfig; beforeEach(() => { jest.clearAllMocks(); jest.mocked(init).mockReturnValue({ cleanup, setServiceContext: initSetServiceContext }); jest.mocked(getOrCreateSharedImpl).mockReturnValue({ setServiceContext, } as unknown as ReturnType); config = { name: 'foo' }; }); const subject = () => renderHook((cfg: ServiceConfig) => useRumService(cfg), { initialProps: config }); describe('on mount', () => { beforeEach(() => { subject(); }); test('registers the service', () => { expect(init).toHaveBeenCalledWith({ service: config }); }); }); describe('on unmount', () => { beforeEach(() => { const { unmount } = subject(); unmount(); }); test('runs cleanup', () => { expect(cleanup).toHaveBeenCalled(); }); }); test('setServiceContext delegates to the shared implementation', () => { const context = { foo: 'bar' }; subject().result.current.setServiceContext(context); expect(setServiceContext).toHaveBeenCalledWith(config.name, context); }); describe('when already rendered', () => { let rerender: RenderHookResult['rerender']; let result: RenderHookResult['result']; beforeEach(() => { const renderHookResult = subject(); rerender = renderHookResult.rerender; result = renderHookResult.result; jest.clearAllMocks(); }); test('does not register the service again', () => { rerender({ name: 'changed' }); expect(init).not.toHaveBeenCalled(); }); test('returns same result', () => { const initial = result.current; rerender({ name: 'changed' }); expect(result.current).toBe(initial); }); }); });