使用纯Jest库(无酶)测试反应形式不起作用

时间:2020-09-08 23:40:56

标签: javascript reactjs jestjs

目前,我仅在开玩笑地测试反应形式。 我的意图是:

  1. 测试提交按钮是否被点击
  2. 测试表单输入数据是否调用了提交按钮
import React, {useState} from 'react';

export const CustomerForm = () => {
    const [form, setForm] = useState({
        fname: "",
        lname: ""
    })

const handleChange = (e)=> {
    // console.log(e);
    setForm({...form, [e.target.name]: e.target.value });
}

const clickSubmit = (e) => {
    e.preventDefault();
    props.handleSubmit(form);
}
 return(
        <form id="customer" onSubmit={clickSubmit}>
            <label htmlFor="firstName">First name</label>
            <input type="text" name="firstName" value="firstName" id="firstName" onChange={handleChange} />
            <label htmlFor="lastName">Last name</label>
            <input type="text" name="lastName" value="lastName" id="lastName" onChange={handleChange} />

            <input type="submit" value="Submit"/>
        </form>
    );
}
 it('check for form is clicked', () => {
        .......
    });

    it('form is submitted with entered data', () => {
        ......
    });

我完全迷失了,因为这是最简单的情况,我几乎不知道如何测试这两个基本条件。 请建议如何进行此测试,以便我学习。

1 个答案:

答案 0 :(得分:1)

如果您不想使用酶进行测试。建议可以先渲染组件,然后使用querySelector seach查找要触发事件的特定元素。您需要导入 “ react-dom”和“ @ testing-library / react”;

示例:

let container;

//With beforeEach will create a new div for each test in the file and adding it.
beforeEach(() => {
  container = document.createElement("div");
  document.body.appendChild(container);
});

it("check for form is clicked", () => {
  act(() => {
    ReactDOM.render(<CustomerForm />, container);
  });

  //querySelector to find the specific DOM element to want to trigger the event.
  const firstName = container.querySelector("#firstName");
  const button = container.querySelector("button");
  firstName.change();
  button.click()
  expect(firstName.value).toBe('')
});

有关更多信息,请参见文档:https://es.reactjs.org/docs/test-utils.html

希望它可以帮助您或至少给您一个想法