Simulate change for textarea Jest test

2019-07-15 07:41发布

问题:

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?

回答1:

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