我有一个像这样连接的容器:
import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { autobind } from 'core-decorators';
const propTypes = {
data: PropTypes.object,
userData: PropTypes.object,
};
class ConnectedContainer extends React.Component {
@autobind
doSomethingImportant() {
...
}
render() {
....
}
}
ConnectedContainer.propTypes = propTypes;
const mapStateToProps = state => ({ data, userData });
const mapDispatchToProps = (dispatch) => {
return { actions: bindActionCreators(actions, dispatch) };
};
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedContainer);
我想测试doSomethingImportant
,所以我有这样的测试:
import React from 'react';
import { shallow } from 'enzyme';
import ConnectedContainer from '.....'';
import configureStore from 'redux-mock-store';
const mockStore = configureStore();
const store = mockStore({ getState: () => null, dispatch: () => null, data: { data from fixture }, userData: { data from fixture } });
const container = (
<ConnectedContainer
store={store}
actions={{}}
/>
);
describe('ConnectedContainer', () => {
describe('doSomethingImportant', () => {
it('returns something important', () => {
const wrapper = shallow(container);
expect(wrapper.instance().doSomethingImportant()).to.equal( ... some output here );
});
});
});
无论我做什么,我都会收到此错误:
TypeError: wrapper.instance(...). doSomethingImportant is not a function
我的容器发生了什么事,导致我无法访问其实例方法?
最佳答案
测试展开的组件
导出 ConnectedContainer 类本身,而不是包装版本。您想要测试您的代码,而不是 connect() 函数。
您可以保留默认导出作为包装组件,然后在类定义前面添加单词 export
:
export class ConnectedContainer extends React.Component { // Named export, for testing purposes only
...
}
然后在您的测试中,从 '....' 导入 { ConnectedContainer }
使用 shallow
渲染它,而不是默认导出。
命名约定
此外,将组件命名为 ConnectedContainer
非常令人困惑!它只有在用 connect 函数包装后才会连接。因此,当您导出ConnectedContainer
(正如我所建议的)时,您实际上是在导出一个非连接组件类。 (它实际上是一个容器吗?这也很模糊。)
人们使用的一种命名约定是定义一个常量来保存 connect() 的返回值,并将其命名为 xxxContainer,如下所示:
export class IconView extends React.Component { // Exported for testing
// ... class implementation
}
function mapStateToProps(){...}
function mapDispatchToProps(){...}
const IconViewContainer = connect(mapStateToProps, mapDispatchToProps)(IconView);
export default IconViewContainer; // Exported for use as a component in other views
关于reactjs - 在 Jest + Enzyme 中测试连接容器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48352193/