programing

효소는 onChange 이벤트를 시뮬레이트합니다.

starjava 2023. 3. 3. 16:47
반응형

효소는 onChange 이벤트를 시뮬레이트합니다.

모카랑 효소랑 반응 성분 테스트 중이야컴포넌트는 다음과 같습니다(물론 심플화를 위해 생략).

class New extends React.Component {

  // shortened for simplicity

  handleChange(event) {
    // handle changing state of input

    const target = event.target;
    const value = target.value;
    const name = target.name
    this.setState({[name]: value})

  }


  render() {
    return(
      <div>
        <form onSubmit={this.handleSubmit}>
          <div className="form-group row">
            <label className="col-2 col-form-label form-text">Poll Name</label>
            <div className="col-10">
              <input
                className="form-control"
                ref="pollName"
                name="pollName"
                type="text"
                value={this.state.pollName}
                onChange={this.handleChange}
              />
            </div>
          </div>

          <input className="btn btn-info"  type="submit" value="Submit" />
        </form>
      </div>
    )
  }
}

테스트 결과는 다음과 같습니다.

it("responds to name change", done => {
  const handleChangeSpy = sinon.spy();
  const event = {target: {name: "pollName", value: "spam"}};
  const wrap = mount(
    <New handleChange={handleChangeSpy} />
  );

  wrap.ref('pollName').simulate('change', event);
  expect(handleChangeSpy.calledOnce).to.equal(true);
})

사용자가 텍스트를 입력했을 때<input>권투 시합을 하다handleChange메서드가 호출됩니다.위의 테스트는 다음과 같이 실패합니다.

AssertionError: expected false to equal true
+ expected - actual

-false
+true

at Context.<anonymous> (test/components/new_component_test.js:71:45)

내가 뭘 잘못하고 있지?

편집

분명히 해야겠어, 내 목표는 그 방법이handleChange호출됩니다.내가 어떻게 그럴 수 있을까?

프로토타입을 통해 직접 방법을 탐색할 수 있습니다.

it("responds to name change", done => {
  const handleChangeSpy = sinon.spy(New.prototype, "handleChange");
  const event = {target: {name: "pollName", value: "spam"}};
  const wrap = mount(
    <New />
  );
  wrap.ref('pollName').simulate('change', event);
  expect(handleChangeSpy.calledOnce).to.equal(true);
})

또는 인스턴스의 메서드에서 spy를 사용할 수 있지만, 마운트 호출 후 컴포넌트가 이미 렌더링되어 onChange가 이미 원래 메서드에 바인딩되어 있기 때문에 강제로 업데이트해야 합니다.

it("responds to name change", done => {
  const event = {target: {name: "pollName", value: "spam"}};
  const wrap = mount(
    <New />
  );
  const handleChangeSpy = sinon.spy(wrap.instance(), "handleChange");
  wrap.update(); // Force re-render
  wrap.ref('pollName').simulate('change', event);
  expect(handleChangeSpy.calledOnce).to.equal(true);
})

언급URL : https://stackoverflow.com/questions/43426885/enzyme-simulate-an-onchange-event

반응형