在React组件中绕过获取调用 [英] Bypass fetch call in React component
问题描述
我正在尝试编写一个对React组件的测试,该组件在安装后会发出获取GET请求.该测试仅需要检查组件是否已渲染,并且在获取运行时我会得到:ReferenceError: fetch is not defined
.我四处搜寻,似乎找不到能解决我问题的任何东西.我正在使用jest和Test Utils来测试组件.
I am attempting to write a test for a react component that sends out a fetch GET request after mounting. The test just needs to check if the component has rendered and when fetch runs I get this: ReferenceError: fetch is not defined
. I have searched around and cant seem to find anything that will fix my problem. I am using jest and Test Utils for testing the components.
我的组件代码:
export class Home extends Component {
constructor(props) {
...
}
componentDidMount() {
fetch('/some/path', {
headers: {
'Key1': 'Data1',
'Key2': Data2
}
}).then(response => {
if (response.status == 200) {
response.json().then((data) => {
this.context.store.dispatch(setAssets(data))
}
);
} else {
return (
<Snackbar
open={true}
message={"ERROR: " + str(response.status)}
autoHideDuration={5000}
/>
);
}
}).catch(e => {});
...
);
}
componentWillUnmount() {
...
}
logout(e) {
...
}
render() {
return (
<div>
<AppBar
title="Title"
iconElementLeft={
<IconButton>
<NavigationClose />
</IconButton>
}
iconElementRight={
<IconMenu
iconButtonElement={
<IconButton>
<MoreVertIcon />
</IconButton>
}
targetOrigin={{
horizontal: 'right',
vertical: 'top'
}}
anchorOrigin={{
horizontal: 'right',
vertical: 'top'
}}
>
<MenuItem>
Help
</MenuItem>
</IconMenu>
}
/>
{
this.context.store.getState().assets.map((asset, i) => {
return (
<Card
title={asset.title}
key={i+1}
/>
);
})
}
</div>
);
}
}
Home.contextTypes = {
store: React.PropTypes.object
}
export default Home;
我的测试代码:
var home
describe('Home', () => {
beforeEach(() => {
let store = createStore(assets);
let a = store.dispatch({
type: Asset,
assets: [{
'id': 1,
'title': 'TITLE'
}],
});
store.getState().assets = a.assets
home = TestUtils.renderIntoDocument(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Provider store={store}>
<Home />
</Provider>
</MuiThemeProvider>
);
});
it('renders the main page, including cards and appbar', () => {}
尝试将Home渲染为文档时出错.
It errors when trying to render Home into document.
我已经尝试过 fetch-mock ,但这仅允许进行API测试的模拟调用,这不是我要做的,也不是在组件中模拟fetch调用.
I have tried fetch-mock but this only allows for mock calls for API testing, which I'm not trying to do and doesn't mock the fetch calls in my component.
模拟首页无法正常工作,因为它是我要测试的组件.除非有一种方法可以模拟我错过的componentDidMount()
函数.
Mocking Home wont work because its the component I am trying to test. Unless there's a way to mock the componentDidMount()
function that I have missed.
我只需要一种解决方法来进行调用.有什么想法吗?
I just need a workaround for the fetch call. Any ideas??
编辑:我正在使用React的JSX作为组件,使用JS作为测试
I'm using React's JSX for the component and JS for the test
推荐答案
我找到了一个对我有用的答案,它非常简单,没有包含任何其他依赖项.这很简单,只需将主要功能存储到变量中并覆盖它,然后在测试用例之后恢复适当的功能
I found an answer that worked for me, and it was very simple without including any other dependencies. It was a simple as storing the main function into a variable and overwriting it, then restoring the proper function after the testcase
解决方案:
var home
describe('Home', () => {
const fetch = global.fetch
beforeEach(() => {
let store = createStore(assets);
let a = store.dispatch({
type: Asset,
assets: [{
'id': 1,
'title': 'TITLE'
}],
});
store.getState().assets = a.assets
global.fetch = () => {return Promise.resolve('', 200)}
home = TestUtils.renderIntoDocument(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Provider store={store}>
<Home />
</Provider>
</MuiThemeProvider>
);
});
it('renders the main page, including cards and appbar', () => {
...
});
afterEach(() => {
global.fetch = fetch;
});
});
这篇关于在React组件中绕过获取调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!