如何在Gatsby中对GraphQL查询进行单元测试 [英] How to unit test GraphQL queries in Gatsby
问题描述
我正在使用Gatsby和Jest进行测试.默认情况下,Gatsby处理GraphQL数据获取,并且据我发现,它没有提供任何在单元测试中测试其GraphQL查询的解决方案.
I'm using Gatsby and Jest for testing. By default Gatsby handles the GraphQL data fetching, and from what I've found it doesn't provide any solution for testing its GraphQL queries in unit tests.
有没有办法做到这一点?现在,我只是在模拟查询以测试组件本身,但是我希望能够在不使用GraphiQL的情况下手动测试查询.
Is there a way to do this? Right now I'm just mocking the queries the test the component itself, but I want to be able to test queries work without manually doing so in GraphiQL.
这是我的代码:
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();
});
});
推荐答案
I've written a plugin that enables testing of Gatsby components with GraphQL queries. If you install it you can retrieve the actual Graph QL data by replacing your mocked data
data: {
markdownRemark: {
html: '<div>test</div>',
},
}
使用
data: await getPageQueryData(`/path/to/your/page`)
然后它将从最近一次构建项目(使用 gatsby build
或 gatsby development
)中提取数据
It will then pull the data from the latest time you built your project (using gatsby build
or gatsby develop
)
这篇关于如何在Gatsby中对GraphQL查询进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!