ReactJS:如何测试参考?

问题描述 投票:2回答:1

这是反应组分中使用的函数。正如您所看到的,我正在使用ref来关注另一个组件的特定输入元素。

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

现在我想通过jestJS测试focus()被调用。

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,所以这种尝试不起作用。

如何在测试中设置参考?


更新

这就是我的组件的样子:

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>
    )
  }
}
javascript reactjs unit-testing jestjs
1个回答
1
投票

尝试做这样的事情:

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评论的那样,浅层渲染无法持有ref
  2. 你不需要将ref作为道具传递(事实上它是错的)
  3. 在我有wrapper.find('#foo')的地方,用Input中DOM元素的class / id替换foo
© www.soinside.com 2019 - 2024. All rights reserved.