用开玩笑 / RTL进行React路由器的测试路线

发布于 2025-02-13 21:46:51 字数 1696 浏览 0 评论 0原文

我正在尝试使用RTL和JEST进行React测试一些路线,但是由于测试不知道路线,测试似乎失败了吗?我试图遵循 rtl docs 我正在使用> rtl docs React-Router-dom”:“^5.2.0”

我的路线:

const Routing: React.FunctionComponent = () => {

  return (
    <>
        <BrowserRouter>
          <Header/>
          <div className="App">
            <Switch>
              <Route exact path="/">
                <Redirect to="/home" />
              </Route>
              <Route exact path={["/home", "/"]} component={Home} />
              <Route path="/account-details/:account?/:id" render={(props: RouteComponentProps<any>) => <AccountDetail {...props} />} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </BrowserRouter>
    </>
  )
}

export default Routing;

我的测试:

const accountQuery = new QueryClient()
    it('Should test 404 route', async () => {
      const history = createMemoryHistory();
      history.push('/bad/route')
        await render(
            <QueryClientProvider client={accountQuery}>
            <Router history={history}>
                <App />
            </Router>,
        </QueryClientProvider>
        )
        expect(await screen.findByText(/404 error/i)).toBeInTheDocument();
    });

如果我断言以下:

expect(history.location.pathname).toBe('/bad/route');

它通过即使我已经渲染了该应用程序的路线?

有什么想法吗?我希望它实际上从应用程序中获取路线?

I am trying to test some routes using RTL and Jest for React, But the test seem to be failing as I don't think the test knows the routes? I have tried to follow the RTL docs I am using "react-router-dom": "^5.2.0"

My routes:

const Routing: React.FunctionComponent = () => {

  return (
    <>
        <BrowserRouter>
          <Header/>
          <div className="App">
            <Switch>
              <Route exact path="/">
                <Redirect to="/home" />
              </Route>
              <Route exact path={["/home", "/"]} component={Home} />
              <Route path="/account-details/:account?/:id" render={(props: RouteComponentProps<any>) => <AccountDetail {...props} />} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </BrowserRouter>
    </>
  )
}

export default Routing;

My test:

const accountQuery = new QueryClient()
    it('Should test 404 route', async () => {
      const history = createMemoryHistory();
      history.push('/bad/route')
        await render(
            <QueryClientProvider client={accountQuery}>
            <Router history={history}>
                <App />
            </Router>,
        </QueryClientProvider>
        )
        expect(await screen.findByText(/404 error/i)).toBeInTheDocument();
    });

If I assert the following:

expect(history.location.pathname).toBe('/bad/route');

It passes, but it does not seem to be actually taking the routes from the App even though I have rendered it?

Any Idea's? I want it to actually get the routes from the App?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2025-02-20 21:46:52

您需要进行一些重构,分为两个部分:路由app组件。 browserrouter将创建浏览器历史 ,然后将其传递给&lt; router/&gt;组件,您的自定义内存历史记录将不使用。参见 browserrouter.js#l14

browserrouter.js react-router-dom v5 ):

class BrowserRouter extends React.Component {
  history = createHistory(this.props);

  render() {
    return <Router history={this.history} children={this.props.children} />;
  }
}

doutes.tsx

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';

const Routing = () => {
  return (
    <Switch>
      <Route exact path="/">
        <Redirect to="/home" />
      </Route>
      <Route exact path={['/home', '/']} component={() => <div>home</div>} />
      <Route path="/account-details/:account?/:id" component={() => <div>account detail</div>} />
      <Route component={() => <div>404 error</div>} />
    </Switch>
  );
};

export default Routing;

doutes.test.tsx

import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { createMemoryHistory } from 'history';
import React from 'react';
import { Router } from 'react-router-dom';
import Routing from './routes';

describe('first', () => {
  it('Should test 404 route', async () => {
    const history = createMemoryHistory();
    history.push('/bad/route');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/404 error/i)).toBeInTheDocument();
  });

  it('should render home page', async () => {
    const history = createMemoryHistory();
    history.push('/home');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/home/i)).toBeInTheDocument();
  });
  it('should render account detail page', async () => {
    const history = createMemoryHistory();
    history.push('/account-details/admin/1');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/account detail/i)).toBeInTheDocument();
  });
});

app.tsxx

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routing from './routes';

const App = () => {
  return (
    <BrowserRouter>
      <header>app</header>
      <div className="App">
        <Routing />
      </div>
    </BrowserRouter>
  );
};
export default App;

通过这种方式,您可以使用自己的自定义内存历史记录测试路由组件。

测试结果:

 PASS  stackoverflow/72897761/routes.test.tsx (10.422 s)
  first
    ✓ Should test 404 route (30 ms)
    ✓ should render home page (7 ms)
    ✓ should render account detail page (4 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 routes.tsx |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        10.93 s, estimated 11 s

You need to do some refactoring, split into two parts: Routes and App components. The BrowserRouter will create browser history and pass it to the <Router/> component, your custom memory history will not be used. See BrowserRouter.js#L14

BrowserRouter.js (react-router-dom v5):

class BrowserRouter extends React.Component {
  history = createHistory(this.props);

  render() {
    return <Router history={this.history} children={this.props.children} />;
  }
}

routes.tsx:

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';

const Routing = () => {
  return (
    <Switch>
      <Route exact path="/">
        <Redirect to="/home" />
      </Route>
      <Route exact path={['/home', '/']} component={() => <div>home</div>} />
      <Route path="/account-details/:account?/:id" component={() => <div>account detail</div>} />
      <Route component={() => <div>404 error</div>} />
    </Switch>
  );
};

export default Routing;

routes.test.tsx:

import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { createMemoryHistory } from 'history';
import React from 'react';
import { Router } from 'react-router-dom';
import Routing from './routes';

describe('first', () => {
  it('Should test 404 route', async () => {
    const history = createMemoryHistory();
    history.push('/bad/route');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/404 error/i)).toBeInTheDocument();
  });

  it('should render home page', async () => {
    const history = createMemoryHistory();
    history.push('/home');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/home/i)).toBeInTheDocument();
  });
  it('should render account detail page', async () => {
    const history = createMemoryHistory();
    history.push('/account-details/admin/1');
    render(
      <Router history={history}>
        <Routing />
      </Router>
    );
    expect(await screen.findByText(/account detail/i)).toBeInTheDocument();
  });
});

app.tsx:

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routing from './routes';

const App = () => {
  return (
    <BrowserRouter>
      <header>app</header>
      <div className="App">
        <Routing />
      </div>
    </BrowserRouter>
  );
};
export default App;

In this way, you can test the Routing component with your own custom memory history.

Test result:

 PASS  stackoverflow/72897761/routes.test.tsx (10.422 s)
  first
    ✓ Should test 404 route (30 ms)
    ✓ should render home page (7 ms)
    ✓ should render account detail page (4 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 routes.tsx |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        10.93 s, estimated 11 s
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文