Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Jest with multiple presets at the same time?

Is it possible to use Jest with multiple presets, say jsdom and react-native?

I'd like to test a React component that can work both on Web and in a React Native environment. The problem is that the component may use either React Native libraries or some document's methods.

When I run some tests, jest replies:

Cannot find module 'NetInfo' from 'react-native-implementation.js'

When I try to add

"jest": {   "preset": "react-native" } 

to package.json, I get:

ReferenceError: window is not defined

like image 900
Davide Briani Avatar asked Jun 23 '18 15:06

Davide Briani


2 Answers

Presets are just plain Javascript objects, so in many circumstances you may simply merge them. For example, that's how I'm enabling ts-jest and jest-puppeteer simultaneously:

const merge = require('merge') const ts_preset = require('ts-jest/jest-preset') const puppeteer_preset = require('jest-puppeteer/jest-preset')  module.exports = merge.recursive(ts_preset, puppeteer_preset, {     globals: {         test_url: `http://${process.env.HOST || '127.0.0.1'}:${process.env.PORT || 3000}`,     }, }) 

If there are certain options that can't be 'merged' like that, just handle these cases manually.

like image 108
Ilya Semenov Avatar answered Oct 04 '22 14:10

Ilya Semenov


Along these same lines, you can do this with the spread operator:

 const tsPreset = require('ts-jest/jest-preset') const puppeteerPreset = require('jest-puppeteer/jest-preset')  module.exports = {   ...tsPreset,   ...puppeteerPreset,   globals: {     test_url: `http://${process.env.HOST||'127.0.0.1'}:${process.env.PORT||3000}`,   },  } 
like image 22
Justin Dalrymple Avatar answered Oct 04 '22 15:10

Justin Dalrymple