2017-09-25 55 views
0

新的测试,所以不是我敢肯定如何处理这个。我的组件中有一个bool prop,它决定了元素的className。布尔被设定的形式是否是有效或不显示的div包含错误消息反应js测试布尔支柱与Jest

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

如何开玩笑测试此?

在此先感谢

UPDATE: 继@ hemerson - 卡林的答案,这里是我的测试。但不能确定为什么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() 
    }) 

}) 
+0

请加你开玩笑代码太 –

回答

-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(); 

}) 

希望它可以帮助

0

这两种情况下使用快照测试:

describe('YourComponent test',() => { 
    let component 

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

    it('should render valid mode',() => { 
    component.setProps({ isValid: true }) 
    expect(component).toMatchSnapshot() 
    }) 

    it('should render invalid mode',() => { 
    component.setProps({ isValid: false }) 
    expect(component).toMatchSnapshot() 
    }) 
}) 
+0

感谢您的回复和帮助,但测试(用两种方法)保持不幸失败'''希望(对象).toHaveProperty(路径,值) 预期目的: { “的isValid”:假} 要具有嵌套属性: “的className” 随着一个值: ''' – Mauro74

+0

不推荐第二种方法 “login__error错误”(这是为什么我写了'类似'的东西)。在第一种情况下,你可以登录'component.props()'吗? – mersocarlin

+0

'组件'似乎是未定义的。你确定这不是一个错字吗?你是从酵素中输入'mount'的吗? – mersocarlin