skip to Main Content

I have a system providing a members only section. I’d like to test if, when an unauthorized user opens a URL from the member section, they get forwarded to the login page.

In my test I render the whole application. From there I’d like to trigger a location change. How would I do that?

test('Unauthorized, open member page', () = {

   // run
   render(<App />);

   // TODO: change location to "/members/profile"

   // check
   expect(window.location.href).toBe('http://localhost/login');
});

2

Answers


  1. A protected route would solve the problem in these cases, if user is not Authorized it will redirect it to login page.

    import { render } from '@testing-library/react';
    import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
    import { isAuthenticated } from './auth'; // Your authorization function or authentication mechanism
    import App from './App';
    
    jest.mock('./auth', () => ({
      isAuthenticated: jest.fn(),
    }));
    
    test('Unauthorized user gets redirected to login page', () => {
      // Mock the authorization function
      isAuthenticated.mockReturnValue(false);
    
      // Render the application with protected routes
      const { container } = render(
        <Router>
          <Route
            path="/protected"
            render={() => (isAuthenticated() ? <div>Protected Content</div> : <Redirect to="/login" />)}
          />
          <Route path="/login" render={() => <div>Login Page</div>} />
          <App />
        </Router>
      );
    
      // Check if the user is redirected to the login page
      expect(container.innerHTML).toContain('Login Page');
    });
    
    Login or Signup to reply.
  2. you can nevigate to another page by import useHistory from react-router-dom

    import { useHistory } from "react-router-dom";
    
    function Page() {
    let history = useHistory();
    return (
    <button type="button" onClick={()=> history.push("/login")}>
      Go to Login page
    </button>
     );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search