【问题标题】:Whats the best way to write test for testing Routes?为测试路由编写测试的最佳方法是什么?
【发布时间】: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


【解决方案1】:

我做了下面的方法,我能够成功运行测试

it("check routes for support create page", () => {
    const history = createBrowserHistory();
    const pluginListener = new SupportPluginListener();
    history.push("/support/home");
    const { getByText, debug } = render(
      <Provider store={mockConnectorStore}>
        <Router history={history}>
          <Home/>
        </Router>
      </Provider>,
    );
    const titleText = getByText(/Open a Support Request/);
    expect(titleText).toBeDefined();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多