redux 的巨大好处之一是它允许您使用纯函数和纯组件来实现几乎所有的应用程序。Redux 和 react-redux 抽象了订阅 UI 到状态更改的实现细节,这允许您单独测试所有应用程序的代码。这样一来,您就不需要在每次想要测试代码时都使用商店渲染提供程序,这大大降低了复杂性。
假设key
您的状态中有一个属性和一个KeyDisplay
组件。您可以使用以下减速器文件实现状态:
减速器.js
import { combineReducers } from 'redux';
export function key(state, { type, value }) {
switch(type) {
case 'SET_VAL': return value;
default: return state;
}
}
export default combineReducers({ key });
您可以为我们的组件设置一个文件:
KeyDisplay.js
import React from 'react';
import { connect } from 'react-redux';
export function KeyDisplay({ keyProp }) {
return (
<div>The key is {keyProp}</div>
);
}
export default connect((state) => { keyProp: state.key })(KeyDisplay);
然后在 reduce 的单元测试中,您可以只导入 reducerkey
并完全独立于用户界面进行测试:
keyReducer.test.js
import test from 'tape';
import { key } from './reducers.js';
test('key reducer', (t) => {
t.plan(1);
const output = key('old', { type: 'SET_VAL', value: 'new' });
t.equal(output, 'new', 'SET_VAL should override old value');
});
此外,由于connect
将 state 作为 props 传递给组件,因此您可以connect
使用一些表示您感兴趣的状态的测试 props 来渲染 uned 组件,而无需设置 store 和 provider:
KeyDisplay.test.js
import test from 'tape';
import { renderIntoDocument } from 'react-addons-test-utils';
import { KeyDisplay } from './KeyDisplay.js';
test('KeyDisplay', (t) => {
const component = renderIntoDocument(<KeyDisplay keyProp="test" />);
// test component
});