Reputation: 114757
I'm stuck with a jest test setup. I want to test some client side code, an electron preload script, to be precise and want to use rewire to test methods that are not exported.
The script under test depends on a another script that accesses window.navigator
. I can require
the test script but it fails with a ReferenceError: navigator is not defined
error on the first line in dom.js
when I use rewire
instead.
Here is a minimal setup that shows the error. I do not use a jest config as it defaults to the jsdom
test enviroment.
dom.js
console.log('during rewire:', global.navigator) // <-- prints undefined
console.log('The added property:', global.FOO) // <-- prints undefined
const userAgent = navigator.userAgent; // <-- fails.
index.js
const myDom = require('./dom.js');
module.exports = {
doSomething: () => {}
}
index.spec.js
const rewire = require('rewire');
describe('Basic test', () => {
it('exports a function', () => {
global.FOO = 'Bar'
console.log('before rewire:', global.navigator) // prints Navigator {}
console.log('The added property:', global.FOO) // prints Bar
// const main = require('.') // <-- works with require
const main = rewire('.') // <-- but fails with rewire
expect(typeof main.doSomething).toBe('function');
})
})
It looks as if rewire
uses a different global
, one that does not have the jsdom
environment anymore (or not yet?) (like global.window.navigator
or global.navigator
).
Any help is highly appreciated, usually I find solutions for almost all problems on google but this time, I'm lost.
To reproduce, copy the three files to a folder, then do npm init
, npm install jest rewire
, npx jest
.
Upvotes: 6
Views: 4532