[英]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?是否可以将 Jest 与多个预设一起使用,比如 jsdom 和 react-native?
I'd like to test a React component that can work both on Web and in a React Native environment.我想测试一个可以在 Web 和 React Native 环境中工作的 React 组件。 The problem is that the component may use either React Native libraries or some document's methods.
问题是该组件可能使用 React Native 库或某些文档的方法。
When I run some tests, jest replies:当我运行一些测试时,jest 回复:
Cannot find module 'NetInfo' from 'react-native-implementation.js'
无法从“react-native-implementation.js”中找到模块“NetInfo”
When I try to add当我尝试添加
"jest": {
"preset": "react-native"
}
to package.json, I get:到 package.json,我得到:
ReferenceError: window is not defined
参考错误:窗口未定义
Presets are just plain Javascript objects, so in many circumstances you may simply merge them.预设只是普通的 Javascript 对象,因此在许多情况下您可以简单地合并它们。 For example, that's how I'm enabling
ts-jest
and jest-puppeteer
simultaneously:例如,这就是我同时启用
ts-jest
和jest-puppeteer
:
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.如果某些选项不能像这样“合并”,只需手动处理这些情况。
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}`,
},
}
For people that are looking for one preset plus typeScript对于正在寻找一种预设和 typeScript 的人
const { defaults: tsjPreset } = require('ts-jest/presets')
module.exports = merge.recursive(ts_preset, puppeteer_preset, {
preset: 'Your_Preset',
transform: tsjPreset.transform,
},
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.