酶-如何访问和设置< input>值? [英] Enzyme - How to access and set <input> value?

查看:70
本文介绍了酶-如何访问和设置< input>值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用 mount 时如何访问< input> 的值,我感到困惑。这是我测试的结果:

I'm confused about how to access <input> value when using mount. Here's what I've got as my test:

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.render().attr('value'));
    input.simulate('focus');
    done();
  });

控制台将打印出 undefined 。但是,如果我稍微修改一下代码,它就会起作用:

The console prints out undefined. But if I slightly modify the code, it works:

  it('cancels changes when user presses esc', done => {
    const wrapper = render(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.val());
    input.simulate('focus');
    done();
  });

当然,除了 input.simulate 行失败,因为我现在正在使用 render 。我都需要正常工作。我该如何解决?

Except, of course, the input.simulate line fails since I'm using render now. I need both to work properly. How do I fix this?

编辑

我应该提到,< EditableText /> 不是受控组件。但是,当我将 defaultValue 传递到< input /> 时,它似乎设置了该值。上面的第二个代码块确实打印出了该值,同样,如果我检查Chrome中的输入元素并在控制台中键入 $ 0.value ,它会显示期望值。

I should mention, <EditableText /> is not a controlled component. But when I pass defaultValue into <input />, it seems to set the value. The second code block above does print out the value, and likewise if I inspect the input element in Chrome and type $0.value in the console, it shows the expected value.

推荐答案

知道了。 (更新/改进版本)

Got it. (updated/improved version)

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    input.simulate('focus');
    input.simulate('change', { target: { value: 'Changed' } });
    input.simulate('keyDown', {
      which: 27,
      target: {
        blur() {
          // Needed since <EditableText /> calls target.blur()
          input.simulate('blur');
        },
      },
    });
    expect(input.get(0).value).to.equal('Hello');

    done();
  });

这篇关于酶-如何访问和设置&lt; input&gt;值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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