Skip to content

Commit

Permalink
✨ removed local mocks, migrate to pusher-js-mock. Not happy with the …
Browse files Browse the repository at this point in the history
…tests.
  • Loading branch information
Harley Alexander committed Feb 26, 2020
1 parent 647bbaa commit 8d09648
Show file tree
Hide file tree
Showing 17 changed files with 153 additions and 455 deletions.
31 changes: 31 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest All",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
},
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
]
}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ I hear ya. If you're feeling audacious, you can use [client events](https://push
import { useChannel, useClientTrigger } from "@harelpls/use-pusher";

const Example = () => {
const channel = useChannel("presence-danger-zone");
const channel = useChannel("presence-ca");
const trigger = useClientTrigger(channel);
const handleClientEvent = () => {
trigger("Pew pew");
Expand All @@ -184,7 +184,7 @@ This project was built using typescript, so types are built-in. Yeeeew!

## Testing

Typed `PusherMock`, `PusherChannelMock` and `PusherPresenceChannelMock` utils are provided based on [`pusher-js-mock`](https://github.com/nikolalsvk/pusher-js-mock) (thanks mate 🙏). Use these to stub out the client and channels, with an additional `emit` method on the channel classes.
I've teamed up with [@nikolalsvk](https://github.com/nikolalsvk) on [`pusher-js-mock`](https://github.com/nikolalsvk/pusher-js-mock) to bring y'all a great pusher mock.

Testing emitted events with jest can be achieved using `jest.mock` and `@testing-library/react` (or `enzyme`, though your tests should reflect what the user should see **NOT** how the component handles events internally):

Expand All @@ -203,7 +203,7 @@ const Example = () => {

// Example.test.tsx
import { render, act } from "@testing-library/react";
import { PusherMock, PusherChannelMock } from "@harelpls/use-pusher";
import { PusherMock, PusherChannelMock } from "pusher-js-mock";

// mock out the result of the useChannel hook
const mockChannel = new PusherChannelMock();
Expand Down
9 changes: 6 additions & 3 deletions example/src/App.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import "./App.css";

import { useClientTrigger, usePresenceChannel } from "./use-pusher";

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { usePresenceChannel, useClientTrigger } from "./use-pusher";

function App() {
const { channel } = usePresenceChannel("presence-my-channel");
const { channel, ...rest } = usePresenceChannel("presence-my-channel");
const trigger = useClientTrigger(channel);
console.log(rest);

return (
<div className="App">
Expand Down
13 changes: 8 additions & 5 deletions example/src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

import * as serviceWorker from "./serviceWorker";
import { PusherProvider } from "./use-pusher/index";

import App from "./App";
import Pusher from "pusher";
import { PusherProvider } from "./use-pusher";
import React from "react";
import ReactDOM from "react-dom";

const pusher = new Pusher({
appId: process.env.REACT_APP_PUSHER_APP_ID,
key: process.env.REACT_APP_PUSHER_KEY,
Expand All @@ -20,7 +22,8 @@ ReactDOM.render(
authorizer={({ name }) => ({
authorize: async (socketId, callback) => {
const auth = pusher.authenticate(socketId, name, {
user_id: Math.random() * 124234
user_id: Math.random() * 124234,
user_info: {}
});
callback(false, auth);
}
Expand Down
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
collectCoverageFrom: ["src/**/*.{ts,tsx}"],
coveragePathIgnorePatterns: ["./src/index.ts"]
};
13 changes: 1 addition & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"gh-pages": "^2.0.1",
"jest-fetch-mock": "^2.1.2",
"pusher-js": "^5.1.0",
"pusher-js-mock": "^0.2.0",
"pusher-js-mock": "mayteio/pusher-js-mock#feature/presence-channels-release",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "^3.0.1",
Expand All @@ -76,16 +76,5 @@
"ts-jest": "^24.0.2",
"typedoc": "^0.16.9",
"typescript": "^3.2.4"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{ts,tsx}"
],
"coveragePathIgnorePatterns": [
"./src/index.ts",
"./src/mocks.ts",
"./src/helpers.ts",
"./src/types.ts"
]
}
}
30 changes: 16 additions & 14 deletions src/__tests__/Example.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { PusherChannelMock, PusherMock } from "pusher-js-mock";
import { PusherProvider, useChannel, useEvent } from "../";
// example.tsx
import React, { useState } from 'react';
import { render, act } from '@testing-library/react';
import { PusherProvider, useChannel, useEvent, PusherMock, PusherChannelMock } from '../';
import Pusher from 'pusher-js';
import React, { useState } from "react";
import { act, render } from "@testing-library/react";

import Pusher from "pusher-js";

// Example component
const Example = () => {
const [title, setTitle] = useState();
const channel = useChannel('my-channel');
useEvent<{ message: string }>(channel, 'title', data => {
const channel = useChannel("my-channel");
useEvent<{ message: string }>(channel, "title", (data) => {
setTitle(data && data.message);
});

Expand All @@ -17,23 +19,23 @@ const Example = () => {

// mock out the result of the useChannel hook
const mockChannel = new PusherChannelMock();
jest.mock('../', () => ({
...require.requireActual('../'),
useChannel: () => mockChannel,
jest.mock("../", () => ({
...require.requireActual("../"),
useChannel: () => mockChannel
}));

test('should show a title when it receives a title event from the socket.', async () => {
test("should show a title when it receives a title event from the socket.", async () => {
// render the provider with a mocked context value
const clientKey = 'key';
const client = { current: (new PusherMock(clientKey, { cluster: 'ap4' }) as unknown) as Pusher };
const clientKey = "key";
const client = (new PusherMock() as unknown) as Pusher;
const { findByText } = render(
<PusherProvider clientKey={clientKey} cluster="ap4" value={{ client }}>
<Example />
</PusherProvider>
);
// call an event on the mocked channel
act(() => mockChannel.emit('title', { message: 'Hello world' }));
act(() => mockChannel.emit("title", { message: "Hello world" }));

// assert expectations
expect(await findByText('Hello world')).toBeTruthy();
expect(await findByText("Hello world")).toBeTruthy();
});
2 changes: 1 addition & 1 deletion src/__tests__/useChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ beforeEach(() => {
});

jest.mock("pusher-js", () => {
const { PusherMock } = require("../mocks");
const { PusherMock } = require("pusher-js-mock");
return PusherMock;
});

Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/useClientTrigger.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { renderHook } from "@testing-library/react-hooks";
import { PusherPresenceChannelMock } from "../mocks";
import { PusherPresenceChannelMock } from "pusher-js-mock";
import { useClientTrigger } from "../useClientTrigger";
import { PresenceChannel } from "pusher-js";

Expand Down
8 changes: 4 additions & 4 deletions src/__tests__/useEvent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import React from "react";
import { renderHook } from "@testing-library/react-hooks";
import { useEvent } from "../";
import { PusherProvider } from "../PusherProvider";
import { PusherChannelMock } from "../mocks";
import { PusherChannelMock } from "pusher-js-mock";
import { Channel } from "pusher-js";

beforeEach(() => {
jest.resetAllMocks();
});

jest.mock("pusher-js", () => {
const { PusherMock } = require("../mocks");
const { PusherMock } = require("pusher-js-mock");
return PusherMock;
});

Expand Down Expand Up @@ -56,7 +56,7 @@ describe("useEvent hook", () => {
rerender();

channel.emit("my-event", "test");
expect(callback).toHaveBeenCalledWith("test", undefined);
expect(callback).toHaveBeenCalledWith("test");
});

test("should unbind on unmount", () => {
Expand All @@ -76,7 +76,7 @@ describe("useEvent hook", () => {
rerender([channel, "your-event", callback]);

channel.emit("your-event", "test");
expect(callback).toHaveBeenCalledWith("test", undefined);
expect(callback).toHaveBeenCalledWith("test");

unmount();
expect(channel.callbacks["my-event"]).toHaveLength(0);
Expand Down
77 changes: 23 additions & 54 deletions src/__tests__/usePresenceChannel.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import Pusher from "pusher-js";
import { PusherMock } from "pusher-js-mock";
import { PusherProvider } from "../PusherProvider";
import React from "react";
import { act } from "@testing-library/react-hooks";
import { renderHook } from "@testing-library/react-hooks";
import { usePresenceChannel } from "../usePresenceChannel";
import { PusherProvider } from "../PusherProvider";
import { act } from "@testing-library/react-hooks";

beforeEach(() => {
jest.resetAllMocks();
});

jest.mock("pusher-js", () => {
const { PusherMock } = require("../mocks");
return PusherMock;
});
// jest.mock("pusher-js", () => {
// const { PusherMock } = require("pusher-js-mock");
// return PusherMock;
// });

const config = {
clientKey: "client-key",
Expand All @@ -20,8 +22,13 @@ const config = {
};

const setup = (channelName = "my-channel", customConfig = {}) => {
const client = new PusherMock("my-id", {}) as unknown;
const wrapper = ({ children }: any) => (
<PusherProvider {...config} {...customConfig}>
<PusherProvider
{...config}
{...customConfig}
value={{ client: client as Pusher }}
>
{children}
</PusherProvider>
);
Expand All @@ -34,7 +41,7 @@ describe("usePresenceChannel hook", () => {
<PusherProvider
{...config}
children={children}
value={{ client: undefined, triggerEndpoint: "d" }}
value={{ client: undefined }}
/>
);
const { result, rerender } = renderHook(
Expand Down Expand Up @@ -70,54 +77,16 @@ describe("usePresenceChannel hook", () => {
});

test("should return new member list when members are added", async () => {
const { result, rerender } = setup("presence-channel");
rerender();

// emits members object
await act(async () => {
result.current.channel.emit("pusher:subscription_succeeded", {
myID: "0a",
members: {
"0b": {
id: "0b",
info: {}
}
}
});
});

expect((result.current.members as any)["0b"]).toBeDefined();
rerender();

const { result, waitForNextUpdate } = setup("presence-channel");
await waitForNextUpdate();
expect(result.current.members).toEqual({ "my-id": {} });
act(() => {
result.current.channel.emit("pusher:member_removed", {
id: "0b",
info: {}
});
result.current.channel.emit("pusher:member_added", {
id: "0c",
info: {}
});
// new client connecting
const otherClient = new PusherMock("your-id", {});
otherClient.subscribe("presence-channel");
});

expect(result.current.members["0b"]).toBeUndefined();
expect(result.current.members["0c"]).toBeDefined();
});

test("should return myID if present", async () => {
const { result, rerender } = setup("presence-channel");
rerender();
await act(async () => {
result.current.channel.emit("pusher:subscription_succeeded", {
myID: "0a",
members: {
"0b": {
id: "0b",
info: {}
}
}
});
});
expect(result.current.myID).toBe("0a");
await waitForNextUpdate();
expect(result.current.members).toEqual({ "my-id": {}, "your-id": {} });
});
});
Loading

0 comments on commit 8d09648

Please sign in to comment.