| ReactNative |-有条件的渲染?:使用Jest && Enzyme

时间:2019-01-30 12:56:45

标签: reactjs react-native jestjs enzyme

下午好, 我有一个全局结构的组件文件:

  class Component ...

      render(){
           const {array} = this.props

           {!array.includes(value) ?
                (<View ...props
                    id="myComponent"/>
                      ....
                 </View>)  :

                (<View ...props
                   id="myOtherComponent"/>
                      ....
                </View>)
            }
        }

在我的测试文件中,我正在做类似的事情:

describe('Testing Component', () => {
        test('conditional rendering', () => {
        const wrapper = shallow(<Component array={[value]}/>);
        expect(wrapper.find(n => n.prop('id') === "myOtherComponent").exists(true))
    });
});

但是,即使我修改了为数组发送的props,它也总是返回我true ...什么关键字来检查嵌套组件是否已实际验证并呈现...

1 个答案:

答案 0 :(得分:1)

我认为错误在于您的expect参数。

  1. 我将使用findWhere函数而不是find
  2. exists方法不应在此方法中接收参数 情况下,因为它仅接收酶的选择器而不是布尔值(您可以阅读有关here的更多信息);
  3. toBeTruthy行中添加一个expect呼叫。

这里有一种与您相似的情况,我们对此进行了测试,并且效果很好:

it('tests name', () => {
  const mockComponent = shallow(<Component {...props} />);
  const textNode = mockComponent.findWhere(n => n.text() === props.name);
  expect(textNode.exists()).toBeTruthy();
});

所以您的测试最终看起来像这样:

describe('Testing Component', () => {
        test('conditional rendering', () => {
        const wrapper = shallow(<Component array={[value]}/>);
        const node = wrapper.findWhere(n => n.prop('id') === 'myOtherComponent');
        expect(node.exists()).toBeTruthy();
    });
});
相关问题