soa*_*gem 1 javascript reactjs jest react-dom
我正在使用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');
});
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,改变状态变量似乎无济于事。我不能打电话,component.componentWillReceiveProps()因为这似乎没有定义。
请注意,我确实希望同一个组件调用其渲染函数,而不是用一个全新的组件有效地替换它。原因是因为我发现了一个错误,该错误导致组件基于this.props而不是进行渲染this.state,并且我希望进行测试以表明它始终使用状态中的数据,而不是初始值。
AirBnb的酶对此具有一些强大的实用程序。您需要安装依赖项,但是它很简单,可以对其进行配置。然后,您可以简单地在组件实例上调用Enzyme的setState方法。重要说明–在这种情况下,您的“组件实例”是浅浅呈现的组件。您的代码如下所示:
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');
});
});
Run Code Online (Sandbox Code Playgroud)
所有这些都假定您state在组件中使用正确。就您而言,items似乎是以形式传入的prop。如果仅state通过复制进行设置props,则可能需要重新考虑您的策略。无论如何,这种方法应该与stateReact中更新的工作方式相同–您在同一组件实例上进行操作而无需卸载和重新安装组件。希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
2281 次 |
| 最近记录: |