javascript - 我如何测试 React 组件的方法并将它们包含在我的 Istanbul 覆盖范围内?

标签 javascript unit-testing reactjs testing

我想知道我如何能够测试我的 react 组件的方法并将它们包含在我的 Istanbul 尔测试范围内?

编辑:我正在使用 enzyme 。忘了说了。

例如,我有这个组件:

class SearchFormContainer extends Component {
  static handleToggle = () => {
    const filter = document.querySelector('.filter-container');
    const root = document.getElementById('root');
    if (filter.classList.contains('closed')) {
      filter.classList.remove('closed');
      filter.classList.add('opened');
      root.classList.add('paused');
    } else {
      root.classList.remove('paused');
      filter.classList.remove('opened');
      filter.classList.add('closed');
    }
  };

  updateQuantity = (e) => {
    const { store } = this.props;
    store.setQuantity(e.target.value);
  }

  updateStrength = (e) => {
    const { store } = this.props;
    store.setStrength(e.target.value);
  }

  updateCustomQuantity = (e) => {
    const { store } = this.props;
    let value = e.target.value || '';
    if (!value) {
      store.setPricingError('invalidquantity');
    } else {
      value = value.match(/\d+(\.)?(\d+)?/);

      if (!value) {
        value = '';
      } else {
        value = value[0];
      }

      if (parseFloat(value) <= 0) {
        store.setPricingError('invalidquantity');
      } else if (store.pricingError === 'invalidquantity') {
        store.setPricingError(null);
      }
    }

    store.setCustomQuantity(value);
  }

  render() {
    const {
      styleName,
      openFilterLabel,
      closeFilterLabel,
      updateFilterLabel,
      searchLabel,
      quantityLabel,
      strengthLabel,
      zipLabel,
      zipPlaceholder,
      searchFormAnchor,
      customQuantityPlaceholder,
      store,
      searchBar,
    } = this.props;
    const toggled = 'closed';
    const { useCustomQuantity } = store;

    let inputType = 'predefined';

    if (useCustomQuantity) {
      inputType = 'custom';
    } else {
      inputType = 'predefined';
    }

    const handleCustomInput = () => {
      store.toggleUseCustomQuantity();
    };

这是我尝试运行的测试(请注意,我已经在 describe block 中分配了 store 和 searchBar。

  it('calls upDateQuantity', () => {
    sinon.spy(App.prototype, 'updateQuantity');
    const updateQuantity = sinon.stub();
    const component = shallow(<App
      updateQuantity={updateQuantity}
      store={store}
      searchBar={searchBar}
      openFilterLabel="Filter"
      closeFilterLabel="Close"
      updateFilterLabel="UPDATE"
      searchLabel="Medication Name"
      quantityLabel="Quantity"
      strengthLabel="Strength"
      zipLabel="ZIP code"
      zipPlaceholder="11111"
      searchFormAnchor="SearchForm"
      name="search-field"
      placeholder="Search drug name..."
      customQuantityPlaceholder="Enter Custom Quantity"
    />);
    component.find('#quantitySelector').simulate('click');
    expect(App.updateQuantity.callCount).to.equal(1);
 });

我不确定这是否会测试实际功能,似乎它只会测试事件是否被触发?我收到错误:

TypeError:尝试将未定义的属性 updateQuantity 包装为函数。

我不确定如何测试上面的某些方法,例如 handleToggle、updateQuantity、UpdateStrength 等。我的 react 测试技能很年轻,所以非常感谢任何帮助。谢谢!

最佳答案

我建议使用 enzyme在您的测试中渲染 react 组件并按以下步骤进行。然后,您可以直接使用以下方法测试您的组件方法:

const component = shallow(<MyComponent {...props} />)
component.instance().myMethod()

或者如果你需要在你的组件上触发一个事件,你可以这样做:

import {shallow} from 'enzyme'
import ButtonControl from '../ButtonControl'

describe('ButtonControl component', () => {
  it('handleClick', () => {

    let onClickHandler = jest.fn()
    let props = { handleClick: onClickHandler }

    let component = shallow(<ButtonControl {...props} />)

    component.find('button').first().props().onClick()
    expect(onClickHandler).toHaveBeenCalled()
  })
})

此测试使用 jest 加上代码覆盖率。酵素与 Jasmine 相容,应该很容易适应。

关于javascript - 我如何测试 React 组件的方法并将它们包含在我的 Istanbul 覆盖范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091219/

相关文章:

javascript - 使用 bookblock.js 时获取当前幻灯片编号?

ruby-on-rails - Ruby on Rails 中 RESTful POST 的功能测试

reactjs - 有没有办法在 react-native 中将背景颜色包裹在文本周围?

javascript - Prop 的变化不会导致react - redux应用程序中的重新渲染

javascript - 将异步函数中的数组添加到传单 react 中不起作用

javascript - 如何使用 JavaScript 将字符串中的双引号替换为转义字符双引号?

javascript - 如何在 Ion Modal 中从调用页面获取数据

java - 服务器端 - 进度条

.net - 用于生成边界条件的单元测试工具

Python、单元测试和模拟导入