我用盖茨比和杰斯特做测试。默认情况下,Gatsby处理GraphQL数据获取,根据我的发现,它没有为在单元测试中测试GraphQL查询提供任何解决方案。
有办法吗?现在我只是模拟测试组件本身的查询,但是我希望能够测试查询的工作,而不需要在GraphiQL中手动执行。
我的代码如下:
页面内容.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();
});
});