Skip to content

Instantly share code, notes, and snippets.

@EduardoAC
Last active June 7, 2024 11:28
Show Gist options
  • Save EduardoAC/59ac4fefa385ce046291b3f78db37c86 to your computer and use it in GitHub Desktop.
Save EduardoAC/59ac4fefa385ce046291b3f78db37c86 to your computer and use it in GitHub Desktop.
Chrome Extension - Site Page Review - Message Handler test using jest.mock to mock underlying handlers
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MessageRate } from "../../types/message.types"
import { messageHandler } from "./eventHandler"
import { ratingMessageHandler } from "./onMessageHandlers/ratingMessageHandler"
jest.mock("./onMessageHandlers/ratingMessageHandler")
describe("messageHandler", () => {
const sendResponseMock = jest.fn()
beforeEach(() => {
jest.clearAllMocks()
})
it('should delegate "rating" message to ratingMessageHandler and return true', () => {
const message: Message<MessageRate> = {
type: "rating",
subType: "update",
data: { url: "http://example.com", rate: 5 },
}
const sender = { tab: { id: 1 } }
const result = messageHandler(message, sender as any, sendResponseMock)
expect(ratingMessageHandler).toHaveBeenCalledWith(
message,
sendResponseMock,
)
expect(result).toBe(true)
})
it("Should respond synchronously and immediately to the content script when an incorrect message type is detected", () => {
// ... Full example can be found on https://github.com/EduardoAC/site-review-extension/blob/master/src/serviceWorker/events/eventHandler.test.ts
})
it("Should respond synchronously if sender.tab is absent, immediately returning a response to the content script", () => {
//... Full example can be found on https://github.com/EduardoAC/site-review-extension/blob/master/src/serviceWorker/events/eventHandler.test.ts
})
it("Should respond synchronously if message.type is missing, immediately returning a response to the content script", () => {
//... Full example can be found on https://github.com/EduardoAC/site-review-extension/blob/master/src/serviceWorker/events/eventHandler.test.ts
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment