jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.15k stars 6.45k forks source link

Jest blow up when used with `export * from 'something'` #879

Closed tals closed 8 years ago

tals commented 8 years ago

When a Jest test imports a module that includes:

// src/__tests__/test.js
import '../index.js'
// src/index.js
export * from './something';
// src/something.js
export function dog() { console.log('hello this is dog'); }

Jest will blow up with

 FAIL  __tests__/test.js
Runtime Error
TypeError: Cannot redefine property: __esModule
    at Function.defineProperty (native)

The reason for this is how Jest's mocking is slightly inaccurate, and this interacts badly with Babel's module system.

A Babel ES6 module defines:

// build/stuff.js
Object.defineProperty(exports, "__esModule", {
  value: true
});

exports.dog = dog;
function dog() {
  console.log('this is dog');
}

export * from './stuff' is implemented as:

Object.keys(_stuff).forEach(function (key) {
  if (key === "default") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _stuff[key];
    }
  });
});

In Node, this is fine, because Object.keys(_stuff) return ["dog"]

However, the Jest module mocks are inaccurate -- when you're collecting the object props, you don't keep track if it's enumerable.

You first get the slots with getSlots():

> getSlots(component)
< ["__esModule", "xxx", "dog"]

But collecting the metadata with getMetadata() only considers the value, and ignores property descriptors. So for __esModule, we get:

> mockMetadata.members.__esModule
Object
    type: "constant"
    value: true

and then gets placed in the mock. At this point, Object.keys(_stuff) returns ["__esModule", "dog"], which causes the redefine error.

tals commented 8 years ago

wops, duplicate

bodawei commented 4 years ago

@tals What was it a duplicate of? I haven't yet found another issue reporting the same problem. (nice detailed report, btw)

tals commented 4 years ago

This guy lol https://github.com/facebook/jest/issues/880

ty! 😇

bodawei commented 4 years ago

@tals Thanks. Looks like a very hard to kill bug. :-)

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.