rewire icon indicating copy to clipboard operation
rewire copied to clipboard

instanceof doesn't work with Jest and rewire

Open georgezlei opened this issue 6 years ago • 2 comments

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

georgezlei avatar May 12 '19 04:05 georgezlei

I hit this same issue

robross0606 avatar Oct 30 '19 19:10 robross0606

I had the same issue, so I wrote jewire.

1

It's a niche library that clones objects and arrays at runtime solely for Jest purposes :D. Hope this helps someone out there.

nktnet1 avatar Oct 12 '23 10:10 nktnet1