在React JS中没有状态无法模拟

时间:2019-11-07 06:27:26

标签: reactjs jestjs enzyme

这是我的功能组件。

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: "umesh@hcl.com" } });
  expect(usernameInput.text()).toEqual("umesh@hcl.com");
});

因此该测试用例失败,并显示错误:

  

预期为“ Umesh@hcl.com”,并输入:“”;

我该如何解决?

1 个答案:

答案 0 :(得分:1)

选中此

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;