gpt4 book ai didi

typescript - React Native with Typescript and Jest 在 0.57 更新 : Couldn't find preset "module:metro-react-native-babel-preset" relative to directory 后被破坏

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:51 32 4
gpt4 key购买 nike

如果您在新的 React 版本 0.57 和 TypeScript 中将测试与 Jest 和 Enzyme 集成,它们将无法工作。以下是重现的步骤:

创建一个新的 React Native 项目:

react-native init MyApp -package "com.my.app" --template typescript && node MyApp/setup.js

安装所有 Jest 和 Enzyne 相关包:

npm install --save-dev react-dom enzyme enzyme-react-adapter-16 jest-fetch-mock ts-jest

添加jest配置:

"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache",
"setupFiles": [
"./tests/setup.js"
]
}

添加文件 tests/setup.js 并包含以下配置:

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { NativeModules } from "react-native";

global.fetch = require("jest-fetch-mock"); // eslint-disable-line no-undef
jest.mock("react-native-config");
Enzyme.configure({ adapter: new Adapter() });

最后但同样重要的是添加一个基本测试 (App.test.tsx) 来检查 Jest 和 Enzyme 是否工作:

import React from "react";
import { shallow } from "enzyme";
import { View } from "react-native";
import App from "./App";

const createTestProps = props => ({
...props
});

describe("App", () => {
describe("rendering", () => {
let wrapper;
let props;
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<App {...props} />);
});

it("should render a <View />", () => {
expect(wrapper.find(View)).toHaveLength(1);
});
});
});

如果您现在尝试运行测试,您收到的错误消息是:

 FAIL  app/App.test.tsx
● Test suite failed to run

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "<Directory"

编辑

这好像和Babel有关

最佳答案

我在这个问题中找到了答案:https://github.com/facebook/metro/issues/242#issuecomment-421139247

基本上,将其添加到 package.json 中的 Jest 部分:

"transform": { "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" }

关于typescript - React Native with Typescript and Jest 在 0.57 更新 : Couldn't find preset "module:metro-react-native-babel-preset" relative to directory 后被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343699/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com