我有一个简单的表单组件,看起来有点像:
'use strict';
import React from 'react';
import { translate } from 'react-i18next';
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {testString: this.props.testString};
}
render() {
const { t } = this.props;
return (<p>
<span>{t('test')}</span>
<em>{this.state.testString}</em>
</p>);
}
}
export default translate()(MyForm);
&#13;
我想测试&#34;州&#34;的变化。使用这样的笑话:
'use strict';
import React from 'react';
import { I18nextProvider, translate } from 'react-i18next';
import { shallow, mount, render } from 'enzyme';
import MyForm from './MyForm';
import renderer from 'react-test-renderer';
import i18n from 'i18next';
i18n.init({react: {withRef: true}});
it('Test my form', async () => {
const item = await mount(<I18nextProvider i18n={i18n}><MyForm/></I18nextProvider>);
item.getWrappedInstance().setState({testString: 'test'});
});
&#13;
我想访问包装的实例来更改某些状态。我的问题是不知何故i18n没有加载ref,我总是得到错误:
TypeError: item.getWrappedInstance is not a function
答案 0 :(得分:0)
我在包装组件中找到了一个使用refs的解决方案,如下所示:
'use strict';
import React from 'react';
import { I18nextProvider, translate } from 'react-i18next';
import { shallow, mount, render } from 'enzyme';
import MyForm from './MyForm';
import renderer from 'react-test-renderer';
import i18n from 'i18next';
i18n.init({react: {withRef: true}});
it('Test my form', async () => {
let instance;
const item = await mount(<I18nextProvider i18n={i18n}><MyForm ref={(element) => { instance = element; }}/></I18nextProvider>);
instance.getWrappedInstance().setState({testString: 'test'});
console.log(item.find('em').node.outerHTML);
});
&#13;