【问题标题】:how to test Routes in react using jest and react testing library如何使用 jest 和 react 测试库在 react 中测试路由
【发布时间】:2021-06-14 17:55:01
【问题描述】:

所以我正在尝试测试每个 Route 组件和 url 是否匹配

函数

const App = () => (
    <Provider store={store}>
        <Router>
            <Layout>
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/login' component={LoginPage} />
                    <Route exact path='/signup' component={SignupPage} />
                    <Route exact path='/recipes' component={RecipesPage} />
                    <Route exact path='/recipes/:id' component={RecipeDetailPage} />
                    <Route exact path='/reset_password' component={ResetPasswordPage} />
                    <Route exact path='/password/reset/confirm/:uid/:token' component={ResetPasswordConfirmPage} />
                    <Route component={NotFound} />
                </Switch>
            </Layout>
        </Router>
    </Provider>
);

有人知道我该如何测试吗?

【问题讨论】:

    标签: reactjs unit-testing jestjs react-testing-library


    【解决方案1】:

    所以经过一些试验和错误后,我设法得到了答案,这是对我有用的测试:

    (我在主页添加了一个 test-id,这样我就可以知道这是被渲染的组件)

    describe('App', () => {
        beforeEach(() => {
            const renderWithRouter = (ui, { route = '/' } = {}) => {
                window.history.pushState({}, 'Test page', route);
    
                return render(ui, { wrapper: BrowserRouter });
            };
            renderWithRouter(<App />);
        });
        afterEach(() => {
            cleanup();
        });
        test('should render without crashing', () => {});
        test('should render home page', () => {
            const homePage = screen.getByText('homePage');
            expect(homePage).toBeInTheDocument();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2019-04-22
      • 2021-06-04
      • 1970-01-01
      • 2020-06-14
      • 2020-06-01
      • 2021-09-20
      • 2021-11-30
      • 2021-04-01
      相关资源
      最近更新 更多