Ad

How To Test Or Get Value From State In React?

- 1 answer

Hi could you please tell me How to test or get value from state in react ? getting error wrapper.instance(...).handleClickShowPassword is not a function

here is my code https://codesandbox.io/s/l2lk4n794l

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

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

enter image description here

Ad

Answer

Since LoginContainer is an wrapped with an HOC, you either need to export the component without withStyles HOC or use dive on the wrapper to get the instance of the component. Also state is a function on component instance and hence you need to call it to access state

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);
  });
});

Working demo

Ad
source: stackoverflow.com
Ad