instanceof doesn't work with Jest and rewire
instanceof doesn't work in Jest when being used on an object returned from Rewire. Please check out codes below.
file rewired.test.js
const rewire = require('rewire')
const code = rewire('./rewired')
const here = {}
const there = code.__get__('another')
test('test', () => {
expect(here instanceof Object).toBeTruthy()
expect(there instanceof Object).toBeTruthy()
})
file rewired.js
const another = {}
It turns out that Jest uses new vm context for each test to simulate a new browser window. That caused all builtins such as Object and Array are created again. And for some reason, the objects created by rewire are cross-context and based on another Object. So the instanceof test can never have correct result.
Here is an example.
const vm = require('vm')
const code = `
const rewire = require("rewire");
const code = rewire("./rewired")
const obj = code.__get__("Object");
console.log(obj === Object);
`;
eval(code)
vm.runInNewContext(code, {require, console})
The result is
true
false
I hit this same issue
I had the same issue, so I wrote jewire.
It's a niche library that clones objects and arrays at runtime solely for Jest purposes :D. Hope this helps someone out there.