Apollo MockedProvider未返回预期数据

时间:2020-11-03 19:52:27

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

我写了一个调用apollo useQuery的钩子。很简单:

useDecider:

import { useState } from 'react';
import { useQuery, gql } from '@apollo/client';

export const GET_DECIDER = gql`
  query GetDecider($name: [String]!) {
    deciders(names: $name) {
      decision
      name
      value
    }
  }
`;

export const useDecider = name => {
  const [enabled, setEnabled] = useState(false);

  useQuery(GET_DECIDER, {
    variables: {
      name
    },
    onCompleted: data => {
      const decision = data?.deciders[0]?.decision;
      setEnabled(decision);
    },

    onError: error => {
      return error;
    }
  });

  return {
    enabled
  };
};

我正在尝试对其进行测试,而MockedProvider未返回预期的数据:

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MockedProvider } from '@apollo/client/testing';
import { useDecider, GET_DECIDER } from './useDecider';

const getMock = (value = false, decider = '') => [
  {
    request: {
      query: GET_DECIDER,
      variables: {
        name: decider
      }
    },
    result: () => {
      console.log('APOLLO RESULT');

      return {
        data: {
          deciders: [
            {
              decision: value,
              name: decider,
              value: 10
            }
          ]
        }
      };
    }
  }
];

const FakeComponent = ({ decider }) => {
  const { enabled } = useDecider(decider);
  return <div>{enabled ? 'isEnabled' : 'isDisabled'}</div>;
};

const WrappedComponent = ({ decider, value }) => (
  <MockedProvider mocks={getMock(value, decider)} addTypename={false}>
    <FakeComponent decider={decider} />
  </MockedProvider>
);

describe('useDecider', () => {
  it('when decider returns true', () => {
    // should return true
    render(<WrappedComponent decider="fake_decider" value={true} />);
    screen.debug();
    const result = screen.getByText('isEnabled');
    expect(result).toBeInTheDocument();
  });
});

2 个答案:

答案 0 :(得分:1)

我简化了您的钩子实现,并编写了working example

import { useQuery, gql } from "@apollo/client";

export const GET_DECIDER = gql`
  query GetDecider($name: [String]!) {
    deciders(names: $name) {
      decision
      name
      value
    }
  }
`;

export const useDecider = (name) => {
  const { data } = useQuery(GET_DECIDER, { variables: { name } });
  return { enabled: data?.deciders[0]?.decision || false };
};

请注意,在测试中,我还将您的getBy更新为await findBy

describe("useDecider", () => {
  it("when decider returns true", async () => {
    // should return true
    render(<WrappedComponent decider="fake_decider" value={true} />);
    screen.debug();
    const result = await screen.findByText("isEnabled");
    expect(result).toBeInTheDocument();
  });
});

这是因为您需要等待API调用完成才能在页面上显示数据,因此您不希望数据出现在第一个渲染器上。

enter image description here

答案 1 :(得分:0)

来自https://www.apollographql.com/docs/react/development-testing/testing/#testing-the-success-state

<块引用>

要测试您的组件在查询完成后如何呈现,您可以 可以在执行检查之前等待零毫秒超时。 这会将检查延迟到事件循环的下一个“滴答”,即 给 MockedProvider 一个填充模拟结果的机会

在您期望的电话之前尝试添加

  await act(async () => {
    await new Promise((resolve) => setTimeout(resolve, 0));
  });