我在测试react-native-vector-icons
时运行Jest
时遇到问题。
错误:
TypeError: Cannot read property 'default' of undefined
14 | test("second step register render correctly", () => {
15 | // @ts-ignore
> 16 | const wrapper = mount<SecondStepRegisterScreenImpl>(<SecondStepRegisterScreenImpl navigation={{}}/>)
| ^
17 | wrapper.render()
18 |
19 | expect(wrapper.find(SafeAreaView)).toExist()
at new Icon (node_modules/react-native-vector-icons/lib/create-icon-set.js:42:399)
at constructClassInstance (node_modules/react-dom/cjs/react-dom.development.js:11361:18)
at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:14687:5)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:15644:16)
首先,我使用带有ignite-bowser
模板的react-native模板,该模板将typescript用于react-native。参考:infinitered/ignite-bowser
使用我的Jest
配置: “玩笑预置-点燃”预置:infinitered/jest-preset-ignite
module.exports = {
preset: "jest-preset-ignite",
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!(jest-)?react-native|react-native|react-navigation|@react-navigation|@storybook|@react-native-community|@expo)"
],
setupFilesAfterEnv: [
"<rootDir>/test/setup-enzyme.ts"
],
moduleNameMapper: {
"^lodash-es$": "lodash"
}
};
我试图像这样模拟react-native-vector-icons
包:
jest.mock("react-native-vector-icons")
但没有结果。
我做错了吗?
答案 0 :(得分:0)
我想出了通过修改最好的预处理器来解决的问题。
从本机问题开始:
创建一个包含jest预处理程序代码的文件(例如:jest-preprocessor.js):
/**
* Your own [temporary?] transform for React Native
*/
const generate = require('@babel/generator').default
const transformer = require('metro-react-native-babel-transformer')
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction')
const metroBabelRegister = require('metro-babel-register')
metroBabelRegister([])
module.exports = {
process(src, file) {
const { ast } = transformer.transform({
filename: file,
options: {
ast: true,
dev: true,
enableBabelRuntime: false,
experimentalImportSupport: false,
hot: false,
inlineRequires: false,
minify: false,
platform: '',
projectRoot: '',
retainLines: true,
sourceType: 'unambiguous',
},
src,
plugins: metroBabelRegister.config.plugins,
})
return generate(
ast,
{
code: true,
comments: false,
compact: false,
filename: file,
retainLines: true,
sourceFileName: file,
sourceMaps: true,
},
src,
).code
},
getCacheKey: createCacheKeyFunction([
__filename,
require.resolve('metro-react-native-babel-transformer'),
require.resolve('@babel/core/package.json'),
]),
}
添加到您的Jest
配置中
transform: {
'^.+\\.js$': '<rootDir>/jest-preprocessor.js',
},