我正在使用Gatsby和Jest进行测试 . 默认情况下,Gatsby处理GraphQL数据获取,并且从我发现它没有提供任何解决方案来测试单元测试中的GraphQL查询 .
有没有办法做到这一点?现在我只是模拟测试组件本身的查询,但我希望能够在GraphiQL中手动测试查询工作 .
这是我的代码的样子:
PageContent.jsx
import PropTypes from 'prop-types';
import React from 'react';
const PageContent = ({ data: { markdownRemark: { html } } }) => (
<div>
{html}
</div>
);
PageContent.propTypes = {
data: PropTypes.shape({
markdownRemark: PropTypes.shape({
html: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
};
export const query = graphql`
query PageContent($id: ID!) {
markdownRemark(frontmatter: { id: $id }) {
html
}
}
`;
export default PageContent;
PageContent.test.jsx
import PageContent from 'templates/PageContent';
describe("<PageContent>", () => {
let mountedComponent;
let props;
const getComponent = () => {
if (!mountedComponent) {
mountedComponent = shallow(<PageContent {...props} />);
}
return mountedComponent;
};
beforeEach(() => {
mountedComponent = undefined;
props = {
data: {
markdownRemark: {
html: '<div>test</div>',
},
},
};
});
it("renders a <div> as the root element", () => {
expect(getComponent().is('div')).toBeTruthy();
});
it("renders `props.data.markdownRemark.html`", () => {
expect(getComponent().contains(props.data.markdownRemark.html)).toBeTruthy();
});
});