我一直在尝试像测试 Flux 应用程序中的组件一样测试 Relay 容器。具体来说,我想确保它们为给定的状态和道具呈现正确的内容,并确保它们调用方法以在适当的位置更改数据;在 Flux 中,这是对动作创建者的调用,在 Relay 中,这是对Relay.Store.update
or的调用this.props.relay.setVariables
。
我的第一次尝试是使用方法构建RelayTestUtil
对象renderContainerIntoDocument
。我主要基于https://github.com/facebook/relay/blob/master/src/tools/mocks /RelayTestUtils.js , https://github.com/facebook/relay/blob/master/src/legacy /store/ mocks /GraphQLStoreQueryResolver.js和 Relay Container 测试。这使用了非常少的模拟,非常适合测试容器渲染,但对于测试数据更改完全没用。试图监视对Relay.Store.update
and的调用this.props.relay.setVariables
,或模拟数据更改,变得比它值得的更麻烦。
我决定添加__mocks__\react-relay.js
完全模拟 Relay 并使用更简单的版本RelayTestUtils.renderContainerIntoDocument
将 Relay 属性注入容器。我对这个解决方案并不完全满意,但它现在似乎有效。
__mocks__\react-relay.js
:
var Relay = require.requireActual('react-relay');
var React = require('react');
module.exports = {
QL: Relay.QL,
Mutation: Relay.Mutation,
Route: Relay.Route,
Store: {
update: jest.genMockFn()
},
createContainer: (component, containerSpec) => {
const fragments = containerSpec.fragments || {};
// mock the static container methods
Object.assign(component, { getFragment: (fragmentName) => fragments[fragmentName] });
return component;
}
};
RelayTestUtils.js
:
const React = require('react');
const ReactDOM = require('react-dom');
const RelayTestUtils = {
renderContainerIntoDocument(containerElement, relayOptions) {
relayOptions = relayOptions || {};
const relaySpec = {
forceFetch: jest.genMockFn(),
getPendingTransactions: jest.genMockFn().mockImplementation(() => relayOptions.pendingTransactions),
hasOptimisticUpdate: jest.genMockFn().mockImplementation(() => relayOptions.hasOptimisticUpdate),
route: relayOptions.route || { name: 'MockRoute', path: '/mock' },
setVariables: jest.genMockFn(),
variables: relayOptions.variables || {}
};
return ReactDOM.render(
React.cloneElement(containerElement, { relay: relaySpec }),
document.createElement('div')
);
}
};
export default RelayTestUtils;
测试看起来像这样,fragmentData
与 GraphQL 响应的形状相匹配:
it('changes items', () => {
const myContainer = RelayTestUtils.renderContainerIntoDocument(
<MyContainer { ...fragmentData }/>,
{ variables: { itemId: 'asdf' } }
);
myContainer.changeItem();
expect(myContainer.props.relay.setVariables).toBeCalled();
});