Как шутить над функцией, находящейся внутри другого реагирующего компонента? - PullRequest
1 голос
/ 10 февраля 2020

Я пытался написать тесты для следующего реактивного компонента, который возвращает разные компоненты в зависимости от моих реквизитов:

const Choice: React.FC<States> = props => {
    function getChoiceComponent(): JSX.Element {
        if (props.choices) {
            return <FirstComponent {...props} />;
        } else {
            return <SecondComponent {...props} />;
        }
    }

    return <>{getChoiceComponent()}</>;
};

Как я могу смоделировать getChoiceComponent функцию и протестировать ее?

1 Ответ

0 голосов
/ 11 февраля 2020

Мы должны проверить компонент реагирования, изменив реквизиты и состояние, а не тестировать метод getChoiceComponent напрямую. Вот решение для модульного тестирования:

index.tsx:

import React from 'react';
import FirstComponent from './first';
import SecondComponent from './second';

type States = any;

const Choice: React.FC<States> = (props) => {
  function getChoiceComponent(): JSX.Element {
    if (props.choices) {
      return <FirstComponent {...props} />;
    } else {
      return <SecondComponent {...props} />;
    }
  }

  return <>{getChoiceComponent()}</>;
};

export default Choice;

first.tsx:

import React from 'react';
const FirstComponent = () => <div>first component</div>;

export default FirstComponent;

second.tsx:

import React from 'react';
const SecondComponent = () => <div>second component</div>;

export default SecondComponent;

index.test.tsx:

import Choice from './';
import FirstComponent from './first';
import SecondComponent from './second';
import React from 'react';
import { shallow } from 'enzyme';

describe('60152774', () => {
  it('should render first component', () => {
    const props = { choices: [] };
    const wrapper = shallow(<Choice {...props}></Choice>);
    expect(wrapper.find(FirstComponent)).toBeTruthy();
  });

  it('should render second component', () => {
    const props = {};
    const wrapper = shallow(<Choice {...props}></Choice>);
    expect(wrapper.find(SecondComponent)).toBeTruthy();
  });
});

Результаты модульных испытаний с отчетом о покрытии:

 PASS  stackoverflow/60152774/index.test.tsx
  60152774
    ✓ should render first component (20ms)
    ✓ should render second component (5ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |   88.24 |      100 |      50 |     100 |                   
 first.tsx  |      75 |      100 |       0 |     100 |                   
 index.tsx  |     100 |      100 |     100 |     100 |                   
 second.tsx |      75 |      100 |       0 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.065s

Исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60152774

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...