如何测试 React 组件的 prop 更新 [英] How to test a prop update on React component

查看:33
本文介绍了如何测试 React 组件的 prop 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单元测试 React 组件 prop 更新的正确方法是什么.

What is the correct way of unit testing a React component prop update.

这是我的测试夹具;

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

这工作正常并且测试通过,但是这会显示一个反应警告消息

This works fine and the test passes, however this displays a react warning message

'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.'

我只想测试属性的更新,而不是创建具有不同属性的元素的新实例.有没有更好的方法来进行此属性更新?

All i want to test is the update of a property, not to create a new instance of the element with a different property. Is there a better way to do this property update?

推荐答案

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

AirBnB's Enzyme library provides an elegant solution to this question.

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

it provides a setProps method, that can be called on either a shallow or jsdom wrapper.

    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 组件的 prop 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆