benchmark.js icon indicating copy to clipboard operation
benchmark.js copied to clipboard

Usage with Jest

Open DJTB opened this issue 8 years ago • 8 comments

Attempting to run benchmark within Jest errors with:

 TypeError: Cannot read property 'parentNode' of undefined      
      at runScript (node_modules/benchmark/benchmark.js:664:27)

It appears that Benchmark believes it's inside a browser environment via supports.browser. If I hack that boolean to false everything runs happily.

Is there a way to force supports.browser to false in a config? Or is there a recommended approach for use within Jest tests?

DJTB avatar Jun 11 '17 15:06 DJTB

I'll treat this as a feature request for a more robust supports.browser check 😄

jdalton avatar Jun 11 '17 16:06 jdalton

Not entirely Benchmark's fault since Jest defaults to a jsdom environment :smile:

Benchmark works as expected when the environment is set to node at the top of a test file.

/**
 * @jest-environment node
 */

DJTB avatar Jun 11 '17 21:06 DJTB

I have the same error on repl.it: https://repl.it/Kh98/1

franky47 avatar Sep 05 '17 10:09 franky47

I have the same error as well in Jest.

wongjiahau avatar Oct 29 '17 13:10 wongjiahau

Same error in CodeSandbox: https://codesandbox.io/s/30l42zjjv1

hexpunk avatar Mar 27 '18 17:03 hexpunk

I could get it to work if I set the testEnvironment to node in the jest.config.js. Therefore, we wouldn't need to set the @jest-environment node comment in every file.

Maybe someone can confirm :innocent:?

module.exports = {
  testEnvironment: 'node',
  ...
};

PhilippeMorier avatar Oct 21 '19 13:10 PhilippeMorier

What if I have code that needs to run in jsdom - is there a way to hack support.browser to be false? :)

wongrichardalex avatar Nov 09 '20 15:11 wongrichardalex

There's a jest reporter now, https://github.com/pckhoi/jest-bench - just wondering how to use it to create a baseline...

Stephanemw avatar Feb 25 '23 17:02 Stephanemw