我不是单元测试fetch函数,所以即使像jest-fetch-mock这样的库也无法帮助摆脱错误。 axios
也不isomorphic-fetch
运行yarn test
会产生此结果。
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()
})
类似于: * Error : Cannot read property fetch. Using jest-expo with react native(可能重复,但问题没有详细说明) * Jest throwing TypeError: Cannot read property 'fetch' of undefined
https://github.com/react-community/create-react-native-app/issues/208
的Facebook /开玩笑#3499
我的屏幕中有一个fetch方法(不在我的测试中)。请注意,无论我是否评论/使用我的提取功能,都会出现上述错误。
我怀疑这与我的babel或jest configs有关。
上面的错误发生在我的.babelrc
下面。正在更改.babelrc
:
{
"presets": ["babel-preset-expo", "react-native", "es2015", "react-native-dotenv"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source","module-resolver"]
}
}
}
删除“es2015”预设会导致另一个错误。请注意,即使没有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)
我正在使用yarn 1.3.2
&amp; ubuntu 17.04
&amp; Node v9.5.0
&amp; create-react-native-app version: 1.0.0
我的应用组件:
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