我编写了简单的react-apollo组件,它使用graphql查询从模式中检索数据。在执行组件工作正常但是,当我使用jest框架和MockedProvider(即react-apollo / test-utils的组件)编写该组件的测试用例时。我无法使用数据填充组件。我在MockedProvider上提到了这篇文章:https://paradite.com/2017/11/16/test-react-apollo-components-enzyme-examples/
我的组件和测试脚本如下:
//MyComponent.js
import React, { Component } from "react";
import { gql, graphql, compose } from "react-apollo";
export class MyComp extends Component {
render() {
console.log("data",this.props);
return (
<div>Hello welcome {this.props.msg}
{!this.props.data.loading && this.props.data.person.edges.map((person,i)=>(
<p key={i}>{person.node.name}</p>
)
)}
</div>
);
}
}
export const PERSON_QUERY = gql`query Info {
person{
edges{
node{
id
name
__typename
}
__typename
}
__typename
}
}`;
export default compose(graphql(PERSON_QUERY,{}))(MyComp);
// MyComponent.test.js
import React from 'react';
import { configure, mount } from 'enzyme';
import toJSON from 'enzyme-to-json';
import { MockedProvider } from 'react-apollo/test-utils';
import { addTypenameToDocument } from 'apollo-client';
import { gql, graphql, compose } from "react-apollo";
import MyComponent,{MyComp, PERSON_QUERY} from 'components/MyComponent';
import Adapter from 'enzyme-adapter-react-15';
import {store} from "stores/store";
configure({adapter: new Adapter()});
const data1 = {
person: {
edges: [
{
node: {
id: "00000000-0002-972",
name: "Magic Mad",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "000-0001-972",
name: "Donald Durm",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "00-0000-fccd3",
name: "Peter Hogwarts",
__typename: "Person"
},
__typename: "PersonEdge"
}
],
__typename: "PersonConnection"
}
};
describe("MockedProvider",()=>{
test("Load with data",()=>{
const wrap = mount(<MockedProvider mocks={[
{
request: {
query: addTypenameToDocument(PERSON_QUERY)
},
result: { data: data1 }
}
]}>
<MyComponent msg={"2018"}/>
</MockedProvider>);
console.log("Mock",wrap.props());
console.log("html",wrap.html());
wrap.update();
});
});
答案 0 :(得分:0)
这里的帖子的作者。
我很容易看到很多问题:
result: { data: data2 }
其中data2
未定义,我认为您的意思是data1
。
此外,您的模拟数据data1
具有data
属性,这是错误的,因为结果对象已经具有data
属性,您应该将其从data1
中删除并直接公开person
属性:
const data1 = {
person: {
edges: [
{
node: {
id: "00000000-0002-972",
name: "Magic Mad",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "000-0001-972",
name: "Donald Durm",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "00-0000-fccd3",
name: "Peter Hogwarts",
__typename: "Person"
},
__typename: "PersonEdge"
}
],
__typename: "PersonConnection"
}
};
如果仍然无法解决您的问题,您应该知道的另一件事是,您可以记录wrap
变量以查看模拟并检查它们是否符合您的要求:
console.log(wrap);
您可以尝试从那里进行调试。