Simulate change for textarea Jest test

送分小仙女□ 提交于 2019-12-24 01:56:05

问题


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


来源:https://stackoverflow.com/questions/50110930/simulate-change-for-textarea-jest-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!