简体   繁体   中英

How to change value of hook state in jest?

I'm new to jest. I'm trying to change hook state in jest.But I couldn't find any docs for implementing the same.Following is my hook state in SignIn screen.

const [form, setForm] = React.useState({
    email: "",
    phoneNumber: "",
    password: "",
    signUpType: SignUpType.PHONE_NUMBER,
  });

I want to change the state of signUpType to EMAIL while testing.How this can be achieved ?I've done the following

it("Email validation", () => {
    const email = "sample.s@abc.com";
    // Stub the initial state
    const stubInitialState = [{ signUpTyp: "EMAIL" }];
    React.useState = jest.fn().mockReturnValue([stubInitialState, {}]);

    const tree = mount(
      <Provider store={configureStore}>
        <SignIn />
      </Provider>
    );
    expect(tree.find('CustomTextInput[attrName="email"]').prop("value")).toBe(
      ""
    );
    expect(email).toMatch(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/);
  });

But the above code is not working for me.Please help me to find a solution for this.Also the TextInput will be either email or phoneNumebr depending on user selection.

You can try to use the jest.spyOn api to mock the React.useState method:

const stubInitialState = [{ signUpTyp: "EMAIL" }];
const mockedSetform = jest.fn();

jest.spyOn(React, 'useState').mockReturnValue([stubInitialState, mockedSetform]);

jest.spyOn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM