首页 > 解决方案 > 如何在反应中测试或从状态中获取价值?

问题描述

嗨,你能告诉我如何在反应中测试或从状态中获取价值吗?收到错误 wrapper.instance(...).handleClickShowPassword is not a function

这是我的代码 https://codesandbox.io/s/l2lk4n794l

it("toggle showpassword value", () => {
    wrapper.setState({ showPassword: false });
    wrapper.instance().handleClickShowPassword();

    expect(wrapper.state.showPassword).toEqual(true);
  });

在此处输入图像描述

标签: reactjsreduxjestjsenzyme

解决方案


由于LoginContainer是使用 HOC 包装的,因此您要么需要在没有withStylesHOC的情况下导出组件,要么dive在包装器上使用来获取组件的实例。也是state一个函数component instance,因此您需要调用它来访问状态

describe("<LoginContainer/>", () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<LoginContainer />);
  });

  it("toggle showpassword value", () => {
    const comp = wrapper.dive();
    comp.dive().setState({ showPassword: false });
    comp.instance().handleClickShowPassword();
    expect(comp.state("showPassword")).toEqual(true);
  });
});

工作演示


推荐阅读