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.
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.
Here's what my code looks like:
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;
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>',
},
}
with
data: await getPageQueryData(`/path/to/your/page`)
It will then pull the data from the latest time you built your project (using gatsby build
or gatsby develop
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.