【问题标题】:|ReactNative|-Conditional rendering ?: with Jest && Enzyme|ReactNative|-条件渲染?:使用 Jest && Enzyme
【发布时间】:2019-01-30 12:56:44
【问题描述】:

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

  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...检查嵌套组件是否实际验证和渲染的关键字是什么...

【问题讨论】:

    标签: reactjs react-native jestjs enzyme


    【解决方案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();
        });
    });
    

    【讨论】:

    • 如果组件实际上是嵌套组件并且我的条件渲染 &lt;View&gt; 不是主要父级,findWhere 是否管理这种情况?
    • 好吧,看起来就像一个魅力,我很接近;)谢谢你的帮助
    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2020-10-20
    • 2022-06-15
    • 2020-11-02
    • 2016-12-18
    • 2016-10-29
    相关资源
    最近更新 更多