Search code examples
reactjstestingjestjstesting-library

Testing a function inside a component with jest and testing-library


I'm new with testing-library and jest and I'm trying to test a function inside of the component that changes the value of an input. The component is a form with another component that it's an input.

export const Form = () => {
    const [name, setName] = useState("");
    const handleOnSubmit = e => {
        e.preventDefault();
        const form = e.target;
    };
    const inputChange = (param) => (e) => {
        const inputValue = e.target.value;
        setName(inputValue);
    };
    return (
        <form className="form" onSubmit={handleOnSubmit}>
            <InputGroup text="name" type="text" value={name} functionality={inputChange("name")}/>
            <Button type="submit"  disabled={name === undefined}/>
        </form>
    );
};

export default Form;

The InputGroup Component looks like this

export const InputGroup = ({type, id, value, required, functionality, text}) => {
    return (
        <label>{text}</label>
        <input className="input" type={type} id={id} name={id} value={value}
            required={required} onChange={functionality}
        />
    );
};

I have tried something like this, but I'm not pretty sure on how to test a function that is directly on the component Form and that it's being passed to the component InputGroup.

describe("Form", () => {
    let value;
    let component;
    const handleSubmit = jest.fn();
    const handleChange = ev => {
        ev.preventDefault();
        value = ev.currentTarget.value;
    }
    beforeEach(() => {
        component = render(
            <Form onSubmit={handleSubmit} functionality={handleChange} />
        );
    });
    it("check error name is triggered", () => {
        const input = component.getByText("name");
        fireEvent.change(input, {target: {value: "aaa"}});
    });
});

I get an error thats says "The given element does not have a value setter", so how can I pass the inputChange function to the InputGroup Component?


Solution

  • Ok, thanks for sharing the InputGroup. So you can test the InputGroup easily.

    describe("InputGroup", () => {
      it("check error name is triggered", () => {
        const fn = jest.fn()
        render(<InputGroup functionality={functionality} />)
        fireEvent.change(input, {target: {value: "aaa"}});
        expect(fn).toHaveBeenLastCalledWith(...)
      });
    });
    

    Just an idea. The above code might not run as posted. Ok, now comes to the Form. The step might be similar but it might take you some time to get around, but you don't need to test the functionality again, simply because this prop has nothing to do with Form. From the form perspective, it only cares onSubmit, so you can test against that in the similar way that posted earlier.