Giter Club home page Giter Club logo

jest-chrome's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

jest-chrome's Issues

How to make jest-chrome work with webextension-polyfill

Google search terms

Jest-chrome mozilla/webextension-polyfill jest.setup

Describe the bug

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

How do we reproduce?

See a repo here

Expected behavior

I expect the browser namespace properties to be defined.

Actual behavior

The browser namespace property is undefined.

Screenshots

Jest-chrome-browser-pollyfill

Please complete the following information:

  • Library Version: 0.7.0
  • Operating System: Linux Mint
  • Browser: chrome Version 87.0.4280.88
  • Node Version: v14.8.0

Getting from MockedFunction to Mock

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!

Manifest v3 Promise Support

Is your feature request related to a problem? Please describe.

With Manifest v3, when callbacks are not provided, functions return promises instead.

Describe the solution you'd like

Return promises instead of using the callback.

Describe alternatives you've considered

Sticking with callbacks. This is ugly!

Additional context

Manifest v2 is EOL and the Chrome store has already stopped accepting new manifest v2 submissions.

Type is missing for chrome.tabs.remove method

Google search terms

jest-chrome tabs.remove

Describe the bug

The types for chrome.tabs is missing the remove property.

How do we reproduce?

Write chrome.tabs.remove in a typescript jest test after installing this library according to the readme

Expected behavior

Typescript should not produce an error when using chrome.tabs.remove

Screenshots

CleanShot 2022-03-07 at 19 49 16

Please complete the following information:

  • Library Version: @0.7.2
  • Operating System: MacOS 11.6
  • Browser: Chrome 98.0.4758.109 (Official Build) (x86_64)
  • Node Version: v14.19.0

Additional Info

Sure enough, there is no exported move mock in the types file

Jest version 29 is not supported

Google search terms

jest-chrome is not work for jest 29

Describe the bug

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"

How do we reproduce?

Expected behavior

Packages installed successfully

Actual behavior

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.

Screenshots

Please complete the following information:

  • Library Version: 0.8.0
  • Operating System: ubuntu
  • Browser: firefox
  • Node Version: v14.18.1

Additional context

Migrate to @extend-chrome

We're migrating this library over to a new and more aptly named organization: extend-chrome!

TODO

  1. Catalog bumble-org dependencies
  2. Update README.md
  3. Update package.json
  4. Transfer GitHub repo
  5. Transfer NPM package

Error: Cannot find module './createHandler' from 'index.cjs.js'

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:

  1. Clone this repo
  2. Checkout to the branch issue-jest-chrome
  3. Run tests npm t
  4. See error

Expected behavior
All tests must pass without any errors and coverage 100%.

Desktop (please complete the following information):

  • OS: MacOS Catalina 10.15.4
  • Node.js: 12.16.1

Additional context
Add any other context about the problem here.

Type definitions not working with chrome.tabs.query

TS linter is throwing an error when trying to mock chrome.tabs.query

image

I think this is happening because chrome is overloading the query function name in their type definition:

image

But the jest definition only has one definition for the mocked function:

image

`expect(chrome.runtime.onMessage.addListener).toHaveBeenCalled()`

Is your feature request related to a problem? Please describe.

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.

Describe the solution you'd like

addListener should be mocked so that I can expect calls on it

Jest 28 support

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?

Cannot read property 'addListener' of undefined chrome.storage.local.onChanged.addListener

Google search terms

jest-chrome chrome.storage.local.onChanged.addListener

Describe the bug

chrome.storage.local.onChanged is undefined

TypeError: Cannot read property 'addListener' of undefined

      166 |         };
      167 |
    > 168 |         chrome.storage.local.onChanged.addListener(

How do we reproduce?

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);
    });
});

Expected behavior

chrome.storage.local.onChanged to be defined so that listeners can be added

Actual behavior

Screenshots

image

Please complete the following information:

  • Library Version: 0.8.0
  • Operating System: macOS
  • Browser: Chrome
  • Node Version: v14.21.2

Additional context

chrome.runtime.id needs to be a string when using webextension-polyfill

Is your feature request related to a problem? Please describe.

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.

Describe the solution you'd like

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.

Vue CLI: Namespace 'jest' has no exported member 'MockedFunction' during build

Google search terms

The error message of this issue

Describe the bug

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

How do we reproduce?

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.

Expected behavior

The build compiles with no warnings.

Actual behavior

See above.

The build still works, but the terminal is hosed with messages.

Screenshots

See copy/paste above

Please complete the following information:

  • Library Version: 0.7.0
  • Operating System: OSX
  • Browser: Chrome
  • Node Version: 12

Additional context

Release v0.8.0

Is your feature request related to a problem? Please describe.

Can not use jest-chrome with jest v28, v29.

Describe the solution you'd like

A release of current master.

Describe alternatives you've considered

  • Create a PR reintroducing the peerDependencies field with current versions
  • Fork the package
  • Stop using the package
  • Change package manager configuration to ignore peerDependencies

Additional context

Export mock factory functions for Chrome types

Is your feature request related to a problem? Please describe.

Provide 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.

Describe the solution you'd like

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);

Describe alternatives you've considered

Manually mock

i.e. try and finish the code in the mockConnect code in the first section. It's very tedious.

Call-oriented API

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.

Expose internal helpers

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.

Other mocking packages

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).

Additional context

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.