umesh shakya
umesh shakya

Reputation: 237

Simulate Is not working without state in react js

This is my functional Component.

const InputText = (props: Props) => {
 return (
  <div>
  <StyledInput type="text" placeholder={props.placeholder} />
  <br></br>
   </div>
   );
  };
 export default InputText;

and this is my test cases.
enter code here
  const wrap = (props: Props) => shallow(<InputText {...props} />);
  it("input text change", () => {
// const wrap = (props: Props) => mount(<StyledInput {...props} />);
  const wrapper = wrap({ placeholder: "UserName" });
  const usernameInput = wrapper.find("input");
  usernameInput.simulate("change", { target: { value: "[email protected]" } });
  expect(usernameInput.text()).toEqual("[email protected]");
});

So this test case failed with error:

Expected "[email protected]" and recevide:"";

How can I resolve this?

Upvotes: 1

Views: 55

Answers (1)

Beginner
Beginner

Reputation: 9125

Check this one

App.test.js

import React from "react";
import { shallow, configure } from "enzyme";
import Input from "./App";
import Adapter from 'enzyme-adapter-react-16';

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


describe("Input Component", () => {
  it("should trigger the onchange", () => {
    const wrapper = shallow(<Input />);
    wrapper
      .find("input")
      .simulate("change", { target: { value: "on typing" } });
      expect(wrapper.find('input').props().value).toBe('on typing')
  });
});

App.js

import React, { useState } from "react";

const InputText = props => {
  const [inputText, setInput] = useState("");

  const onHandleChange = e => {
    setInput(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={inputText}
        onChange={onHandleChange}
      />
      <br />
    </div>
  );
};

export default InputText;

Upvotes: 1

Related Questions