如何测试将使用钩子更改状态值的“ onChange”功能

时间:2019-12-10 14:03:50

标签: reactjs react-hooks enzyme

如何测试“ onChange”功能 谁将通过钩子改变国家的价值 直接在react js中使用anzyme。 如何测试“ onChange”功能 谁将通过钩子改变国家的价值 直接在react js中使用酶。

function BrockerConfig(props) {
  const [disabled, setDisabled] = useState(false);

  return (
    <Switch
      onChange={setDisabled}
      checkedChildren={<IntlMessages id="settings.Switch.Activation" />}
      unCheckedChildren={<IntlMessages id="settings.Switch.Deactivation" />}
    />
  );
}

it("onChange state of Disabled", () => {
  const BrockerConfigComponent = () => shallow(<BrockerConfigForm />).dive();
  const TotalSwitchs = BrockerConfigComponent().find(Switch);
  expect(TotalSwitchs.length).toBe(1);

  TotalSwitchs.simulate("change", "true");
  expect(TotalSwitchs.state("disabled")).toEqual("true");
});

1 个答案:

答案 0 :(得分:0)

第一件事:将BrockerConfigComponent作为函数意味着对它的每次调用都返回新的且完全独立的实例。您将无法对其进行变异并检查结果。让我们将其作为变量:

const BrockerConfigComponent = shallow(<BrockerConfigForm />).dive();

包装中的酶(find()filter()返回的所有内容)are read-only。您需要在模拟操作后重新获取它:

  TotalSwitchs.simulate("change", "true");
  expect(BrockerConfigComponent.find(Switch).state("disabled")).toEqual("true");

为了避免将来再出现这种情况,最好不要将.find()放在中间变量中。

现在state一样。设置或声明状态始终是错误的举动,因为它是实现细节。在这里,它甚至根本无法工作,因为对于shallow(),嵌套的组件(例如此处的Switch)不会被渲染/初始化。

那你该怎么办?根据渲染结果进行验证。通过调用道具进行交互(“模拟”事件也称为调用道具)。假设您的disabled变量作为prop传递给相同的Switch

BrockerConfigComponent.find(Switch).simulate("change");
expect(BrockerConfigComponent.find(Switch).props().ifIDisabledProp).toBe(true);