pusher-js-mock
Mock Pusher.js in your JavaScript tests with ease
Installing ⏬
Using yarn:
yarn add --dev pusher-js-mock
Or using npm:
npm install -D pusher-js-mock
Usage 🛠
For more detailed examples, check out examples
directory
inside the project!
Also, you can check out the
Docs for even more information.
Emitting an event in tests
If you need to mock a Pusher object in your tests that can
subscribe to channel, it's best to use PusherMock.
import { PusherMock } from "pusher-js-mock";
const pusher = new PusherMock()
const channel = pusher.subscribe("my-channel")
channel.emit("event-name")
Stubbing Pusher when imported from pusher-js package
If you're using Pusher in your code in this or similar manner:
import Pusher from 'pusher-js';
You will need to mock Pusher in a specific way.
I suggest you use Jest to test your code.
To do this in Jest, you'll need something like this:
jest.mock('pusher-js', () => {
const Pusher = require('pusher-js-mock').PusherMock
return Pusher
})
If you have tips on how to mock this using other testing frameworks, please
submit an issue or a pull request.
Stubbing Pusher when used as a global variable
This shows how to stub a pusher if you're attaching it to window object in your
project. If you're attaching a PusherFactory to a window
object like this in
your code:
window.PusherFactory = {
pusherClient: function(pusherKey) {
return new Pusher(pusherKey);
}
};
It's best for you to use PusherFactoryMock.
import { PusherFactoryMock } from "pusher-js-mock";
const pusherFactoryMock = new PusherFactoryMock();
window.PusherFactory = pusherFactoryMock;
pusher = pusherFactoryMock.pusherClient()
This way you'll just replace your PusherFactory with PusherFactoryMock.
Credits
Photo by Octavian Rosca on Unsplash