[英]Testing Relay [createFragmentContainer] with jest?
I am tring to test my components but every component that exports createFragmentContainer shows me this issue: 我正在测试我的组件,但是每个导出createFragmentContainer的组件都向我显示此问题:
console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
Warning: Failed context type: Invalid prop/context `relay` supplied to `Relay(Product)`, expected `undefined` to be an object with an `environment` and `variables`.
in Relay(Product)
console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
React caught an error thrown by Relay(Product). You should fix this error in your code. Consider adding an error boundary to your tree to customize error handling behavior.
TypeError: Cannot read property 'environment' of undefined
The error is located at:
in Relay(Product)
so does jest support fragment containers or the problem is in my project ? 那么笑话是否支持片段容器,或者问题出在我的项目中?
Add the below to __mocks__
folder. 将以下内容添加到
__mocks__
文件夹。 Then in the test add jest.mock('react-relay');
然后在测试中添加
jest.mock('react-relay');
to the unit test that needs relay. 到需要中继的单元测试。
import React from 'react'; import PropTypes from 'prop-types'; const relayMock = jest.genMockFromModule('react-relay'); const relayChildContextTypes = { relay: PropTypes.object, }; const relayEnvironment = { lookup: jest.fn(), }; const relayContext = { relay: { environment: relayEnvironment, variables: {}, }, }; const relayFragmentProps = { relay: { environment: relayEnvironment, }, }; const relayRefetchProps = { relay: { environment: relayEnvironment, refetch: jest.fn(), }, }; const relayPaginationProps = { relay: { environment: relayEnvironment, hasMore: jest.fn(), loadMore: jest.fn(), isLoading: jest.fn(), }, }; relayMock.__relayEnvironment = relayEnvironment; relayMock.__relayFragmentProps = relayFragmentProps; relayMock.__relayRefetchProps = relayRefetchProps; relayMock.__relayPaginationProps = relayPaginationProps; const makeRelayWrapper = (relayProps) => ( (Comp) => { class HOC extends React.Component { getChildContext() { return relayContext; } render() { return <Comp {...this.props} {...relayProps}/>; } } HOC.childContextTypes = relayChildContextTypes; return HOC; } ); relayMock.QueryRenderer = jest.fn(() => React.createElement('div', null, 'Test')); relayMock.createFragmentContainer = makeRelayWrapper(relayFragmentProps); relayMock.createRefetchContainer = makeRelayWrapper(relayRefetchProps); relayMock.createPaginationContainer = makeRelayWrapper(relayPaginationProps); module.exports = relayMock;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.