I am writing a simple test using react-native-testing-library (my first steps with that library) in my react native expo app. But I am getting a confused error coming from somewhere inside react-native code base itself. Either there is something wrong with my code or there is a bug with react-native-testing-library npm library.
Here is simple jest test:
describe("AppTitle", () => {
it("should display applicaton title", () => {
const { getByText } = render(<AppTitle />);
expect(getByText('App Name')).toBeTruthy();
});
});
And here is the simple <AppTitle /> component (just a View and a Text)
export const AppTitle = () => {
return (
<View>
<Text>App Name</Text>
</View>
);
};
But I am getting this error when I run the test:
...../Utilities/warnOnce.js:15
const warnedKeys: {[string]: boolean} = {};
^^^^^^^^^^
SyntaxError: Missing initializer in const declaration
at ScriptTransformer.transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native-implementation.js:14:18)
...
This is a simple and straight forward template. Any help from a react-native + react-native-testing-library would be appreciate.
react: 16.8.3
react-native: fork from Expo 33
jest-expo: "^33.0.2"
react-native-testing-library": "1.7.0"
I resolved this added "preset": "react-native" in jest.config.js file
I am using expo in my project. I have same issue. i forgot to add "preset": "jest-expo" to package.json. i added then the problem solved.
"jest": { "preset": "jest-expo" },
Related
I'm using #testing-library/react-native but when I try to test a component that has any rneui: 4.0.0-rc-6 components I get several errors:
The first now was
Details:
/Users/ep/myProject/node_modules/#rneui/themed/dist/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { AirbnbRatingDefault as AirbnbRating, } from './AirbnbRating';
I was able to solve this by adding #rneui to transformIgnorePatterns inside package.json
but now Im getting
ReferenceError: getCacheKeyFunction is not defined
at _default (node_modules/#jest/create-cache-key-function/build/index.js:76:3)
at Object.<anonymous> (node_modules/jest-expo/src/preset/assetFileTransformer.js:5:16)
Any ideas on how to solve this?
(my component is using Icon and Input from rneui)
I was able to solve these by mocking the components
const MockInput = () => (<View />)
jest.mock('#rneui/themed', () => ({
// AirbnbRating: jest.fn()
Input: jest.fn(() => <MockInput />),
Icon: jest.fn(() => <></>)
}))
I am unable to resolve this, and gone through the below document
https://www.npmjs.com/package/react-native-tab-view
Also I did not come across any document regarding this issue. I have used the same sample code mentioned in the above link.
import * as React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function TabViewExample() {
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
const styles = StyleSheet.create({
scene: {
flex: 1,
},
});
How do I resolve this?
npm version is 6.14.4
React-native version is 0.62.2
react-native-tab-view: "^2.15.0"
react-native-gesture-handler: "^1.6.1"
react-native-reanimated: "^1.10.1"
#react-native-community/masked-view: "^0.1.10"
run npm i react-native-gesture-handler#1.7.0. Clear cache and build again.
Linking is not required from version 0.59 as it auto links the dependencies.
Upgrade the react-native-gesture-handler to 1.7.0
I encountered this error while working with #react-navigation/drawer and this worked for me.
npm i react-native-reanimated
Add plugins: ['react-native-reanimated/plugin'], below presets in '<your_app_root_folder>/babel.config.js'.
Add import 'react-native-gesture-handler'; to the top of '<your_app_root_folder>/App.js'.
Reset the cache using npx react-native start --reset-cache.
In case this helps anyone out there working with Expo (Expo 46, react-native-reanimated 2.9.1): I had the same error on a development build after installing react-native-reanimated and couldn't figure out why, even though I did the steps shown:
expo install react-native-reanimated
Added plugins: ['react-native-reanimated/plugin'] to my babel.config.js
expo start --dev-client --clear
What ended up working for me was uninstalling my app and creating a new build with the new package.json and babel.config.js. To be fair, it might have worked by just reinstalling the original build, but I'm not trying to go back to having this error...
Use react-native link react-native-reanimated
And then following this link
https://github.com/software-mansion/react-native-reanimated/blob/master/Example/android/app/src/main/java/com/swmansion/reanimated/example/MainApplication.java
I'm getting this error after upgrading the Expo SDK version to 33:
ENOENT: no such file or directory, scandir '.\node_modules\native-base\Fonts'
Failed building JavaScript bundle.
Updating the Expo may have caused a conflict with the updated #expo/vector-icons. If the native-base module is deleted and is not reinstalled or the problem is not resolved,
rm -rf node_modules && yarn install && expo start
Expo loads fonts in a new way:
https://docs.expo.io/versions/latest/sdk/font/
The below examples are based on both the examples from native-base and the expo docs.
https://github.com/GeekyAnts/NativeBase
You may need to run this first:
expo install expo-font
Then, in your code:
import * as Font from 'expo-font'
and
export default class App extends React.Component {
async componentDidMount() {
await Font.loadAsync({
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
});
this.setState({ isReady: true });
}
// ...
}
Using the import path of native-base/Fonts/Roboto.ttf did not work for me but using a relative path like below worked:
await Font.loadAsync({
Roboto: require('../node_modules/native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('../node_modules/native-base/Fonts/Roboto_medium.ttf')
});
Here is a slightly more complete example:
export default class extends React.Component {
state = {
isReady: false,
};
async componentDidMount() {
await Font.loadAsync({
Roboto: require('../node_modules/native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('../node_modules/native-base/Fonts/Roboto_medium.ttf')
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return ( <AppLoading />);
}
return <Navigator />;
}
}
I just added TouchableOpacity to a component and the app is working fine, but my tests, using react-native-testing-library, fail to run:
● Test suite failed to run
TypeError: Cannot read property 'Direction' of undefined
at Object.Direction (node_modules/react-native-gesture-handler/Directions.js:3:39)
at Object.<anonymous> (node_modules/react-native-gesture-handler/GestureHandler.js:2:1)
I just removed and re-added react-native-gesture-handler with yarn, and ran pod install. Again, the app is working, but the tests fail to run.
I actually get the same error when using <Text onPress={() => onOptionPress(opt)} /> rather than TouchableOpacity.
component:
const SelectOptions = ({ field, dismissOverlay, onOptionPress }) => {
return (
<Overlay
isVisible
overlayStyle={styles.overlay}
height={"auto"}
onBackdropPress={dismissOverlay}
>
<View>
{field.options.map((opt, i) => (
<TouchableOpacity
style={styles.option}
key={i}
onPress={() => onOptionPress(opt)}
>
<Text>{opt}</Text>
</TouchableOpacity>
))}
</View>
</Overlay>
);
};
test:
describe("CardFormView", () => {
let wrapper, birthdayField;
beforeEach(() => {
wrapper = render(
<React.Fragment>
<CardFormView form={form} />
</React.Fragment>
);
birthdayField = wrapper.getByText("Add a Birthday Gift Card");
});
const message1 =
"...";
const message2 =
"...";
it("shows the options for a birthday card when clicked", () => {
fireEvent.press(birthdayField);
expect(wrapper.getByText(message1)).toBeDefined();
});
it("sets an option when clicked", () => {
fireEvent.press(birthdayField);
const firstOption = wrapper.getByText(message1);
fireEvent.press(firstOption);
expect(wrapper.queryByText(message2)).toBeNull();
expect(wrapper.getByText(message1)).toBeDefined();
});
});
This is because you are not mocking the react-navigation-gesture-handler
To use mock of react-navigation-gesture-handler you should add jestSetup.js from node_modules in jest.config.json or jest.config.js
setupFiles: [
"./node_modules/react-native-gesture-handler/jestSetup.js"
]
I found a reference from the following link and It's working for me.
https://github.com/software-mansion/react-native-gesture-handler/issues/344#issuecomment-489547513
For me just adding the setupFiles didn't work. I added setupFiles and transformIgnorePatterns at "jest" in package.json
Here the code to make the gestureHandler work, but I tested it with AsyncStorage and the storage stopped work. If you aren't using AsyncStorage I presume this code will work very well!
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js"
],
"transformIgnorePatterns": [
"/node_modules/(?!native-base)/"
]
My reference:
https://github.com/software-mansion/react-native-gesture-handler/issues/344
Updating package.json and reinstalling npm package worked for me.
"jest": {
"preset": "react-native",
"transformIgnorePatterns": ["node_modules/(?!(jest-)?react-native|#?react-navigation)"],
"setupFiles": ["./node_modules/react-native-gesture-handler/jestSetup.js"]
}
This is happening because you have to mock the NativeModules module from react-native. It can happen with several modules but it was happening to me specifically with the ImagePicker, Linking and #react-navigation/native. This is what I did to mock the native modules.
/src/testSetup.ts
import {NativeModules} from 'react-native';
NativeModules.RNGestureHandlerModule= {
attachGestureHandler: jest.fn(),
createGestureHandler: jest.fn(),
dropGestureHandler: jest.fn(),
updateGestureHandler: jest.fn(),
State: {},
Directions: {},
},
NativeModules.ImagePickerManager = {
showImagePicker: jest.fn(),
}
NativeModules.Linking = {
canOpenUrl: jest.fn().mockResolvedValue(true),
openUrl: jest.fn().mockResolvedValue(true)
}
NativeModules.Platform = {
OS: 'iOS'
}
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
jest.mock('react-native/Libraries/Animated/src/animations/TimingAnimation');
const mockNavigation = () => {
const mockedNavigate = jest.fn();
const mockedAddListener = jest.fn();
jest.mock('#react-navigation/native', () => ({ // #ts-ignore
...(jest.requireActual('#react-navigation/native')),
useNavigation: () => ({
navigate: mockedNavigate,
addListener: mockedAddListener
})
}));
return {mockedNavigate, mockedAddListener}
}
in your tests
import { fireEvent, act, render } = '#testing-library/react-native'
const {mockedNavigate, mockedAddListener} = mockNavigation()
test('Should navigate', () => {
const { queryByText } = render(<Component />)
fireEvent.press(getByText('View Page Button'))
expect(mockedNavigate).toHaveBeenCalledWith('Your Page Name')
expect(mockedAddListener).toHaveBeenCalled()
})
In my case, I was using react-native-cli when encountered this problem. I removed it and installed #react-native-community/cli instead. It fixed everything!
I have just created a new snack and add native base library with the instructions provided by Native base documentation for expo:
Here is the instructions i have followed:
// At the top of your file
import { Font } from 'expo';
import { Ionicons } from '#expo/vector-icons';
// Later on in your component
async componentDidMount() {
await Font.loadAsync({
'Roboto': require('native-base/Fonts/Roboto.ttf'),
'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
...Ionicons.font,
});
}
But It shows Error As Unable to resolve module FontAwesome5.js
Please Suggest me some solution for the same
Here is my Snack Link for the same.
https://snack.expo.io/#simransingh/native-base
Thanks.
Hi I just found the solution for the same ,
It's because of FontAwesome5 not loaded properly ,
You can import it from #expo/vector-icons
Here is the working snack:
https://snack.expo.io/#simransingh/native-base
yep this problem happend to me in snack i just solved it by changing the version of nativebase from latest to previous version
{
"dependencies": {
"react-native-paper": "2.2.8",
"native-base": "latest"
}
}
change to
{
"dependencies": {
"react-native-paper": "2.2.8",
"native-base": "2.12.1"
}
}