[英]relay modern: how to mock relay for unit testing
Am trying to test react relay modern container, but am having this issue.我正在尝试测试反应中继现代容器,但遇到了这个问题。
TypeError: Cannot read property 'environment' of undefined
Here is the test code:下面是测试代码:
test('render component', () => {
const tree = renderer.create(
<User />,
).toJSON();
expect(tree).toMatchSnapshot();
});
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.到需要中继的单元测试。 This will mock out relay and leave just the component to test.
这将模拟中继并只留下要测试的组件。
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;
You actually dont need to mock the environment variable at all.您实际上根本不需要模拟环境变量。 What I usually do is add:
我通常做的是添加:
export class User
to the classdeclaration of the class that I want to test.到我要测试的类的类声明。 (Make sure to keep the export default on your connected version of the same class).
(确保在同一类的连接版本上保持导出默认值)。
I can then test the component the preferred way by importing the component without the need for relay like so in my test:然后,我可以通过导入组件以首选方式测试组件,而无需像在我的测试中这样的中继:
import { User } from '../User'
This removes the need for mocking relay and you can pass in the props cleanly to the component.这消除了对模拟中继的需要,您可以将 props 干净地传递给组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.