Skip to content

Commit

Permalink
feat: improve useNetworkState tests
Browse files Browse the repository at this point in the history
  • Loading branch information
xobotyi committed May 3, 2021
1 parent e5512e7 commit c91c3b6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/useNetworkState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ export const useNetworkState: typeof navigator.connection extends undefined
on(window, 'online', handleStateChange, { passive: true });
on(window, 'offline', handleStateChange, { passive: true });

// it is quite hard to test it in jsdom environment maybe will be improved in future
/* istanbul ignore next */
if (conn) {
on(conn, 'change', handleStateChange, { passive: true });
}
Expand All @@ -125,6 +127,7 @@ export const useNetworkState: typeof navigator.connection extends undefined
off(window, 'online', handleStateChange);
off(window, 'offline', handleStateChange);

/* istanbul ignore next */
if (conn) {
off(conn, 'change', handleStateChange);
}
Expand Down
22 changes: 21 additions & 1 deletion tests/dom/useNetworkState.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { renderHook } from '@testing-library/react-hooks/dom';
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { useRef } from 'react';
import { useNetworkState } from '../../src/useNetworkState';

describe(`useNetworkState`, () => {
Expand All @@ -25,4 +26,23 @@ describe(`useNetworkState`, () => {
'type',
]);
});

it('should rerender in case of online or offline events emitted on window', () => {
const hook = renderHook(
() => {
const renderCount = useRef(0);
return [useNetworkState(), ++renderCount.current];
},
{ initialProps: false }
);

expect(hook.result.current[1]).toBe(1);
const prevNWState = hook.result.current[0];

act(() => {
window.dispatchEvent(new Event('online'));
});
expect(hook.result.current[1]).toBe(2);
expect(hook.result.current[0]).not.toBe(prevNWState);
});
});

0 comments on commit c91c3b6

Please sign in to comment.