React Native with Typescript and Jest is broken after 0.57 Update: Couldn't find preset “module:metro-react-native-babel-preset” relative to directory

  • A+
Category:Languages

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" 

Edit

It seems like this has something to do with Babel.

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: