如何使用react-i18next测试有状态、冗余连接的组件



我需要对一个也连接到redux存储的有状态组件进行单元测试,以调度事件。我用的是Jest和Enzyme。

我尝试了文档中提供的各种示例:https://react.i18next.com/misc/testing

没有一个示例涵盖使用redux连接的用例。

考虑伪代码中的以下反应组件:

// ../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",

使用Enzyme的装载功能时,我无法检索实际组件。相反,我得到的是包装好的上下文,要么是Provider,要么是Context对象,要么是其他什么——这意味着我不能测试组件。

为了澄清——这就是在添加react-i18next-lib之前我的单元测试的样子…

在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((不返回组件,而是将其封装在某种Context对象中。。。

好吧,我在这里的建议是导出MyComponent,并将其模拟状态作为道具传递。类似这样的东西:

const mockedState = {
...state data you want to pass
}
const MyComponentForTest = <MyComponent state={mockedState} />

describe('MyComponent state', () => {
let myPage;
test('init', () => {
myPage = shallow(MyComponentForTest);
});
});

这里的重点是您的组件在某个状态下的行为,该状态是您想要在这里测试的。这应该达到目的。

最新更新