Jest是否可以同时使用多个预设?

问题描述:

是否可以将Jest与多个预设(例如jsdom和react-native)一起使用?

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

我想测试一个既可以在Web上也可以在React Native环境中工作的React组件.问题在于该组件可能使用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:

从'react-native-implementation.js'中找不到模块'NetInfo'

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

当我尝试添加

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

到package.json,我得到:

to package.json, I get:

ReferenceError:未定义窗口

ReferenceError: window is not defined

预设只是普通的Javascript对象,因此在许多情况下,您可以简单地将它们合并.例如,这就是我同时启用ts-jestjest-puppeteer的方式:

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.