Skip to content

Commit

Permalink
✅ added testUtils file
Browse files Browse the repository at this point in the history
  • Loading branch information
Harley Alexander committed Mar 3, 2020
1 parent df0ce7d commit 0798afc
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/__tests__/useChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Pusher from "pusher-js";
import React from "react";
import { __PusherContext } from "../PusherProvider";
import { renderHook } from "@testing-library/react-hooks";
import { renderHookWithProvider } from "../../testUtils";
import { renderHookWithProvider } from "../testUtils";
import { useChannel } from "../useChannel";

describe("useChannel()", () => {
Expand Down
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// hooks for prod
export * from "./PusherProvider";
export * from "./usePusher";
export * from "./useChannel";
export * from "./usePresenceChannel";
export * from "./useEvent";
export * from "./useClientTrigger";
export * from "./useTrigger";

// test utils
import * as testUtils from "./testUtils";
export { testUtils };
46 changes: 46 additions & 0 deletions src/testUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { act, renderHook } from "@testing-library/react-hooks";

import Pusher from "pusher-js";
import { PusherMock } from "pusher-js-mock";
import React from "react";
import { __PusherContext } from "./PusherProvider";

/**
* Flushes async promises in mocks
*/
export const actAndFlushPromises = async () =>
await act(async () => await new Promise(setImmediate));

/**
* Does a bit of setup for us so we don't have to repeat ourselves
* @param hook the hook you want to render, i.e. () => useHook()
* @param clientConfig the client config passed to PusherMock
*/
export async function renderHookWithProvider<T>(
hook: () => T,
clientConfig: Record<string, any> = {}
) {
const client = new PusherMock("key", clientConfig) as unknown;
const wrapper: React.FC = ({ children }) => (
<__PusherContext.Provider value={{ client: client as Pusher }}>
{children}
</__PusherContext.Provider>
);
const result = renderHook(hook, { wrapper });
await actAndFlushPromises();
return result;
}

/**
* Generates basic Pusher config with authorizer
* @param id the id for the client
* @param info the info object for the client
*/
export const makeAuthPusherConfig = (id: string = "my-id", info: any = {}) => ({
authorizer: () => ({
authorize: (
socketId: string,
callback: (errored: boolean, info: any) => void
) => callback(socketId === "errored", { id, info })
})
});

0 comments on commit 0798afc

Please sign in to comment.