I have a React Native application. I want to add unit tests with Jest. When I run yarn test
, I get the following error:
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 | });
Here's my 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 />
);
};
Here's what I have in my App.test.tsx
:
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();
});
});
And, here's my 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",
],
};