If you integrate test with Jest and Enzyme in the new React Version 0.57 and TypeScript, they won't work. Here are the steps to reproduce:
Create a new React Native project:
react-native init MyApp -package "com.my.app" --template typescript && node MyApp/setup.js
Install all Jest and Enzyne related packages:
npm install --save-dev react-dom enzyme enzyme-react-adapter-16 jest-fetch-mock ts-jest
Add the jest configuration:
"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"
]
}
Add a file tests/setup.js
and include the following configuration:
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() });
Last but not least add a basic test (App.test.tsx) to check if Jest and Enzyme work:
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);
});
});
});
If you now try to run the test, the error message you get is:
FAIL app/App.test.tsx
● Test suite failed to run
Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "<Directory"
It seems like this has something to do with Babel.
I found the answer here in this issue: https://github.com/facebook/metro/issues/242#issuecomment-421139247
Basically, add this to your Jest section in package.json
:
"transform": { "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" }
had a similar issue when upgrading to 0.57, my package.json
still contained an entry for babel-preset-react-native
(which is now deprecated in favor of metro-react-native-babel-preset
). All I had to do was
yarn remove babel-preset-react-native
and then
yarn add metro-react-native-babel-preset --dev
Lastly, make sure you change your .babelrc
from
{
"presets": ["react-native"]
}
to
{
"presets": ["module:metro-react-native-babel-preset"]
}
More info can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With