1

Currently I am testing a react form with only jest. My intention is to:

  1. test that submit button is clicked
  2. test that submit button is called with forms entered data
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', () => {
        ......
    });

I am completely lost as it is the most simplest scenario and I barely know how to test these two basic conditions. Please suggest how to do this tests so that I can learn.

1 Answer 1

1

If you dont want to use Enzyme for the testing. a recommendation could be to render the component and then with querySelector seach for the specific element you want trigger the event. You need to import "react-dom" and "@testing-library/react";

example:

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('')
});

Here the doc for more information:https://es.reactjs.org/docs/test-utils.html

Hope it helps you or least give you an a idea

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.