首页 > 解决方案 > 如何在以 Query 开头的组件中测试 onCompleted、onError 或 onSuccess

问题描述

嗨,我对测试相当陌生,我不知道如何输入查询的 onCompleted 回调。我将 jest 与 react-testing-library 一起使用。

我需要输入 onCompleted 回调来检查其中的 if 语句。

组件:

...

  return (
    <Query
      query={ALL_STICKS}
      variables={{
        name: inputValue,
        idProcess,
        isExceptional,
        codeClasse: data && data.codeClasse,
        codeSubject: data && data.codeSubject,
        codeCompetence: data && data.codeCompetence
      }}
      notifyOnNetworkStatusChange
      onCompleted={dataVaras => {
        if (
          dataVaras.varas_competentes &&
          dataVaras.varas_competentes.items.length === 1
        ) {
          onChange(dataVaras.varas_competentes.items[0]);
        }
      }}
    >
      {({ data: dataSticks, loading }) => {
        return (

          ...
          
        );
      }}
    </Query>
  );

...

当前的测试套件:

imports ...

describe('SelectStick Component', () => {
  afterEach(cleanup);

  it('should render component', async () => {
    const component = createComponent();

    await wait(0);

    expect(component).toBeDefined();
  });
});

function createComponent(props = {}) {
  const defaultProps = {
    onChange: jest.fn(),
    value: {},
    idProcess: 'II00000020000',
    ...props
  };

  return render(
    <MockedProvider mocks={[sticks]} addTypename={false}>
      <SelectStick {...defaultProps} />
    </MockedProvider>
  );
}

标签: javascriptreactjsunit-testinggraphqlreact-testing-library

解决方案


所以,我已经想通了。我正在测试 onError 回调并且我传递给模拟组件的变量不完整,我需要做的就是传递我在模拟查询中定义的所有变量。

这是一个非常初学者的问题,但正如我所说,我是测试 Graphql 查询和突变的新手。


推荐阅读