我需要对一个有状态的组件进行单元测试,该组件也连接到redux存储,以调度事件。我正在使用Jest和酶。
我尝试了文档中提供的各种示例: https://react.i18next.com/misc/testing
这些示例都没有涉及使用redux-connect的用例。
考虑以下伪代码中的react组件:
// ../MyComponent.js
import React, { Component } from 'react';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import { withNamespaces } from 'react-i18next';
class MyComponent extends Component {
constructor(props) {
super(props);
// init state…
}
// Code body…
}
// Using compose from Redux lib
export default compose(
connect(null, mapDispatchToProps),
withNamespaces('myNamespace'),
)(MyComponent);
单元测试:
// ../__tests__/MyComponent.test.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { I18nextProvider } from 'react-i18next';
import i18n from '../../i18nForTests';
import reducers from '../../reducers';
import MyComponent from '../MyComponent';
const createStoreWithMiddleware = applyMiddleware()(createStore);
let MyComponentForTest = (
<Provider store={createStoreWithMiddleware(reducers)}>
<I18nextProvider i18n={i18n}>
<MyComponent />
</I18nextProvider>
</Provider>
);
describe('MyComponent state', () => {
let myPage;
test('init', () => {
myPage = shallow(MyComponentForTest); <-- Not getting the actual component.
});
});
使用以下依赖项
"react": "^16.6.1",
"react-app-polyfill": "^0.1.3",
"react-dev-utils": "^6.0.5",
"react-dom": "^16.6.1",
"react-i18next": "^8.3.8",
"react-inlinesvg": "^0.8.2",
"react-redux": "^5.1.1",
"redux": "^4.0.1",
"i18next": "^12.1.0",
"identity-obj-proxy": "3.0.0",
"jest": "23.6.0",
"jest-pnp-resolver": "1.0.1",
"jest-resolve": "23.6.0",
"webpack": "4.19.1",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.7.0",
在使用 shallow 或 mount 函数时,我无法从Enzyme检索实际组件。取而代之的是,我得到了包装的上下文,无论是提供者,上下文对象还是其他东西-这意味着我无法测试该组件。
为了澄清-这是我的单元测试在添加react-i18nextlib之前的样子……
在MyComponent.js中导出
export default connect(null, mapDispatchToProps)(MyComponent); <-- Note, not using compose as it is not needed.
单元测试MyComponent.test.js
let MyComponentForTest = <MyComponent store={createStoreWithMiddleware(reducers)} />;
describe(’MyComponent', () => {
describe('initially', () => {
let myPage;
test('init', () => {
myPage = shallow(MyComponentForTest).dive(); <-- Note, using dive(), to get the component.
console.log('*** myPage: ', myPage.debug());
});
});
在终端机中:
<MyComponent store={{...}} redirectPage={[Function]} />
因此,当不使用 react-i18next 时,我显然可以获取组件。
我认为问题的至少一部分是 withNamespaces()不返回组件,而是将其包装在某种上下文对象中...
答案 0 :(得分:0)
好吧,我的建议是导出MyComponent
并将其模拟状态作为道具传递。像这样:
const mockedState = {
...state data you want to pass
}
const MyComponentForTest = <MyComponent state={mockedState} />
describe('MyComponent state', () => {
let myPage;
test('init', () => {
myPage = shallow(MyComponentForTest);
});
});
这里的全部要点是,您的组件在传递的某种状态下的行为,您要在此处进行测试。这应该达到目的。