Anyone has used vitest to unit test a chrome extension?

373 views
Skip to first unread message

Patricio Gonzalez

unread,
Aug 17, 2023, 9:38:46 AM8/17/23
to Chromium Extensions
I'm stuck defining the chrome variable as a global to mock it. Any have some experience with this?




Peter Bloomfield

unread,
Aug 17, 2023, 10:15:31 AM8/17/23
to Chromium Extensions, Patricio Gonzalez
We use Jest rather than vitest, but hopefully something similar will work.

We wrote a file which explicitly declares mocks for some of the Chrome API functions we use most often, and injects them into the global namespace:

const chrome = {
  alarms: {
    onAlarm: { addListener: jest.fn },
    get: jest.fn(),
    create: jest.fn(),
  },

  // ...
};

globalThis.chrome = chrome;
```

In our Jest configuration, that file is specified in the `setupFilesAfterEnv` property. That means it gets included automatically when running tests.

Each test or test suite which actually uses a mock has to set up its own expectations on each mock, and then the mocks typically have to be reset or cleared afterwards. It can be quite cumbersome, but it's been pretty effective so far.

Patricio Gonzalez

unread,
Aug 22, 2023, 2:15:22 PM8/22/23
to Chromium Extensions, Peter Bloomfield, Patricio Gonzalez
Thank you Peter, very useful
 If anyone helps, this is the way how is working for me with Vitest

in vite.config.ts. Add the setupFiles

test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/tests/setup.ts',
},

and in that setup.ts  file override the chrome as a global stub

beforeAll(() => {
const chromeMock = {
tabs: {
query: vi.fn((_queryInfo, callback) => {
callback([{ id: 123 }]);
}),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
create: vi.fn(({ url }: { url: string }) => {}),
},
sidePanel: {
open: vi.fn(),
},
commands: {
getAll: vi.fn(() => {
return [];
}),
},
};

vi.stubGlobal('chrome', chromeMock);
});

John Gordon

unread,
11:04 AM (3 hours ago) 11:04 AM
to Chromium Extensions, Patricio Gonzalez, Peter Bloomfield
This post is a little old, but I found the https://www.npmjs.com/package/sinon-chrome package that I used in my vitest to mock things out. I haven't used it extensively, but it seems to do what I need without having to mock out the whole chrome api.

Anyone else using this or another mock for Chrome?

Reply all
Reply to author
Forward
0 new messages