简体   繁体   中英

flatMap doesn't work in yarn test javascript

I have some code in a component method of mine using flatMap . The code works just fine in the browser, but the flatMap method isn't there when running the code using yarn test . Has anyone ever seen something like this before?

● Click Events › should copy table data

TypeError: children.map(...).flatMap is not a function

  181 |     const dataKeys = children
  182 |       .map(({ $: { data: dataKey } }) => dataKey)
> 183 |       .flatMap(k => k.split(LEVEL_DELIMITER));
      |        ^

EDIT - reproducible example: created a CRA base and added this simple test:

it('can flatMap', () => {
    [1, 2, 3, 4].flatMap(x => [x * 2]);
});

got the same error:

 FAIL  src/App.test.js
● can flatMap

TypeError: [1,2,3,4].flatMap is not a function

  at Object.<anonymous>.it (src/App.test.js:12:16)
      at new Promise (<anonymous>)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)

✓ renders without crashing (4ms)
✕ can flatMap

A coworker of mine found the solution. Apparently flatMap isn't supported by Node.js:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#Browser_compatibility


flatMap is now supported in node 11+ as said below, see the same link.

For what it is worth, using a react polyfill package also worked for me. I can control my own local environment, but the build system I have to work with is more restricted and used by multiple teams.

npm package: react-app-polyfill

Usage:

// setupTests.js (jest)
// Using ie9 polyfills as the "kitchen sink" of polyfills
import 'react-app-polyfill/ie9';
import 'react-app-polyfill/stable';

This works for Node v10.16.0, what I have currently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM