Simulate change for textarea Jest test

2019-07-15 07:32发布

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条回答
冷血范
2楼-- · 2019-07-15 07:54

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);
});
查看更多
登录 后发表回答