Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate change for textarea Jest test

I have the following component:

render() {
    return (
        <textarea onChange={this.handlechange}  value="initial value" />
    )
}

handlechange = (e) => {
    console.log(e.currentTarget.value);
}

and the corresponding test that's supposed to check if on change fired correctly or not:

const TEST_PROPS = {
    OnChange: jest.fn()
}

it("Fires on change correctly", () => {
    const textArea = enzyme.mount(<TextArea {...TEST_PROPS} />);

    jest.resetAllMocks();

    expect(textArea.find("textarea").simulate("change"));
    expect(TEST_PROPS.OnChange).toHaveBeenCalledTimes(1);
    expect(TEST_PROPS.OnChange).toHaveBeenLastCalledWith(//what should go here?//);
});

I want to pass in the value of the new target.value once the onchange is fired to the toHaveBeenLastCalledWith function. How can I do this?

like image 924
blankface Avatar asked Dec 02 '25 00:12

blankface


1 Answers

simulate event accepts a event obj as a 2nd arg, which you can use it in your 2nd assertion.

const TEST_PROPS = {
    OnChange: jest.fn()
}

it("Fires on change correctly", () => {
    const textArea = enzyme.mount(<TextArea {...TEST_PROPS} />);
    const event = { target: { value: "sometext" } };
    jest.resetAllMocks();

    expect(textArea.find("textarea").simulate("change", event));
    expect(TEST_PROPS.OnChange).toHaveBeenCalledTimes(1);
    expect(TEST_PROPS.OnChange).toHaveBeenLastCalledWith(event);
});
like image 170
Galeel Bhasha Avatar answered Dec 03 '25 13:12

Galeel Bhasha