sinon-chrome
sinon-chrome copied to clipboard
Usage with Jest - ReferenceError: chrome is not defined
I'm getting ReferenceError: chrome is not defined
when trying to use sinon-chrome
with Jest.
Can anyone help me get this working?
bump for this aswell.
@RobertJGabriel can you let me know if you find a fix? For now I'm just stubbing out chrome using jest.fn()
but would rather get this working of course!
You can extend the Jest behavior by providing a test setup file. You can find everything about this in their documentation. Simply apply the sinon-chrome module to this.global.chrome in the setup file.
Any updates on this? I am unsure what @marcus-sa meant, I am first time using any testing library.
I think @marcus-sa was referring to something like this:
import chrome from 'sinon-chrome/extensions'
import browser from 'sinon-chrome/webextensions'
describe('your test', () => {
beforeAll(() => {
global.chrome = chrome
global.browser = browser
})
it('should ...', () => {
// ..
})
afterAll(() => {
chrome.flush()
browser.flush()
})
})
However, this was not my issue. My issue is that I am using webextension-polyfill
in most of my classes for the extension project and I couldn't test a single one, because chrome
is not defined.
Just importing the class would throw such error, without any other needs.
How I managed to fix this? - Easy.
Below all your module imports, mock the polyfill with this package.
jest.mock('webextension-polyfill', () => require('sinon-chrome/webextensions'))
Personally had to
import * as chrome from "sinon-chrome";
before I could use the module with typescript
I was getting the same error so I had to declare window.chrome = chrome
before including my .js file to be tested.
const chrome = require('sinon-chrome');
window.chrome = chrome;
require('../src/check');
Thanks everyone. I'm thinking about submitting a PR to add these to the docs
Anyone else running into this today, I solved by
// jest.config.ts
import { pathsToModuleNameMapper, type JestConfigWithTsJest } from 'ts-jest';
const chrome = require('sinon-chrome/extensions');
const config: JestConfigWithTsJest = {
extensionsToTreatAsEsm: ['.ts'],
verbose: true,
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
transform: {
'^.+\\.(ts)?$': ['ts-jest', { useESM: true }],
},
testPathIgnorePatterns: ['./dist'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */),
// setupFilesAfterEnv: ['./jest.setup.js'],
globals: {
chrome,
},
};
export default config;