Closed laurisdjilo closed 5 years ago
I have this problem but only when test my app with jest
.
$ jest
FAIL __tests__/App.test.js
● Test suite failed to run
TypeError: Cannot read property 'UserTrackingModes' of undefined
1 | import React from 'react'
2 | import PropTypes from 'prop-types'
> 3 | import Mapbox from '@mapbox/react-native-mapbox-gl'
| ^
4 | import Icon from 'react-native-vector-icons/MaterialIcons'
5 |
6 | const Bike = props => {
at Object.<anonymous> (node_modules/@mapbox/react-native-mapbox-gl/javascript/components/MapView.js:850:2279)
at Object.<anonymous> (node_modules/@mapbox/react-native-mapbox-gl/javascript/index.js:6:39)
at Object.<anonymous> (src/components/Bike.js:3:51)
I also hit this when attempting to test with jest
. To get around it you may need to set up a mock for Jest.
There's an example you can use here https://github.com/mapbox/react-native-mapbox-gl/blob/master/__tests__/__mocks__/react-native-mapbox-gl.mock.js
Your setup will vary, but in mine I include:
setupTestFrameworkScriptFile: "<rootDir>/src/utils/setupTests.js",
In my jest config in a jest.config.js
(can also be in package.json)
And then I copy/pasted the contents of react-native-mapbox-gl.mock.js
into setupTests.js
.
Note I did hit one other issue with that. In the above UserTrackingModes
the keyMirror
function is used so the values for each tracking mode constant end up a string. That threw an error for me because Mapbox expects those to be ints. To get around that I changed the value to:
...
UserTrackingModes: {
None: 0,
Follow: 1,
FollowWithCourse: 2,
FollowWithHeading: 3
},
...
Had same issue, but I also another one because react-native-mapbox-gl.mock.js
file isn't creating the views needed to render the component.
So I was getting this error:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
What I ended up doing it:
jest.mock("@mapbox/react-native-mapbox-gl", () => {
const React = require("React");
const NativeModules = require("react-native");
// ....
NativeModules.MGLModule = {
UserTrackingModes: {
None: 0,
Follow: 1,
FollowWithCourse: 2,
FollowWithHeading: 3,
},
};
// ....
// it creates the view I need.
return class Mapbox extends React.Component {
static MapView = props =>
React.createElement("MapView", props, props.children);
static PointAnnotation = props =>
React.createElement("PointAnnotation", props, props.children);
render() {
return React.createElement("MapView", this.props, this.props.children);
}
static setAccessToken = () => jest.fn();
};
});
Mocking is required for jest. Closing as issue is resolved.
I have this error when i import the mapbox module with the instruction import MapboxGL from '@mapbox/react-native-mapbox-gl'; Did any one already had this problem please?