在Apollo Client中测试客户端解析器

我的以下tiny fullstack Apollo project具有以下架构:

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    books: [Book]
  }

  type Book {
    id: Int
    name: String
    published: Int
    author: Author
  }

  type Author {
    id: Int
    name: String
  }
 `;

module.exports = typeDefs;

我创建了一个用于获取图书的查询:

export const GET_BOOKS = gql`
  query GetBooks {
    books {
      id
      name
      published
      author {
        id
        name
      }
    }
  }
`;

我创建了一个客户端解析器,该解析器扩展了一个提供作者的新查询:

import gql from 'graphql-tag';
import {GET_BOOKS} from "./components/Books";

export const typeDefs = gql`
  extend type Query {
    authors: [Author]
  }
`;

const getauthors = (books) => {
  return books.reduce((authors,{author}) => {
      return authors.set(author.id,author);
  },new Map());
};

export const resolvers = {
  Query: {
    authors: async (_,__,{ client }) => {
      const {data} = await client.query({query: GET_BOOKS});
      return [...getauthors(data.books)].map(([,author]) => author);
    },},};

我有一个Authors组件,可以根据客户端查询显示作者:

import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
import ShowDataComponent from "./ShowDataComponent";

export const GET_AUTHORS = gql`
  query Getauthors {
    authors @client {
      id
      name
    }
  }
`;

export default function Authors() {
  const { data,loading,error } = useQuery(GET_AUTHORS);
  if (loading) return <div>Loading ...</div>;
  if (error) return <ShowDataComponent label="Authors" data={error}/>;

  return <ShowDataComponent label="Authors" data={data}/>
}

然后,它按预期工作。但是,考虑到模拟的服务器预订查询GET_BOOKS,我想测试组件Authors是否运作良好。我将客户端解析器传递给MockedProvider组件,没有任何结果:

export const Tolkien = () => ({
  id: 2,name: 'John Ronald Reuel Tolkien'
});

export const Orwell = () => ({
  id: 3,name: 'George Orwell'
});

const BooksMock = () => [{
  id: 1,name: 'The Hobbit',published: 1954,author: Tolkien()
},{
  id: 1,name: 'Nineteen Eighty-Four',published: 1949,author: Orwell()
}];

describe('Books',() => {
  afterEach(cleanup);

  it('renders books',async () => {
    const cache = new InmemoryCache({ addTypename: false });
    const books = BooksMock();
    const mocks = [
      {
        request: { query: GET_AUTHORS },result: {
          data: {
            books,];
    const { container } = await render(
      <MockedProvider
        mocks={mocks}
        cache={cache}
        resolvers={resolvers}
      >
        <Authors/>
      </MockedProvider>
    );
    await wait(() => expect(container.textContent).toContain(Orwell().name));
    await wait(() => expect(container.textContent).toContain(Tolkien().name));
  });
});

但是Authors组件仍在加载。我不确定我做错了什么还是MockedProvider无法执行这种测试。

zhangfanfootball 回答:在Apollo Client中测试客户端解析器

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3096416.html

大家都在问