jhnns / rewire

Easy monkey-patching for node.js unit tests
MIT License
3.08k stars 128 forks source link

instanceof doesn't work with Jest and rewire #164

Open georgezlei opened 5 years ago

georgezlei commented 5 years ago

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
robross0606 commented 5 years ago

I hit this same issue

nktnet1 commented 1 year ago

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.