【发布时间】:2019-01-15 05:22:23
【问题描述】:
我正在使用 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();
});
});
【问题讨论】:
-
你找到方法了吗?
-
@VladyslavZavalykhatko 不,抱歉。我仍然只是在嘲笑查询
-
你想对 GraphQL 查询进行哪些测试?还是一样吗?
-
您可以对其进行快照测试,只需检查
query导出中的内容。