我有一个React Native应用程序。我想用Jest添加单元测试。当我运行yarn test
时,我得到以下错误:
FAIL ./App.test.tsx
● app › can render snapshot
ReferenceError: React is not defined
5 | describe("app", () => {
6 | it("can render snapshot", () => {
> 7 | const tree = renderer.create(<App />);
| ^
8 | expect(tree).toMatchSnapshot();
9 | });
10 | });
下面是我的App.tsx
:
import React from "react";
import Amplify from "aws-amplify";
import awsmobile from "./src/aws-exports";
import AppContainer from "./src/navigation/index";
Amplify.configure(awsmobile);
const App = () => {
return (
<AppContainer />
);
};
下面是我的App.test.tsx
中的内容:
import "react-native";
import React from "react";
import renderer from "react-test-renderer";
import App from "./App";
describe("app", () => {
it("can render snapshot", () => {
const tree = renderer.create(<App />);
expect(tree).toMatchSnapshot();
});
});
下面是我的jest.config.js
:
// jest.config.js
const {defaults: tsjPreset} = require("ts-jest/presets");
module.exports = {
...tsjPreset,
preset: "react-native",
transform: {
...tsjPreset.transform,
"\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
},
globals: {
"ts-jest": {
babelConfig: true,
},
},
// This is the only part which you can keep
// from the above linked tutorial's config:
cacheDirectory: ".jest/cache",
moduleFileExtensions: [
"ios.js",
"native.js",
"js",
"json",
"jsx",
"node",
"ios.ts",
"native.ts",
"ts",
"tsx",
],
};
更新日期:
下面是我的babel.config.js
:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
我按照指示here操作。
1条答案
按热度按时间uurv41yg1#
对我来说,设置下一个配置修复了这个问题:
jest.config.js
来源:https://github.com/facebook/jest/issues/11591#issuecomment-899508417