测试物料UI无线电检查值

时间:2019-12-10 20:23:08

标签: reactjs redux react-redux material-ui react-hooks

  • 我有一个使用React用Redux编写的功能组件 钩子。
  • 我正在使用带有酶的Jest进行测试。
  • 该组件呈现Material UI单选按钮(下面的代码示例):
<RadioGroup>
  <FormControlLabel
    value="batchName"
    label="Batch Name"
    name="batchName"
    control={
      <Radio
        disableRipple
        name="batchName"
        color="primary"
        checked={searchBy === 'batchName'}
        onClick={() => {dispatch(actions.setBatchSearchBy('batchName'))}}
      />
    }
  />
  <FormControlLabel
    value="firstPaymentDate"
    label="First Payment Date"
    name="firstPaymentDate"
    control={
      <Radio:
        disableRipple
        name="firstPaymentDate"
        color="primary"
        checked={searchBy === 'firstPaymentDate'}
        onClick={() => {dispatch(actions.setBatchSearchBy('firstPaymentDate'))}}
      />
    }
  />
</RadioGroup>

测试文件:

import React from 'react';
import { BatchHeaderComponent } from '../../../components/batchManagement/BatchHeaderComponent';
import configureStore from '../../../store';
import {Provider} from "react-redux";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Radio from "@material-ui/core/Radio";

Enzyme.configure({ adapter: new Adapter() });

describe('BatchHeaderComponent', () => {
  it('mounts to the DOM with its sub-components', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent/>
    </Provider>);
    expect(wrapper.find(BatchHeaderComponent)).toBeDefined();
  });

  it('changes searchBy when a new option has been selected', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent />
    </Provider>);
    const radio = wrapper.find(Radio).last();
    console.log(radio.debug());
    // radio.simulate('change', {target: {name: 'firstPaymentDate', checked: true}});
    // radio.prop('onChange', {target: { name: 'firstPaymentDate', checked: true}});
    radio.simulate('click');
    console.log(radio.debug());
    expect(radio.props().checked).toEqual(true);
  });
});

在模拟“单击”或“更改”事件时,我无法更改“已检查”值。

无论我走哪条路,被检查的值仍然为假。

任何建议将不胜感激。 谢谢!

1 个答案:

答案 0 :(得分:0)

我知道了。我需要再次运行wrapper.find才能看到更新的更改。

  it('changes searchBy when a new option has been selected', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent />
    </Provider>);
    const radio = wrapper.find(Radio).last();
    radio.simulate('click');
    expect(wrapper.find(Radio).last().props().checked).toEqual(true);
  });