Текущее значение реактивного сопротивления в шутке для мелкого испытания - PullRequest
2 голосов
/ 16 апреля 2019

Я пытаюсь смоделировать this.ref.current.value как часть теста функции в моем компоненте React. В настоящее время current является нулевым, потому что я выполняю поверхностное монтирование моего компонента. Я пытаюсь найти способ смоделировать то, что current.value возвращает для моего ref, чтобы я мог проверить другую часть функции, значение refs на самом деле не имеет значения для этого теста.

Фактическая функция:

copyDefinitionTarget = selectedInput => () => {
    // get and select the input value
    const copyText = this[`${selectedInput}`].current.value;

    // copy to clipboard
    navigator.clipboard.writeText(copyText);
  };

Тестовый код:

it('calls navigator.clipboard appropriately to copy the text in copyDefinitionTarget', () => {
    component = shallow(<Alert {...props} />);

    component
      .dive()
      .find('Item')
      .dive()
      .find('Button')
      .simulate('click');

    expect(navigator.clipboard.writeText).toHaveBeenCalled();
  });

Сбой теста:

TypeError: Cannot read property 'value' of null

      50 |     // get and select the input value
    > 51 |     const copyText = this[`${selectedInput}`].current.value;

Есть ли способ сделать это? Я забочусь о проверке того, что navigator.clipboard назывался не так, как он назывался.

Обновление, потому что я изменил свой код, чтобы использовать this.ref вместо stringRefName Фактическая функция:

copyDefinitionTarget = selectedInput => () => {
    // get and select the input value
    const copyText = selectedInput.current.value;
    // copy to clipboard
    navigator.clipboard.writeText(copyText);
  };

Тестовый код:

it('calls navigator.clipboard appropriately to copy the text in copyDefinitionTarget', () => {
    component = shallow(<Alert {...props} />);
instance = component.instance();

    // we are clicking on the first Alert Item
    // so mock that ref specifically
    instance.firstNameRef = {
      current: {
        value: 'stuff'
      }
    };

    component
      .dive()
      .find('Item')
      .dive()
      .find('Button')
      .simulate('click');

    expect(navigator.clipboard.writeText).toHaveBeenCalled();
  });

Вызов функции:

<Item
 inputRef={this.firstNameRef}
 inputValue={`${realmName}`}
 copyDefinitionTarget={this.copyDefinitionTarget(this.firstNameRef)}
/>

Ответы [ 2 ]

3 голосов
/ 16 апреля 2019

Вы можете пойти дальше и сделать что-то вроде этого:

const component = shallow(<Alert {...props} />);
const selectedInput = 'ref';
component.instance()[selectedInput] = {
  current: {
    value: 'stuff'
  }
}
navigator.clipboard = {writeText: jest.fn()}
component
  .dive()
  .find('Item')
  .dive()
  .find('Button')
  .simulate('click');
expect(navigator.clipboard.writeText).toHaveBeenCalled();

Примечание: я не уверен, какой должна быть строка selectedInput, вы могли бы пропустить любую строку, которая соответствует вашей реальнойкод компонента.

Поскольку ссылка существует как свойство экземпляра в компоненте, вы можете просто передать любой желаемый объект, пока он выглядит как current.value, тогда вы можете заменить функцию копирования на макет, имитируя щелчока затем посмотреть, если writeText был вызван.

0 голосов
/ 17 апреля 2019

Публикация другого подхода, который может быть использован в случае, если вы передаете фактическую ссылку вместо строки. Я вытащил получение значения из ссылки в его собственную функцию и высмеял это в моем тесте

Фактический код:

  // get the value from ref
  getRefValue = ref => ref.current.value;

  // copy value
  copyDefinitionTarget = selectedInput => () => {
    // get and select the input value
    const copyText = this.getRefValue(selectedInput);
    // copy to clipboard
    navigator.clipboard.writeText(copyText);
  };

Тестовый код:

it('calls navigator.clipboard appropriately to copy the text in copyDefinitionTarget', () => {
    component = shallow(<MetadataAlert {...props} />);
    instance = component.instance();

    jest.spyOn(instance, 'getRefValue').mockImplementationOnce(() => '?');

    component
      .dive()
      .find('Item')
      .dive()
      .find('Button')
      .simulate('click');

    expect(navigator.clipboard.writeText).toHaveBeenCalled();
  });
...