代码之家  ›  专栏  ›  技术社区  ›  foufrix

测试中组件的访问状态

  •  0
  • foufrix  · 技术社区  · 7 年前

    我有一个组件,当我们注入不同的道具时,它会改变一些道具。

    我正在努力寻找一种简单的方法来从我的测试中获取我的浅组件的状态。

    代码如下:

    describe('componentWillReceiveProps', () => {
        it('update state isDedicatedDealPriceSelected to true', () => {
            const productComponent = shallow(<Product selectedPriceOption="Test" />);
            productComponent.setProps({ selectedPriceOption: 'dedicatedDealPrice' });
            expect(productComponent.props.isDedicatedDealPriceSelected).toBeTruthy();
        });
    });
    

    我没有定义,我想访问的道具是专门选定的,应该是真实的。我想我在productcomponent.props.isdicateddelpriceselected的最后一行写错了什么。 如何访问组件的道具?

    我使用enzime在测试中用jast浅显组件。

    提前感谢!

    编辑:我不是要访问道具,而是要访问状态!不好意思把钱放错了

    2 回复  |  直到 7 年前
        1
  •  0
  •   adz5A    7 年前

    似乎 setProps 在重新呈现后执行回调。也许您的测试需要是异步的,断言需要在这个回调中完成。

    仅从示例中 componentWillReceiveProps 似乎是同步调用的。

    https://airbnb.io/enzyme/docs/api/ShallowWrapper/setProps.html

        2
  •  0
  •   foufrix    7 年前

    要访问浅渲染组件的状态,可以使用以下方法访问它:

    const wrapper = shallow(<component />);
    wrapper.state().componentVar
    

    要访问浅渲染组件的函数,可以使用以下方法访问它:

    wrapper.instance().componentFunction()