无法使MemoryRouter与@ testing-library / react一起使用

时间:2020-01-24 07:45:13

标签: reactjs react-router react-testing-library

我正在尝试测试路由器是否按预期工作。但是我无法让路由器指向除/

之外的其他位置

这是我的简化测试代码。

App.tsx

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

const App: React.FC = () => {
    return (
        <div>
            <BrowserRouter>
                <Switch>
                    <Route path={'/test'}>test</Route>
                    <Route path={'/'}>index</Route>
                </Switch>
            </BrowserRouter>
        </div>
    );
};

export default App;

App.test.tsx

import React from 'react';
import App from './App';
import {MemoryRouter} from 'react-router-dom';
import {render} from '@testing-library/react';


test('renders /test route', async () => {
    const app = render(
        <MemoryRouter initialEntries={['/test']} initialIndex={0}>
            <App/>
        </MemoryRouter>);
    expect(app.getByText(/test/i)).toBeInTheDocument();
});

我收到以下错误消息

Error: Unable to find an element with the text: /test/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

<body>
  <div>
    <div>
       index
    </div>
  </div>
</body>

我在做什么错了?

2 个答案:

答案 0 :(得分:7)

问题是,我要测试的组件已经声明了路由器。 为了解决此问题,我不得不将App组件分为AppRoutes

对于测试,我只需要渲染Routes组件,一切都会按预期进行。

App.tsx

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

export const Routes = () => {
    return (
        <>
            <Switch>
                <Route path={'/test'}> test</Route>
                <Route path={'/'}> index</Route>
            </Switch>
        </>
    )
};

const App: React.FC = () => {
    return (
        <div>
            <BrowserRouter>
                <Routes/>
            </BrowserRouter>
        </div>
    );
};

export default App;

App.test.tsx

import React from 'react';
import {Routes} from './App';
import {MemoryRouter} from 'react-router-dom';
import {render} from '@testing-library/react';


test('renders routes correct', async () => {
    const app = render(
        <MemoryRouter initialEntries={['/test']} initialIndex={0}>
            <Routes/>
        </MemoryRouter>
    );
    expect(app.getByText(/test/i)).toBeInTheDocument();
});

答案 1 :(得分:0)

如果您要从App加载index.js(在我在Create React App应用程序中遇到此问题时就是这种情况),也可以将App包装在{ {1}},然后按照您的期望测试Router路由,而不必像完成那样导出App

例如(否则,股票CRA Routes):

index.js