Skip to content

Instantly share code, notes, and snippets.

@EduardoAC
Created June 7, 2024 11:00
Show Gist options
  • Save EduardoAC/cc58b1fe8d922ab990a79942853d0cb6 to your computer and use it in GitHub Desktop.
Save EduardoAC/cc58b1fe8d922ab990a79942853d0cb6 to your computer and use it in GitHub Desktop.
Chrome extension - testing rating message handler using jest-chrome for Chrome API mocking
/* eslint-disable @typescript-eslint/no-explicit-any */
import { JestChrome } from "jest-chrome/types/jest-chrome"
import { ratingMessageHandler } from "./ratingMessageHandler"
import { MessageRate } from "../../../types/message.types"
describe("ratingMessageHandler", () => {
const sendResponseMock = jest.fn()
const jestChrome = chrome as any as JestChrome
beforeEach(() => {
jest.clearAllMocks()
})
it('should delegate "get" message to getRateFromCache', async () => {
const message: Message<MessageRate> = {
type: "rating",
subType: "get",
data: { url: "http://example.com" },
}
jestChrome.storage.local.get.mockImplementation(() =>
Promise.resolve({ "http://example.com": 5 }),
)
await ratingMessageHandler(message, sendResponseMock)
expect(chrome.storage.local.get).toHaveBeenCalledWith([
"http://example.com",
])
expect(sendResponseMock).toHaveBeenCalledWith({
statusCode: 200,
data: 5,
})
})
it('should delegate "update" message to updateCacheRating', async () => {
const message: Message<MessageRate> = {
type: "rating",
subType: "update",
data: { url: "http://example.com", rate: 5 },
}
jestChrome.storage.local.set.mockImplementation(() => Promise.resolve())
await ratingMessageHandler(message, sendResponseMock)
expect(chrome.storage.local.set).toHaveBeenCalledWith({
"http://example.com": 5,
})
expect(sendResponseMock).toHaveBeenCalledWith({ statusCode: 200 })
})
it("should return status 405 for unsupported subType", async () => {
const message: Message<MessageRate> = {
type: "rating",
subType: "unknown" as any,
data: { url: "http://example.com" },
}
await ratingMessageHandler(message, sendResponseMock)
expect(sendResponseMock).toHaveBeenCalledWith({ statusCode: 405 })
})
})
@EduardoAC
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment