【问题标题】:Mocking apollo link state模拟阿波罗链路状态
【发布时间】:2018-12-06 17:59:09
【问题描述】:

我正在尝试模拟查询@client,但我没有得到。

我正确地模拟了来自 graphql 服务器的查询并且它正在工作。

import React from 'react';
import renderer from 'react-test-renderer';
import wait from 'waait';
import ExchangeRates from './ExchangeRates';
import { MockedProvider } from 'react-apollo/test-utils';
import { sucessMockrates, errorMockrates } from '../../mocks/exchangeRatesMock';

describe('ExchangeRates', () => {
  it('should render rate', async () => {
    const component = renderer.create(
      <MockedProvider mocks={[sucessMockrates]} addTypename={false}>
        <ExchangeRates />
      </MockedProvider>
    );
    await wait(0);
    const p = component.root.findByType('p');
    expect(p.children).toContain('AED: 3.67');
  });

  it('should render loading state initially', () => {
    const component = renderer.create(
      <MockedProvider mocks={[]}>
        <ExchangeRates />
      </MockedProvider>
    );

    const tree = component.toJSON();
    expect(tree.children).toContain('Loading...');
  });
  it('should show error UI', async () => {
    const component = renderer.create(
      <MockedProvider mocks={[errorMockrates]} addTypename={false}>
        <ExchangeRates />
      </MockedProvider>
    );

    await wait(0);

    const tree = component.toJSON();
    expect(tree.children).toContain('Error!');
  });
});

我正在使用来自 apollo tutorial 的 graphql 服务器链接

但是当我尝试使用本地状态测试 apollo 查询时出现错误。

我的查询:

import gql from 'graphql-tag';

export default gql`
  query {
    allocations @client {
      list
    }
  }
`;

和我的 apollo 客户端设置:

const cache = new InMemoryCache();

const defaultState = {
  allocations: {
    __typename: 'Allocations',
    list: [],
  },
};


const listQuery = gql`
  query getAllocations {
    allocations @client {
      list
    }
  }
`;

const stateLink = withClientState({
  cache,
  defaults: defaultState,
  resolvers: {
      addAllocation: (
        _,
        { userName },
        { cache }
      ) => {
        const previousState = cache.readQuery({ query: listQuery });
        const { list } = previousState.allocations;
        const data = {
          ...previousState,
          allocations: {
            ...previousState.allocations,
            list: [
              ...list,
              {
                userName
              },
            ],
          },
        };

        cache.writeQuery({ query: listQuery, data });
        return data.allocations;
      },
    },
  },
});

const client = new ApolloClient({
  link: ApolloLink.from([
    stateLink,
    new HttpLink({
      uri: 'https://w5xlvm3vzz.lp.gql.zone/graphql',
    }),
  ]),
  cache,
});

我对阿波罗本地状态的测试:

import React from 'react';
import renderer from 'react-test-renderer';
import AllocationListPage from './AllocationListPage';
import { MockedProvider } from 'react-apollo/test-utils';
import { sucessMockAllocations } from '../../../mocks/allocationListMock';

describe('AllocationListPage', () => {
  it('should render list of allocations', () => {
    renderer.create(
      <MockedProvider mocks={[sucessMockAllocations]} addTypename={false}>
        <AllocationListPage />
      </MockedProvider>
    );
  });
});

我得到的错误:TypeError:

无法解构“未定义”或“空”的属性list

我需要mock apollo本地状态的初始状态,不知道怎么做。

提前致谢。

【问题讨论】:

    标签: reactjs graphql apollo react-apollo apollo-client


    【解决方案1】:

    我用这个组件设置了我的 apollo 链接状态:

    import React, { PureComponent } from 'react';
    import PropTypes from 'prop-types';
    import { ApolloProvider } from 'react-apollo';
    import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
    import { ApolloClient } from 'apollo-client';
    import { stateLink, cache } from '../graphql/stateLink';
    import { ApolloLink } from 'apollo-link';
    import { SchemaLink } from 'apollo-link-schema';
    
    const setupClient = mocks => {
      const typeDefs = `
      type Query {
        test: String!
      }
    `;
    
      const schema = makeExecutableSchema({ typeDefs });
      addMockFunctionsToSchema({
        schema,
        mocks,
        preserveResolvers: false,
      });
    
      return new ApolloClient({
        cache,
        link: ApolloLink.from([stateLink, new SchemaLink({ schema })]),
      });
    };
    
    class ApolloLinkStateSetup extends PureComponent {
      render() {
        return (
          <ApolloProvider client={setupClient(this.props.mocks)}>
            {this.props.children}
          </ApolloProvider>
        );
      }
    }
    
    ApolloLinkStateSetup.defaultProps = {
      mocks: {},
    };
    
    ApolloLinkStateSetup.propTypes = {
      children: PropTypes.object.isRequired,
      mocks: PropTypes.object,
    };
    
    export default ApolloLinkStateSetup;
    

    您可以使用 graphql-tools 中的 makeExecutableSchema 和 addMockFunctionsToSchema 来模拟 graphql 查询。这个模拟对于创建没有后端的前端非常有用。

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2020-03-23
      • 2019-04-16
      • 2019-02-04
      • 2013-02-02
      • 2021-12-28
      • 2017-10-15
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多