【发布时间】:2020-11-19 20:24:50
【问题描述】:
我想为 main.tsx 编写一个测试。下面是相同的代码。我以前没有为路线写过任何测试。如何为这些路由编写测试?
const init = async () => {
const history = createBrowserHistory({ basename: `${HISTORY_BASENAME}` });
// Catch link clicks and push them to the history object.
handleNavigation(history);
const renderCreateOldSliModal = () => <OldSliCreateModal />;
const renderCreateSRModal = (forceProblemType?: SupportType) => (
<CreateSRModal forceProblemType={forceProblemType} interPluginContext=
{pluginListener.getContext()} />
);
ReactDOM.render(
<Configuration value={{ language: startData.initialContext.locale }}>
<Provider store={store}>
<ConnectedRouter history={history}>
<NavMenuContextProvider navigation={navTree}>
<Switch>
<Route
path={`/${ResourceNames.serviceRequest}/${ResourceNames.create}`}
render={renderCreateOldSliModal}
/>
<Route
path={`/${ResourceNames.create}`}
render={() => renderCreateSRModal()}
exact={true}
/>
</Switch>
</NavMenuContextProvider>
</ConnectedRouter>
</Provider>
</Configuration>,
document.getElementById(CONTAINER_ID)
};
init();
我写了一个类似下面的测试,但是我得到一个错误
TypeError: Cannot read property 'createElement' of undefined
下面是我的测试
it("check routes", () => {
const history = createBrowserHistory();
const { container } = render(
<ConnectedRouter history={history}>
<NavMenuContextProvider navigation={undefined}>
<Switch>
<Route history={history}>
path="/support/create"
</Route>
</Switch>
</NavMenuContextProvider>
</ConnectedRouter>,
);
expect(container.innerHTML).toMatch("Open a Support Request");
});
【问题讨论】:
-
TypeError: Cannot read property 'createElement' of undefined,发生此错误是因为我没有正确导入反应。我修好了。现在我得到一个不同的错误。React.Children.only expected to receive a single React element child.
标签: reactjs unit-testing testing routes