当前位置: 首页 > 面试题库 >

如何在React组件上测试道具更新

封飞
2023-03-14
问题内容

什么是对React组件prop更新进行单元测试的正确方法。

这是我的测试装置;

describe('updating the value', function(){
        var component;
        beforeEach(function(){
            component = TestUtils.renderIntoDocument(<MyComponent value={true} />);
        });

        it('should update the state of the component when the value prop is changed', function(){
            // Act
            component.props.value = false;
            component.forceUpdate();
            // Assert
            expect(component.state.value).toBe(false);
        });
});

这可以正常工作,并且测试通过了,但是显示了反应警告消息

'Warning: Dont set .props.value of the React component <exports />. Instead specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.'

我要测试的只是属性的更新,而不是使用其他属性创建元素的新实例。有没有更好的方法来执行此属性更新?


问题答案:

AirBnB的酶库为这个问题提供了一个优雅的解决方案。

它提供了一个setProps方法,可以在浅包装或jsdom包装上调用该方法。

    it("Component should call componentWillReceiveProps on update", () => {
        const spy = sinon.spy(Component.prototype, "componentWillReceiveProps");
        const wrapper = shallow(<Component {...props} />);

        expect(spy.calledOnce).to.equal(false);
        wrapper.setProps({ prop: 2 });
        expect(spy.calledOnce).to.equal(true);
    });


 类似资料:
  • 问题内容: 我使用下面的代码在React组件上设置默认道具,但是它不起作用。在该方法中,我可以看到输出“ undefined props”已打印在浏览器控制台上。如何为组件道具定义默认值? 问题答案: 您忘记合上支架了。

  • 我有一个React应用程序,其中来自父组件的道具被传递到子组件,然后道具设置子组件的状态。 如何让它更新子组件上的状态? 我的精简代码:

  • 我想在Vue中创建自己的复选框。我想使用fontawesome中的两个图标(锁定和解锁)。选中“我的复选框”后,图标应锁定,否则将解锁。 这是我的代码: 我收到一个错误: 无法分配给“checked”,因为它是常量或只读属性 你能帮我解决这个问题吗?

  • 我正在做一个React-Native项目,我意识到React-Native似乎打破了React-flow(父到子)道具更新。 基本上,我是从“应用程序”组件调用“菜单”组件,将一个道具传递给“菜单”。然而,当我更新“应用程序”状态时,“菜单”上的道具应该更新,但这不会发生。我做错什么了吗? 这是我的密码: 一个pp.js 菜单js

  • 我使用的是dev-express中的react-grid库,库中有一个表组件,我们可以向它传递单元格组件,在CustomCell中,我使用的是Material UI中的菜单 在上述情况下,菜单工作良好, 但是我想要传递道具到这个组件,我尝试了以下操作 在这种情况下菜单不工作,我想知道是否有一个替代的方法来实现第二种情况。

  • 示例代码:https://github.com/d6u/example-redux-update-nested-props/blob/master/one-connect/index.js 查看现场演示:http://d6u.github.io/example-redux-update-nested-props/one-connect.html 我有上面的组件,回购和重新整理。我想更新第一个rep