reactjs - 如何使用 Jest 和 react 测试库在 react 中测试路线

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

所以我试图测试每个 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>
);
任何人都知道我如何测试这个?

最佳答案

所以经过一些试验和错误后,我设法得到了答案,这是对我有用的测试:
(我在 homePage 中添加了一个 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();
    });
});

关于reactjs - 如何使用 Jest 和 react 测试库在 react 中测试路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66672332/

相关文章:

unit-testing - 在测试中禁用 React 的 CSSTransitionGroup

javascript - ReactJS:本地镜像未加载(使用覆盖路径)

javascript - 我可以通过 props.children React JS 将 props 传递给 children 吗

c++ - 如何对嵌入式代码进行单元测试?

javascript - 如何确定 JEST 是否正在运行代码?

reactjs - Axios 发布请求在 React Native 中不起作用

c# - 如何在 Microsoft Moles 中提供不带参数的用户定义委托(delegate)

ruby-on-rails - 测试时我应该在 Factory girl 中 stub 模型还是在规范文件中 stub ?

jestjs - 如何在beforeAll()中调用数据库连接,并在afterAll()中关闭数据库连接

node.js - NodeJS axios 请求自签名在浏览器中有效,但在 Jest super 测试案例中无效