Question

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

 46  15103  46
1 Jan 1970

Solution

 42

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.

2018-10-03

Solution

 31

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}`,
  }, 
}
2020-04-21