打字稿/反应:打字稿无法识别通过React.cloneElement()

时间:2019-04-18 08:27:48

标签: javascript reactjs typescript jestjs enzyme

我目前正在使用Typescript / React项目中的Jest / Enzyme编写一系列单元测试。为了提供翻译,我正在使用react-intl库。该库提供有关如何编写辅助函数的文档,这些辅助函数包装了Enzyme的浅层/装入方法并注入了适当的道具:https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#enzyme

这一切都按预期工作,并且我的测试通过了,但是Typescript抛出类型检查错误,因为它没有意识到包装方法正在注入道具。

以下示例:

组件:

interface IWrapperProps {
    intl: InjectedIntl;
}

interface IWrapperQuery {
    data?: ISearchTerm;
    loading: boolean;
    error?: Error;
}

const SearchWrapper: SFC<IWrapperProps> = props => {
    return (
        ...
    );
};

测试:

it('renders correctly', async () => {
    const wrapper = mountWithHelpers(<SearchWrapper />, { mocks });
    await wait(50);
    expect(wrapper).toMatchSnapshot();
});

帮助方法:

// Int Provider
const intlProvider = new IntlProvider({ locale: 'en-gb', messages });
const { intl } = intlProvider.getChildContext();

function nodeWithIntlProp(node: any) {
    return React.cloneElement(node, { intl });
}

// Mount render
export function mountWithHelpers(node: any, { context = {}, childContextTypes = {}, mocks = [], store = null, ...additionalOptions } = {}) {
    const reduxStore = store || createStore(() => {});
    return mount(
        <Provider store={reduxStore}>
            <ThemeProvider theme={theme}>
                <MockedProvider mocks={mocks} addTypename>
                    {nodeWithIntlProp(node)}
                </MockedProvider>
            </ThemeProvider>
        </Provider>,
        {
            context: Object.assign({}, context, { intl }),
            childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes),
            ...additionalOptions
        }
    );
}

抛出的错误打字稿是:Property 'intl' is missing in type '{}' but required in type 'IWrapperProps'.我确信该道具正在注入,因为您可以在Jest快照文件中看到相应的道具。这只是Typescript的问题,没有意识到intl道具是由包装器提供的。

任何建议将不胜感激。

0 个答案:

没有答案