模拟textarea Jest测试的更改 [英] Simulate change for textarea Jest test

查看:179
本文介绍了模拟textarea Jest测试的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下组成部分:

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

一旦将onchange触发到toHaveBeenLastCalledWith函数,我想传入新的target.value的值.我该怎么办?

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?

推荐答案

模拟事件接受事件obj作为第二个arg,您可以在第二个断言中使用它.

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

这篇关于模拟textarea Jest测试的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆