用Jest反应js测试布尔道具

时间:2017-09-25 13:53:03

标签: javascript reactjs jestjs

新测试,所以我不确定如何处理这个问题。我的组件中有一个bool prop,用于确定元素的className。无论表单是否有效,都会设置布尔值,显示包含错误消息的div

<div>
   <div className={!this.props.isValid ? 'login__error error' : 'hidden'}>
      ...
   </div>
</div>

如何在Jest中测试?

提前致谢

更新: 按照@ hemerson-carlin的回答,这是我的测试。但是RangeError: Invalid string length不确定为什么会一直失败。

describe('Given invalid details the form should display an error', () => {
  let component

  beforeEach(() => {
    component = mount(<Login />)
  })

  it('should render valid mode', () => {
    component.setProps({ isValid: true })
    console.log(component.props())

    expect(component).toMatchSnapshot()
  })

  it('should render invalid mode', () => {
    component.setProps({ isValid: false })
    console.log(component.props())

    expect(component).toMatchSnapshot()
  })

})

2 个答案:

答案 0 :(得分:0)

对两种情况使用快照测试:

BackendUserAuthentication

答案 1 :(得分:-1)

最后找到了一条路,比我想象的要简单。

test('Given invalid details the form should display an error', () => {

  const login = mount(<Login isValid={false}/>);
  expect(login.find('.error').hasClass('login__error')).toBeTruthy();

})

test('Given valid details the form should not display an error', () => {

  const login = mount(<Login isValid={true}/>);
  expect(login.find('.error').hasClass('hidden')).toBeTruthy();

})

希望有所帮助

相关问题