Created
June 7, 2024 11:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 }) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code for sendMessage can be found at https://gist.github.com/EduardoAC/000b1e39a6ec10a892e7c6cd93730a53
The original test file can be found at https://github.com/EduardoAC/site-review-extension/blob/master/src/contentScript/messages/sendMessage.test.ts