1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-26 12:25:20 +01:00
bitwarden-browser/apps/browser/spec/mock-port.spec-util.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

30 lines
1.1 KiB
TypeScript
Raw Normal View History

import { mockDeep } from "jest-mock-extended";
/**
* Mocks a chrome.runtime.Port set up to send messages through `postMessage` to `onMessage.addListener` callbacks.
* @param name - The name of the port.
* @param immediateOnConnectExecution - Whether to immediately execute the onConnect callbacks against the new port.
* Defaults to false. If true, the creator of the port will not have had a chance to set up listeners yet.
* @returns a mock chrome.runtime.Port
*/
export function mockPorts() {
// notify listeners of a new port
(chrome.runtime.connect as jest.Mock).mockImplementation((portInfo) => {
const port = mockDeep<chrome.runtime.Port>();
port.name = portInfo.name;
// set message broadcast
(port.postMessage as jest.Mock).mockImplementation((message) => {
(port.onMessage.addListener as jest.Mock).mock.calls.forEach(([callbackFn]) => {
callbackFn(message, port);
});
});
(chrome.runtime.onConnect.addListener as jest.Mock).mock.calls.forEach(([callbackFn]) => {
callbackFn(port);
});
return port;
});
}