extend-chrome / jest-chrome Goto Github PK
View Code? Open in Web Editor NEWA complete mock of the Chrome API for Chrome extensions for use with Jest.
License: MIT License
A complete mock of the Chrome API for Chrome extensions for use with Jest.
License: MIT License
Jest-chrome mozilla/webextension-polyfill jest.setup
When using jest-chrome with webextension-polyfill, the browser namespace property returns undefined (For example: browser.runtime.sendMessage).
What's strange is that browser is defined and even browser.runtime, but then I look for sendMessage and it returns undefined.
I've already added browser to the global object in my jest.setup file, but I didn't know what else to do to get the namespace to be defined
I expect the browser namespace properties to be defined.
The browser namespace property is undefined.
Hey,
First of all, thank you for an awesome extension!
Second, please see this unanswered question.
It's more of a quality of life thing than an actual issue (I hate to use any
in TS).
Figured since the code works just fine there must be a less risky way to tell TS it's fine.
The assertion is from jest-extended
TL;DR
I'm trying to make TS to accept the following line but without casting to any
:
expect(chrome.tabs.update).toHaveBeenCalledAfter(chrome.cookies.set as any);
Thanks!
With Manifest v3, when callbacks are not provided, functions return promises instead.
Return promises instead of using the callback.
Sticking with callbacks. This is ugly!
Manifest v2 is EOL and the Chrome store has already stopped accepting new manifest v2 submissions.
jest-chrome tabs.remove
The types for chrome.tabs
is missing the remove
property.
Write chrome.tabs.remove
in a typescript jest test after installing this library according to the readme
Typescript should not produce an error when using chrome.tabs.remove
Sure enough, there is no exported move
mock in the types file
I updated my chrome extension to manifest v3, also I see that declarativeWebRequest is deprecated, and the recomendation is tu use declarativeNetRequest namespace which is not supported on jest-chrome.
Thanks
jest-chrome is not work for jest 29
I have jest 29.3.1 and i try to use jest-chrome to test my browser extension https://github.com/translate-tools/linguist
But i can't even install jest-chrome, because its packages.json
requires a jest version jest@"^26.0.1 || ^27.0.0"
npm i -D [email protected]
npm i -D jest-chrome
Packages installed successfully
We got an error about incompatible versions
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/jest
npm ERR! dev jest@"^29.3.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer jest@"^26.0.1 || ^27.0.0" from [email protected]
npm ERR! node_modules/jest-chrome
npm ERR! dev jest-chrome@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
We're migrating this library over to a new and more aptly named organization: extend-chrome!
Describe the bug
I just got the package updated from v0.5.1 to v0.5.2 and I see this error now:
Cannot find module './createHandler' from 'index.cjs.js'
To Reproduce
Steps to reproduce the behavior:
issue-jest-chrome
npm t
Expected behavior
All tests must pass without any errors and coverage 100%.
Desktop (please complete the following information):
Additional context
Add any other context about the problem here.
Since Chrome v102 we have chrome.storage.session
- https://developer.chrome.com/docs/extensions/reference/storage/#storage-areas
I'm trying to test that a function is registering events, but it seem that this use case was not considered. The readme helpfully demoes the testing of events but not in the same way.
addListener
should be mocked so that I can expect
calls on it
When using Manifest V3, chrome.browserAction
(and pageAction
) is replaced with chrome.action
. It looks like this is not supported by jest-chrome
currently.
Support for chrome.action
as alternative to chrome.browserAction
.
We use Jest 28 in our project. When installing jest-chrome, we get the following error:
~> npm i jest-chrome -save-dev --save-exact
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/jest
npm ERR! dev jest@"28.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer jest@"^26.0.1 || ^27.0.0" from [email protected]
npm ERR! node_modules/jest-chrome
npm ERR! dev jest-chrome@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
I tried to install with --force
and it passed but then there is another issue.
When I added './jest.setup.js'
as the last entry in my setupFilesAfterEnv
and the jest.setup.js
file like that:
const chromeMock = require('jest-chrome');
Object.assign(global, chromeMock);
console.log(chromeMock);
and I run my tests, it logs an empty object instead of Chrome mock:
console.log
{ chrome: {} }
at Object.<anonymous> (jest.setup.js:5:9)
And tests fail. They expect chrome.storage API but it doesn't exist.
Am I doing something wrong or Jest 28 is not supported yet?
jest-chrome chrome.storage.local.onChanged.addListener
chrome.storage.local.onChanged is undefined
TypeError: Cannot read property 'addListener' of undefined
166 | };
167 |
> 168 | chrome.storage.local.onChanged.addListener(
import { renderHook, act } from "@testing-library/react";
import { usePopup } from "../usePopup";
import { chrome } from "jest-chrome";
describe("usePopupRecordBytes", () => {
it("test", async () => {
chrome.storage.local.onChanged.addListener(
(changes: {
[key: string]: chrome.storage.StorageChange;
}) => {
console.log('foo')
};
);
expect(chrome.storage.local.onChanged.addListener).toHaveBeenCalledTimes(1);
});
});
chrome.storage.local.onChanged to be defined so that listeners can be added
When using webextension-polyfill
you have to declare chrome.runtime.id
as a string in jest.setup.js
, like for example chrome.runtime.id = 'test id'
if not you get the following error
Error: This script should only be loaded in a browser extension.
I'd like it if jest-chrome could add a random default string or just a hard coded value so I wouldn't have to remember to add this id.
The error message of this issue
Have set up Jest Chrome in an existing Vue project, and when I run the build the screen fills with 100s and 100s of lines the following:
ERROR in /Volumes/Data/Work/Current/.../node_modules/jest-chrome/types/jest-chrome.d.ts(6092,31):
6092:31 Namespace 'jest' has no exported member 'MockedFunction'.
6090 | * function(string result) {...};
6091 | */
> 6092 | export const getTitle: jest.MockedFunction<typeof chrome.pageAction.getTitle>
| ^
6093 | /**
6094 | * Gets the html document set as the popup for this page action.
6095 | *
ERROR in /Volumes/Data/Work/Current/.../node_modules/jest-chrome/types/jest-chrome.d.ts(6102,31):
6102:31 Namespace 'jest' has no exported member 'MockedFunction'.
6100 | * function(string result) {...};
6101 | */
> 6102 | export const getPopup: jest.MockedFunction<typeof chrome.pageAction.getPopup>
| ^
6103 | /**
6104 | * Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified.
6105 | *
ERROR in /Volumes/Data/Work/Current/.../node_modules/jest-chrome/types/jest-chrome.d.ts(6110,30):
6110:30 Namespace 'jest' has no exported member 'MockedFunction'.
6108 | * function() {...};
6109 | */
> 6110 | export const setIcon: jest.MockedFunction<typeof chrome.pageAction.setIcon>
| ^
6111 |
6112 | /** Fired when a page action icon is clicked. This event will not fire if the page action has a popup. */
6113 | export const onClicked: PageActionClickedEvent
Unsure. This is a Vue project around 18 months old.
Also just upgraded the Vue CLI to the latest copy of everything, which brought its own issues (I think the compiler / linting settings are more aggressive) โ not sure if they are connected.
Vue uses its own copy of Jest, but to be on the safe side, I installed Jest again as a peer dependency, but no luck.
The build compiles with no warnings.
See above.
The build still works, but the terminal is hosed with messages.
See copy/paste above
Can not use jest-chrome
with jest
v28, v29.
A release of current master
.
peerDependencies
field with current versionsProvide a factory for chrome.runtime.Port
.
Consider trying to test code that calls chrome.runtime.connect
:
const mockConnect = (extensionId?: string, connectInfo?: object) => {
const port: chrome.runtime.Port = {
name: connectionInfo?.name ?? 'name',
postMessage: jest.fn() as jest.MockedFunction<(message: any) => void>,
disconnect: jest.fn() as jest.MockedFunction<() => void>,
onDisconnect, // Event is non-trivial to fake!
onMessage, // another Event :(
};
return port;
};
chrome.runtime.connect.mockImplementation(mockConnect);
Creating a suitable mock implementation is quite arduous in typescript (Port
itself has onMessage
and onDisconnect
events, and they in turn have a bunch of their own methods that need to be mocked).
jest-chrome
already mocks a bunch of things like this, but only for the static functions in the Chrome API. It has the necessary machinery to make mocking events (and even schema-driven mocking) easy, but it neither applies that to things like Port
, nor does it expose functions like createEvent
.
jest-chrome should export a chromeMocks
like:
import { chromeMocks } from 'jest-chrome';
const port = new chromeMocks.runtime.Port();
chrome.runtime.connect.mockReturnValue(port);
codeUnderTest();
// Events on the Port mock are just as easy to use as `chrome.runtime.onMessage`.
const listenerSpy = jest.fn();
port.onMessage.addListener(listenerSpy);
i.e. try and finish the code in the mockConnect
code in the first section. It's very tedious.
A slightly different API than above, instead of factories that return Chrome types like Port
, use factories that correspond directly to the synchronous functions that would otherwise return types like Port
.
Instead of exposing a factory, jest-chrome could just expose its helpers like createEvent
. However, then you'd be exporting APIs that didn't just come from Chrome, and it would make the implementation brittle (since you'd have to support these functions for compatibility going-forwards).
TBH though, just exporting the Event fakes would help a lot with users being able to mock things like Port
.
I think something like jest-mock-extended
would make mocking these types much less tedious. It can already do a lot of what jest-chrome does (but not the Event fakes).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.