Created
June 6, 2024 07:57
-
-
Save EduardoAC/a93bb566ebdbbb1e67ca02e1dbe39ee8 to your computer and use it in GitHub Desktop.
Chrome extension - testing 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 { sendMessage } from "./sendMessage" | |
describe("sendMessage", () => { | |
it("should send the message correctly", async () => { | |
const message: Message = { type: "rating", subType: "get" } | |
const response: MessageResponse = { statusCode: 200, data: 2 } | |
const jestChrome = chrome as any as JestChrome | |
jestChrome.runtime.sendMessage.mockImplementation( | |
(_message: any, callback: any) => { | |
return callback(response) | |
}, | |
) | |
const promiseResult = await sendMessage(message) | |
expect(promiseResult).toEqual(2) | |
expect(chrome.runtime.sendMessage).toHaveBeenCalledWith( | |
message, | |
expect.any(Function), | |
) | |
}) | |
it("should resolve the promise if response success", (done) => { | |
const message: Message = { type: "rating", subType: "get" } | |
const response: MessageResponse = { statusCode: 200, data: 2 } | |
const jestChrome = chrome as any as JestChrome | |
jestChrome.runtime.sendMessage.mockImplementation( | |
(_message: any, callback: any) => { | |
return callback(response) | |
}, | |
) | |
sendMessage(message).then((data) => { | |
expect(data).toBe(2) | |
done() | |
}) | |
}) | |
it("should reject the promise if response fails", (done) => { | |
const message: Message = { type: "rating", subType: "get" } | |
const response: MessageResponse = { | |
statusCode: 500, | |
data: "background script error", | |
} | |
const jestChrome = chrome as any as JestChrome | |
jestChrome.runtime.sendMessage.mockImplementation( | |
(_message: any, callback: any) => { | |
return callback(response) | |
}, | |
) | |
sendMessage(message).catch((error) => { | |
expect(error).toBe("background script error") | |
done() | |
}) | |
}) | |
}) |
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