如何在测试时获取I18N组件的包装实例



我有一个简单的表单组件,看起来有点像:

'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);

我想使用这样的玩笑测试"状态"的更改:

'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'});
});

我想访问包装实例以更改某些状态。我的问题是以某种方式I18N没有加载参考,我总是会出现错误:

TypeError: item.getWrappedInstance is not a function

我在包装的组件中找到了使用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);
});

相关内容

最新更新