Fatah
Fatah

Reputation: 2286

JEST Test Failed - TypeError: Cannot read property 'fetch' of undefined in CRNA Expo App

I am not unit testing a fetch function so even libraries like jest-fetch-mock don't help get rid of the error. Neither does axios nor isomorphic-fetch

Running yarn test yields this.

enter image description here My App.test.js simply doesn't test fetch:

import React from 'react'
import renderer from 'react-test-renderer'
import App from './App'

it('renders without crashing', () => {
  const rendered = renderer.create(<App />).toJSON()
  expect(rendered).toBeTruthy()
})

Similar to: * Error : Cannot read property fetch. Using jest-expo with react native (might be duplicate but the question is not elaborated) * Jest throwing TypeError: Cannot read property 'fetch' of undefined

I have a fetch method in my screens(not in my tests). Note that the above error occurs whether or not I comment/use my fetch functions.

I am suspecting this has something to do with my babel or jest configs.

The above error happens with my .babelrc below. Changing .babelrc:

   {
     "presets": ["babel-preset-expo", "react-native", "es2015", "react-native-dotenv"],
     "env": {
     "development": {
       "plugins": ["transform-react-jsx-source","module-resolver"]
      }
     }
    }

by removing "es2015" preset causes another error. Note this happens even if there is no babel-preset-es2015 devDependency.

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG                                                                                             
^
  SyntaxError: Invalid or unexpected token

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
  at Object.<anonymous> (node_modules/react-navigation/src/views/Header/HeaderBackButton.js:92:223)

I am using yarn 1.3.2 & ubuntu 17.04 & Node v9.5.0 & create-react-native-app version: 1.0.0

My App Component:

   import React, { Component } from 'react'
   import {
      TouchableHighlight,
      Text,
      View,
      AsyncStorage
   } from 'react-native'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: null
    }
  }
  componentWillMount() {
    this.setState({
      loading: true
    }, this._getData)
  }
  _getData = () => {
      fetch('localhost:1212')
      .then(() => {
        this.setState({
          data: data,
        })
      })
      .catch((error) => {
        alert('There was an error fetching the secret info.')
      })
      .done()
    }
  _renderData = () => (
    <Text>You are seeing</Text>
  )
  render() {
    return (
      <View >
        {
          <Text>
            {this.state.secret ? this._renderData() : <Text>Nothing to See</Text>}
          </Text>
        }
      </View>
    )
  }
}

export default App

Upvotes: 2

Views: 1142

Answers (0)

Related Questions