本文介绍了ReactJS:如何测试参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在React组件中使用的功能.如您所见,我正在使用ref来关注另一个组件的特定输入元素.

This is a function used in a react component. As you can see I'm using ref to get the focus on a specific input element of another component.

myFunction (param) {
  this.refInput && this.refInput.focus()
}

现在,我想通过jestJS测试是否调用了focus().

Now I would like to test via jestJS for the focus() to have been called.

it('myFunction() should call focus()', () => {
  // SETUP
  const refInput = { focus: jest.fn() }
  wrapper = shallow(<Example
    refInput={refInput}
  />)
  // EXECUTE
  wrapper.instance().myFunction('anything')
  // VERIFY
  expect(refInput.focus).toHaveBeenCalled()
})

但这是错误的,因为我将refInput作为属性传递.但是不是 this.props.refInput,因此此尝试无效.

But this is wrong, as I pass the refInput as a property. But it is not this.props.refInput, so this attempt is not working.

如何在测试中设置裁判?

How do I setup a ref in my test?

更新

这是我的组件的样子:

class Example extends Component {
  setStep (state) {
    state.term = ''
    this.setState(state)
    this.refInput && this.refInput.focus()
  }

  render () {
    return (
      <div>
        <Step onClick={this.setStep.bind(this, this.state)}>
          <Step.Content title='title' description='description' />
        </Step>
        <Input ref={input => { this.refInput = input }} />
      </div>
    )
  }
}

推荐答案

尝试执行以下操作:

it('myFunction() should call focus()', () => {
  // SETUP
  wrapper = mount(<Example />)
  // EXECUTE
  wrapper.instance().myFunction('anything')
  // VERIFY
  const elem = wrapper.find('#foo');
  const focusedElement = document.activeElement;
  expect(elem.matchesElement(focusedElement)).to.equal(true);
})

注意事项:

  1. 使用Mount而不是Shallow,就像@Marouen Mhiri所说的那样,浅层渲染无法保存参考

  1. Use Mount rather than Shallow, as @Marouen Mhiri commented, shallow rendering can't hold a ref

您不需要将ref作为道具传递(实际上这是错误的)

You don't need to pass ref as props (in fact it's wrong)

在有wrapper.find('#foo')的地方,将foo替换为Input中DOM元素的类/id

Where I have wrapper.find('#foo'), replace foo by class/id of the DOM element in Input

这篇关于ReactJS:如何测试参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:18