0

我正在尝试使用 Apollo 从 React 编写单元测试。

我从https://dev-blog.apollodata.com/seamless-integration-for-graphql-and-react-6ffc0ad3fead找到了一个例子

尝试时出现错误:

错误:

Uncaught (in react-apollo) Error: Network error: No more mocked responses for the query: query people {
      allPeople(first: 1) {
        people {
          name
          __typename
        }
        __typename
      }
    }

测试:

it('executes a query', (done) => {

  const query = gql` query people { allPeople(first: 1) { people { name } } }`;
  const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } };
  const networkInterface = mockNetworkInterface({ request: { query }, result: { data } });
  const client = new ApolloClient({ networkInterface });

  const withGraphQL = graphql(query);

  class Container extends Component {
    componentWillReceiveProps(props) {
      expect(props.data.loading).to.be.false;
      expect(props.data.allPeople).to.deep.equal(data.allPeople);
      done();
    }
    render() {
      return null;
    }
  };

  const ContainerWithData = withGraphQL(Container);

  mount(<ApolloProvider client={client}><ContainerWithData /></ApolloProvider>);

});
4

1 回答 1

1

我知道这是一个老问题,但也许有人像我一样来到这里 :) 这些 __typename 字段很可能是您的问题,查询最终看起来与您传递给模拟接口的查询不同。该错误基本上意味着它找不到该查询的任何匹配模拟。

无论如何,这是这个测试的一个工作示例,已更新为在 Apollo 2 中工作。

it('executes a query', (done) => {
  const query = gql` query people { allPeople(first: 1) { people { name } } }`;
  const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } };

  const withGraphQL = graphql(query);

  class Container extends React.Component {
    componentWillReceiveProps(props) {
      expect(props.data.loading).toBeFalsy();
      expect(props.data.error).toBeUndefined();
      expect(props.data.allPeople.people[0].name).toEqual(data.allPeople.people[0].name);
      done();
    }
    render() {
      return null;
    }
  };

  const ContainerWithData = withGraphQL(Container);

  mount(<MockedProvider removeTypename mocks={[ { request: { query },   result: { data } } ]}><ContainerWithData /></MockedProvider>);

});
于 2018-03-23T18:13:50.247 回答