我在测试HoC组件时遇到问题,该组件执行gql查询并将结果添加为prop。该组件正常工作是因为我手动测试了它,但是在模拟查询时遇到了麻烦。这是apollo的2.5之前的版本,因此其他@client查询也可以使用。
这是我的专案
export const GET_CONFIG = gql`
{
config @client,
}
`;
/**
* This HoC wraps a component adding to it the current site configuration stored in Apollo.
* It should be used for every component which needs to access the configuration.
*
* @param Component
* @returns The Component wrapped with the config prop
*/
export const withConfig = Component => props => (
<Query
query={GET_CONFIG}
>
{({loading, error, data}) => {
console.log(data);
return (
<Component config={JSON.parse(data.config)} {...props} />
);
}
}
</Query>
);
testComponent
const TestComponent = () => (
<div>test</div>
)
export default withConfig(TestComponent);
我的测试:
describe('withConfig', () => {
const mockData = () => [
{
request: {
query : GET_CONFIG
},
result: {
data: {
config: 'jjjjjjj',
},
},
},
];
it('should pass extra props to provided component', async () => {
const wrapper = renderer.create(
<MockedProvider mocks={mockData()} addTypename={false}>
<TestComponent />
</MockedProvider>,
);
await wait(0);
expect(wrapper.toJSON()).toMatchSnapshot();
});
});
问题在于,模拟查询不会返回预期的“ ggggg”,但会返回一个空对象,因此测试失败并显示JSON解析错误
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
23 | console.log(data);
24 | return (
> 25 | <Component config={JSON.parse(data.config)} {...props} />
| ^
26 | );
27 | }
28 |
有什么想法吗?