3

如何断言 React Native 测试库中的按钮被禁用?我会想象这样的事情:

expect(getByRole('button')).toBeDisabled()

但 RNTL 不提供toBeDisabled断言。

4

1 回答 1

2

由于 RN 的性质,这是一个常见问题。我已经设法通过测试回调函数的实际效果来达到我的目标,而不仅仅是比较调用次数或类似的东西......

describe('<Button /> - ', () => {
  let state = false
  const onPressMock = jest.fn(() => {
    state = !state
  })
  const props: ButtonProps = {
    text: 'Submit',
    onPress: onPressMock
  }

  it('should become disabled', () => {
    // act: render container
    const { container } = render(<Button {...props} isDisabled />)

    // assert 1: check if button receives {isDisabled}
    expect(container.props.isDisabled).toEqual(true)
    
    // act2: fire callback
    fireEvent(container, 'onPress')
    
    // assert 2: "state" should remain as false.
    expect(state).toEqual(false)
  })
})

确保您的按钮看起来像:

const isBlockedInteraction: boolean = isLoading || isDisabled;

return (
  <TouchableOpacity
    onPress={!isBlockedInteraction && onPress}
    disabled={isBlockedInteraction}
    {...props}
  />
)
于 2021-03-14T09:23:19.820 回答