-
Notifications
You must be signed in to change notification settings - Fork 8
Network connection provider and hook #80
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
myty
wants to merge
16
commits into
rsm-hcd:main
Choose a base branch
from
myty:feature/use-network-information
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
18f917d
add network information context, provider, and hook
myty 7a66e0c
add devDependencies
myty 9ab69e7
update network-connection-provider and add tests
myty 6553105
Merge branch 'main' of https://github.com/AndcultureCode/AndcultureCo…
myty 438bf9b
additional network connection provider tests
myty c99cfbc
address PR comments
myty 14149bf
Merge branch 'main' of https://github.com/AndcultureCode/AndcultureCo…
myty 73f02da
export network connection provider and hook
myty 08b3832
additional window eventhandlers
myty f85783d
update tests
myty b3f50d5
tests cleanup
myty 537c98b
consolidate the network change event
myty 3b68f27
cleanup around the NetworkConnectionFactory
myty 2d2506b
remove rtt attrinute from NetworkConnectionFactory
myty 19b0bbb
more test factory cleanup
myty a4548a5
update util type to TypeOfKey
myty File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { NetworkConnection } from "andculturecode-javascript-core"; | ||
import React from "react"; | ||
|
||
export const NetworkConnectionContext = React.createContext< | ||
NetworkConnection | undefined | ||
>(undefined); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { render } from "@testing-library/react"; | ||
import { renderHook } from "@testing-library/react-hooks"; | ||
import { | ||
NetworkConnection, | ||
NetworkInformationUtils, | ||
} from "andculturecode-javascript-core"; | ||
import React from "react"; | ||
import { NetworkConnectionProvider } from "../providers/network-connection-provider"; | ||
import { useNetworkConnection } from "./use-network-connection"; | ||
|
||
// ----------------------------------------------------------------------------------------- | ||
// #region Mocks | ||
// ----------------------------------------------------------------------------------------- | ||
|
||
const getNetworkConnectionMock = jest.spyOn( | ||
NetworkInformationUtils, | ||
"getNetworkConnection" | ||
); | ||
|
||
// #endregion Mocks | ||
|
||
describe("useNetworkConnection", () => { | ||
describe("when used outside NetworkConnectionProvider", () => { | ||
it("throws error", () => { | ||
// Arrange & Act | ||
const { result } = renderHook(() => useNetworkConnection()); | ||
|
||
// Assert | ||
expect(result.error).toBeDefined(); | ||
}); | ||
}); | ||
|
||
describe("when used inside NetworkConnectionProvider", () => { | ||
it("returns network connection information", () => { | ||
// Arrange | ||
let networkConnection: NetworkConnection; | ||
const expectedNetworkConnection: NetworkConnection = { | ||
isOnline: true, | ||
}; | ||
|
||
getNetworkConnectionMock.mockReturnValue(expectedNetworkConnection); | ||
|
||
const TestComponent = () => { | ||
networkConnection = useNetworkConnection(); | ||
return <div></div>; | ||
}; | ||
|
||
// Act | ||
render( | ||
<NetworkConnectionProvider> | ||
<TestComponent /> | ||
</NetworkConnectionProvider> | ||
); | ||
|
||
// Assert | ||
expect(networkConnection).toEqual(expectedNetworkConnection); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { useContext } from "react"; | ||
import { NetworkConnection } from "andculturecode-javascript-core"; | ||
import { NetworkConnectionContext } from "../contexts/network-connection-context"; | ||
|
||
/** | ||
* Hook that returns the current network connection information | ||
*/ | ||
export const useNetworkConnection = (): NetworkConnection => { | ||
const networkConnection = useContext(NetworkConnectionContext); | ||
|
||
if (networkConnection == null) { | ||
throw new Error( | ||
"useNetworkConnection must be used within a NetworkConnectionProvider component" | ||
); | ||
} | ||
|
||
return networkConnection; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,216 @@ | ||
import React from "react"; | ||
import { act, cleanup, render } from "@testing-library/react"; | ||
import { NetworkConnectionProvider } from "./network-connection-provider"; | ||
import { | ||
NetworkConnection, | ||
NetworkInformationUtils, | ||
} from "andculturecode-javascript-core"; | ||
import { useNetworkConnection } from "../hooks/use-network-connection"; | ||
import { FactoryType } from "../tests/factories/factory-type"; | ||
import { Factory } from "rosie"; | ||
|
||
// ----------------------------------------------------------------------------------------- | ||
// #region Types | ||
// ----------------------------------------------------------------------------------------- | ||
|
||
type TypeFromKey<Type, Key extends keyof Type> = Type[Key]; | ||
|
||
// #endregion Types | ||
|
||
// ----------------------------------------------------------------------------------------- | ||
// #region Interfaces | ||
// ----------------------------------------------------------------------------------------- | ||
|
||
interface SetupSutOptions { | ||
mockConnections?: Array<Partial<NetworkConnection>>; | ||
} | ||
|
||
interface SetupSutResults { | ||
TestComponent: () => JSX.Element; | ||
networkConnectionResults: { | ||
all: Array<NetworkConnection>; | ||
current?: NetworkConnection; | ||
}; | ||
} | ||
|
||
// #endregion Interfaces | ||
|
||
// ----------------------------------------------------------------------------------------- | ||
// #region Setup | ||
// ----------------------------------------------------------------------------------------- | ||
|
||
const getNetworkConnectionMock = jest.spyOn( | ||
NetworkInformationUtils, | ||
"getNetworkConnection" | ||
); | ||
|
||
const setupMocks = (mockConnections: Array<Partial<NetworkConnection>>) => { | ||
getNetworkConnectionMock.mockReset(); | ||
for (let index = 0; index < mockConnections.length; index++) { | ||
const mockImplementation = | ||
index === mockConnections.length - 1 | ||
? getNetworkConnectionMock.mockImplementation | ||
: getNetworkConnectionMock.mockImplementationOnce; | ||
|
||
mockImplementation(() => { | ||
return { | ||
isOnline: true, | ||
...mockConnections[index], | ||
}; | ||
}); | ||
} | ||
}; | ||
|
||
const setupSut = (options?: SetupSutOptions): SetupSutResults => { | ||
const { mockConnections = [] } = options ?? {}; | ||
|
||
setupMocks(mockConnections); | ||
|
||
const networkConnectionResults: TypeFromKey< | ||
SetupSutResults, | ||
"networkConnectionResults" | ||
> = { | ||
all: [] as NetworkConnection[], | ||
}; | ||
|
||
function TestComponent() { | ||
const connection = useNetworkConnection(); | ||
networkConnectionResults.all.push(connection); | ||
networkConnectionResults.current = connection; | ||
|
||
return <div></div>; | ||
} | ||
|
||
return { | ||
TestComponent, | ||
networkConnectionResults, | ||
}; | ||
}; | ||
|
||
// #endregion Setup | ||
|
||
describe("NetworkConnectionProvider", () => { | ||
it("renders initial network connection state", () => { | ||
// Arrange | ||
const expectedConnection = Factory.build<NetworkConnection>( | ||
FactoryType.NetworkConnection | ||
); | ||
const { networkConnectionResults, TestComponent } = setupSut({ | ||
mockConnections: [ | ||
Factory.build<NetworkConnection>(FactoryType.NetworkConnection), | ||
expectedConnection, | ||
], | ||
}); | ||
|
||
// Act | ||
render( | ||
<NetworkConnectionProvider> | ||
<TestComponent /> | ||
</NetworkConnectionProvider> | ||
); | ||
|
||
// Assert | ||
expect(networkConnectionResults.all.length).toEqual(2); | ||
expect(networkConnectionResults.current).toEqual(expectedConnection); | ||
}); | ||
|
||
it("adds an event listener", () => { | ||
// Arrange | ||
const addEventListener = jest.fn(); | ||
const networkConnection = Factory.build<NetworkConnection>( | ||
FactoryType.NetworkConnection, | ||
{ | ||
addEventListener, | ||
} | ||
); | ||
const { TestComponent } = setupSut({ | ||
mockConnections: [networkConnection], | ||
}); | ||
|
||
// Act | ||
render( | ||
<NetworkConnectionProvider> | ||
<TestComponent /> | ||
</NetworkConnectionProvider> | ||
); | ||
|
||
// Assert | ||
expect(addEventListener).toBeCalled(); | ||
}); | ||
|
||
describe("when change event is called", () => { | ||
it("loads network connection into state", () => { | ||
// Arrange | ||
let changeEventCallback = () => {}; | ||
|
||
const expectedNetworkConnection = Factory.build<NetworkConnection>( | ||
FactoryType.NetworkConnection | ||
); | ||
|
||
const mockConnections: Array<NetworkConnection> = [ | ||
Factory.build<NetworkConnection>(FactoryType.NetworkConnection), | ||
Factory.build<NetworkConnection>( | ||
FactoryType.NetworkConnection, | ||
{ | ||
addEventListener: ( | ||
event: "change", | ||
callback: VoidFunction | ||
) => { | ||
changeEventCallback = callback; | ||
}, | ||
} | ||
), | ||
expectedNetworkConnection, | ||
]; | ||
|
||
const { networkConnectionResults, TestComponent } = setupSut({ | ||
mockConnections, | ||
}); | ||
|
||
// Act | ||
render( | ||
<NetworkConnectionProvider> | ||
<TestComponent /> | ||
</NetworkConnectionProvider> | ||
); | ||
|
||
act(() => changeEventCallback()); | ||
|
||
// Assert | ||
expect(networkConnectionResults.all.length).toEqual( | ||
mockConnections.length | ||
); | ||
expect(networkConnectionResults.current).toEqual( | ||
expectedNetworkConnection | ||
); | ||
}); | ||
}); | ||
|
||
describe("when unmounted", () => { | ||
it("calls removeEventlistener for cleanup", async () => { | ||
// Arrange | ||
const removeEventListener = jest.fn(); | ||
const networkConnection = Factory.build<NetworkConnection>( | ||
FactoryType.NetworkConnection, | ||
{ | ||
removeEventListener, | ||
} | ||
); | ||
const { TestComponent } = setupSut({ | ||
mockConnections: [networkConnection], | ||
}); | ||
|
||
// Act | ||
render( | ||
<NetworkConnectionProvider> | ||
<TestComponent /> | ||
</NetworkConnectionProvider> | ||
); | ||
|
||
await cleanup(); | ||
|
||
// Assert | ||
expect(removeEventListener).toBeCalled(); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import React, { | ||
PropsWithChildren, | ||
useCallback, | ||
useEffect, | ||
useState, | ||
} from "react"; | ||
import { | ||
NetworkConnection, | ||
NetworkInformationUtils, | ||
} from "andculturecode-javascript-core"; | ||
import { NetworkConnectionContext } from "../contexts/network-connection-context"; | ||
|
||
/** | ||
* Wrapper provider component that provides context to the `useNetworkConnection` hook | ||
*/ | ||
export const NetworkConnectionProvider: React.FC = ( | ||
props: PropsWithChildren<unknown> | ||
) => { | ||
const { children } = props; | ||
|
||
const [state, setState] = useState<NetworkConnection | undefined>( | ||
NetworkInformationUtils.getNetworkConnection() | ||
); | ||
|
||
const loadNetworkInformation = useCallback((isOnline?: boolean) => { | ||
const networkConnection = NetworkInformationUtils.getNetworkConnection(); | ||
|
||
if (networkConnection == null) { | ||
return; | ||
} | ||
|
||
setState((prev) => ({ | ||
...prev, | ||
...networkConnection, | ||
isOnline: isOnline ?? networkConnection.isOnline, | ||
})); | ||
}, []); | ||
|
||
useEffect( | ||
function handleNetworkChangeEvents() { | ||
const networkConnection = NetworkInformationUtils.getNetworkConnection(); | ||
|
||
const createNetworkChangeHandler = (isOnline?: boolean) => () => | ||
loadNetworkInformation(isOnline); | ||
|
||
const handleNetworkChange = createNetworkChangeHandler(); | ||
const handleOffline = createNetworkChangeHandler(false); | ||
const handleOnline = createNetworkChangeHandler(true); | ||
|
||
networkConnection?.addEventListener?.( | ||
"change", | ||
handleNetworkChange | ||
); | ||
window?.addEventListener?.("online", handleOnline); | ||
window?.addEventListener?.("offline", handleOffline); | ||
|
||
loadNetworkInformation(); | ||
|
||
return function cleanup() { | ||
networkConnection?.removeEventListener?.( | ||
"change", | ||
handleNetworkChange | ||
); | ||
window?.removeEventListener?.("online", handleOnline); | ||
window?.removeEventListener?.("offline", handleOffline); | ||
}; | ||
}, | ||
[loadNetworkInformation] | ||
); | ||
|
||
return ( | ||
<NetworkConnectionContext.Provider value={state}> | ||
{children} | ||
</NetworkConnectionContext.Provider> | ||
); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.