如何使用React DOM在单元测试中触发状态更改?

问题描述 投票:0回答:1

我正在使用React Test Utilities对我的一些代码进行单元测试。我调用renderIntoDocument来渲染自定义组件,然后使用findDOMNode来测试渲染的内容。我遇到的麻烦是我不确定如何更新状态并在单元测试的上下文中有效地触发重新渲染。

这是一些示例代码 - 注意代码注释:

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';
import MyCustomComponent from '../../app/components/MyCustomComponent';

describe('My Test Suite', () => {
    let component, node;
    test('verify state change', () => {
        const items = [{'value': '1'}];
        component = TestUtils.renderIntoDocument(
            <MyCustomComponent items={items} />
        );
        node = ReactDOM.findDOMNode(component);
        expect(node.querySelector('input[type=text]').value).toEqual('1');
        component.state.items = [{'value': '2'}];
        // do something here to trigger a re-render?
        expect(node.querySelector('input[type=text]').value).toEqual('2');
    });
});

不幸的是,似乎只是改变状态变量没有做任何事情。我不能打电话给component.componentWillReceiveProps(),因为这似乎没有定义。

请注意,我确实希望使用相同的组件来调用其渲染功能,而不是将其替换为有效的全新组件。原因是因为我发现了一个组件基于this.props而不是this.state渲染事物的错误,我想要一个测试来表明它总是使用来自状态的数据,而不是来自初始值。

javascript reactjs jest react-dom
1个回答
3
投票

来自AirBnb的Enzyme有一些很好的实用工具。你需要安装the dependencies,但它足够简单,可以配置它。然后,您只需在组件实例上调用Enzyme's setState method即可。一个重要的注意事项 - 在这种情况下你的“组件实例”是一个shallow rendered component。您的代码看起来像这样:

import React from 'react';
import MyCustomComponent from '../../app/components/MyCustomComponent';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

// configure your adapter
configure({ adapter: new Adapter() });

describe('My Test Suite', () => {

    test('verify state change', () => {
        const items = [{'value': '1'}];
        const wrapper = shallow(<MyCustomComponent items={items} />);

        // find your shallow rendered component and check its value
        expect(wrapper.find('input[type="text"]').value).toEqual('1');

        // set the state of the component
        wrapper.setState({ items: [{'value': '2'}] });

        // state should be updated, make sure its value was properly set
        expect(wrapper.find('input[type="text"]').value).toEqual('2');
    });
});

所有这些假设您正确地在组件中使用state。在你的情况下,items似乎作为prop传入。如果您只是通过复制state来设置props,您可能需要重新考虑您的策略。在任何情况下,这种方法应该与qactxswpoi在React工作中的更新方式相同 - 您在相同的组件实例上运行而无需卸载和重新安装组件。希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.