react-router-dom#BrowserHistory JavaScript Examples

The following examples show how to use react-router-dom#BrowserHistory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.test.js    From QiskitFlow with Apache License 2.0 6 votes vote down vote up
describe('<ConnectedLanguageProvider />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render the default language messages', () => {
    const { queryByText } = render(
      <Provider store={store}>
        <ConnectedLanguageProvider messages={translationMessages}>
          <FormattedMessage {...messages.someMessage} />
        </ConnectedLanguageProvider>
      </Provider>,
    );
    expect(queryByText(messages.someMessage.defaultMessage)).not.toBeNull();
  });
});
Example #2
Source File: store.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('configureStore params', () => {
  it('should call window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__', () => {
    /* eslint-disable no-underscore-dangle */
    const compose = jest.fn();
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ = () => compose;
    configureStore(undefined, browserHistory);
    expect(compose).toHaveBeenCalled();
    /* eslint-enable */
  });
});
Example #3
Source File: store.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('configureStore', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  describe('injectedReducers', () => {
    it('should contain an object for reducers', () => {
      expect(typeof store.injectedReducers).toBe('object');
    });
  });

  describe('injectedSagas', () => {
    it('should contain an object for sagas', () => {
      expect(typeof store.injectedSagas).toBe('object');
    });
  });

  describe('runSaga', () => {
    it('should contain a hook for `sagaMiddleware.run`', () => {
      expect(typeof store.runSaga).toBe('function');
    });
  });
});
Example #4
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<SettingsPage />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <SettingsPage dispatch={dispatch} intl={intl} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #5
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<ConnectedLanguageProvider />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render the default language messages', () => {
    const { queryByText } = render(
      <Provider store={store}>
        <ConnectedLanguageProvider messages={translationMessages}>
          <FormattedMessage
            id={messages.someMessage.id}
            defaultMessage={messages.someMessage.defaultMessage}
          />
        </ConnectedLanguageProvider>
      </Provider>,
    );
    expect(queryByText(messages.someMessage.defaultMessage)).not.toBeNull();
  });
});
Example #6
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<CommunicationProvider />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <CommunicationProvider dispatch={dispatch}>
          <br />
        </CommunicationProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #7
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<ChatManager />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <ChatManager channel="test" channelData={{}} dispatch={dispatch} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #8
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<UsersModal />', () => {
  let store;
  const user = {
    name: 'test',
    isBlocked: false,
  };
  const myLevel = 'user';

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <UsersModal user={user} myLevel={myLevel} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #9
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<UserItem />', () => {
  let store;
  const user = {
    name: 'test',
    isBlocked: false,
  };
  const myLevel = 'user';

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <UserItem user={user} myLevel={myLevel} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #10
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<StartScreen />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <StartScreen dispatch={dispatch} intl={intl} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #11
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<Notifier />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <Notifier dispatch={dispatch} intl={intl} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #12
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<MainMenu />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <MainMenu dispatch={dispatch} intl={intl} />
        </IntlProvider>
      </Provider>,
    );
    expect(spy).not.toHaveBeenCalled();
  });
});
Example #13
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
describe('<ChannelItem />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render a <button> tag', () => {
    const { container } = render(
      <Router>
        <Provider store={store}>
          <IntlProvider locale={DEFAULT_LOCALE}>
            <ChannelItem />
          </IntlProvider>
        </Provider>
      </Router>,
    );
    expect(container.querySelector('button')).not.toBeNull();
  });

  it('should have a class attribute', () => {
    const { container } = render(
      <Router>
        <Provider store={store}>
          <IntlProvider locale={DEFAULT_LOCALE}>
            <ChannelItem />
          </IntlProvider>
        </Provider>
      </Router>,
    );
    expect(container.querySelector('button').hasAttribute('class')).toBe(true);
  });
});
Example #14
Source File: index.test.js    From awsboilerplate with MIT License 6 votes vote down vote up
describe('<Footer />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render and match the snapshot', () => {
    const renderedComponent = renderer
      .create(
        <Provider store={store}>
          <IntlProvider locale="en">
            <Footer />
          </IntlProvider>
        </Provider>,
      )
      .toJSON();

    expect(renderedComponent).toMatchSnapshot();
  });
});
Example #15
Source File: store.test.js    From QiskitFlow with Apache License 2.0 6 votes vote down vote up
describe('configureStore params', () => {
  it('should call window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__', () => {
    /* eslint-disable no-underscore-dangle */
    const compose = jest.fn();
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ = () => compose;
    configureStore(undefined, browserHistory);
    expect(compose).toHaveBeenCalled();
    /* eslint-enable */
  });
});
Example #16
Source File: store.test.js    From QiskitFlow with Apache License 2.0 6 votes vote down vote up
describe('configureStore', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  describe('injectedReducers', () => {
    it('should contain an object for reducers', () => {
      expect(typeof store.injectedReducers).toBe('object');
    });
  });

  describe('injectedSagas', () => {
    it('should contain an object for sagas', () => {
      expect(typeof store.injectedSagas).toBe('object');
    });
  });

  describe('runSaga', () => {
    it('should contain a hook for `sagaMiddleware.run`', () => {
      expect(typeof store.runSaga).toBe('function');
    });
  });
});
Example #17
Source File: index.test.js    From hackchat-client with Do What The F*ck You Want To Public License 5 votes vote down vote up
describe('<HomePage />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  const location = {
    search: '',
  };

  const meta = {
    channels: {},
  };

  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    const dispatch = jest.fn();
    const onOpenJoinModal = jest.fn();
    render(
      <Router>
        <Provider store={store}>
          <IntlProvider locale={DEFAULT_LOCALE}>
            <HomePage
              dispatch={dispatch}
              location={location}
              channel={false}
              meta={meta}
              onOpenJoinModal={onOpenJoinModal}
            />
          </IntlProvider>
        </Provider>
      </Router>,
    );
    expect(spy).not.toHaveBeenCalled();
  });

  describe('mapDispatchToProps', () => {
    describe('onChannelChange', () => {
      it('should be injected', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        expect(result.onChannelChange).toBeDefined();
      });
    });

    describe('onOpenJoinModal', () => {
      it('should be injected', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        expect(result.onOpenJoinModal).toBeDefined();
      });
    });
  });
});
Example #18
Source File: index.test.js    From QiskitFlow with Apache License 2.0 5 votes vote down vote up
describe('<LocaleToggle />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should match the snapshot', () => {
    const { container } = render(
      <Provider store={store}>
        <LanguageProvider messages={translationMessages}>
          <LocaleToggle />
        </LanguageProvider>
      </Provider>,
    );
    expect(container.firstChild).toMatchSnapshot();
  });

  it('should present the default `en` english language option', () => {
    const { container } = render(
      <Provider store={store}>
        <LanguageProvider messages={translationMessages}>
          <LocaleToggle />
        </LanguageProvider>
      </Provider>,
    );
    expect(container.querySelector('option[value="en"]')).not.toBeNull();
  });

  describe('mapDispatchToProps', () => {
    describe('onLocaleToggle', () => {
      it('should be injected', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        expect(result.onLocaleToggle).toBeDefined();
      });

      it('should dispatch changeLocale when called', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        const locale = 'de';
        const evt = { target: { value: locale } };
        result.onLocaleToggle(evt);
        expect(dispatch).toHaveBeenCalledWith(changeLocale(locale));
      });
    });
  });
});
Example #19
Source File: index.test.js    From QiskitFlow with Apache License 2.0 4 votes vote down vote up
describe('<HomePage />', () => {
  let store;

  beforeAll(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render and match the snapshot', () => {
    const {
      container: { firstChild },
    } = render(
      <Provider store={store}>
        <IntlProvider locale="en">
          <HomePage loading={false} error={false} repos={[]} />
        </IntlProvider>
      </Provider>,
    );
    expect(firstChild).toMatchSnapshot();
  });

  it('should fetch the repos on mount if a username exists', () => {
    const submitSpy = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale="en">
          <HomePage
            username="Not Empty"
            onChangeUsername={() => {}}
            onSubmitForm={submitSpy}
          />
        </IntlProvider>
      </Provider>,
    );
    expect(submitSpy).toHaveBeenCalled();
  });

  it('should not call onSubmitForm if username is an empty string', () => {
    const submitSpy = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale="en">
          <HomePage onChangeUsername={() => {}} onSubmitForm={submitSpy} />
        </IntlProvider>
      </Provider>,
    );
    expect(submitSpy).not.toHaveBeenCalled();
  });

  it('should not call onSubmitForm if username is null', () => {
    const submitSpy = jest.fn();
    render(
      <Provider store={store}>
        <IntlProvider locale="en">
          <HomePage
            username=""
            onChangeUsername={() => {}}
            onSubmitForm={submitSpy}
          />
        </IntlProvider>
      </Provider>,
    );
    expect(submitSpy).not.toHaveBeenCalled();
  });

  describe('mapDispatchToProps', () => {
    describe('onChangeUsername', () => {
      it('should be injected', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        expect(result.onChangeUsername).toBeDefined();
      });

      it('should dispatch changeUsername when called', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        const username = 'mxstbr';
        result.onChangeUsername({ target: { value: username } });
        expect(dispatch).toHaveBeenCalledWith(changeUsername(username));
      });
    });

    describe('onSubmitForm', () => {
      it('should be injected', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        expect(result.onSubmitForm).toBeDefined();
      });

      it('should dispatch loadRepos when called', () => {
        const dispatch = jest.fn();
        const result = mapDispatchToProps(dispatch);
        result.onSubmitForm();
        expect(dispatch).toHaveBeenCalledWith(loadRepos());
      });

      it('should preventDefault if called with event', () => {
        const preventDefault = jest.fn();
        const result = mapDispatchToProps(() => {});
        const evt = { preventDefault };
        result.onSubmitForm(evt);
        expect(preventDefault).toHaveBeenCalledWith();
      });
    });
  });
});
Example #20
Source File: login.js    From Docketeer with MIT License 4 votes vote down vote up
Login = () => {
  const dispatch = useDispatch();
  const updateSession = () => dispatch(actions.updateSession());
  const updateUser = (userInfo) => dispatch(actions.updateUser(userInfo));

  const session = useSelector((state) => state.session.isLoggedIn);

  const [modalIsOpen, setIsOpen] = useState(false);

  // Material UI
  const classes = useStyles();

  // Need to set the app element to body for screen-readers (disability), otherwise modal will throw an error
  useEffect(() => {
    fetch("http://localhost:3000/db")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        return console.log("Connected to DB successfully", data);
      })
      .catch((err) => {
        return console.log("Fetch request to /db failed:", err);
      });
  }, []);

  // callback function invoked when 'login' button is clicked
  const handleLogin = (e) => {
    e.preventDefault(); // prevents form submit from reloading page
    const usernameInput = document.getElementById("username");
    const passwordInput = document.getElementById("password");
    const username = usernameInput.value;
    const password = passwordInput.value;

    // clears input fields after login
    usernameInput.value = "";
    passwordInput.value = "";

    authenticateUser(username, password);
  };

  // callback function which will send request to endpoint http://localhost:3000/login and expect either SSID in cookie.
  const authenticateUser = (username, password) => {
    fetch("http://localhost:3000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username: username,
        password: password,
      }),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (Object.prototype.hasOwnProperty.call(data, "error")) {
          window.alert(data.error);
        } else {
          updateSession(); // loggedIn = true
          updateUser(data); // update user info in sessions reducer
        }
      })
      .catch((err) => {
        console.log("Fetch: POST error to /login", err);
        // created a pop window for wrong username/password
        window.alert("Wrong Password or Username! Please try Again!");
      });
  };

  // Upon successful login, redirect to /app location and render the App component

  // Note: this could be re-worked, just thinking about it this looks like poor security design since loggedIn is a local state variable on client end which can be hardcoded to true. Rather, the server should verify credentials and then send client either SSID to access next endpoint or another means.
  if (session) {
    return (
      <Router history={BrowserHistory}>
        <Redirect to="/app" />
        <Switch>
          {/* <Route component={App} exact path="/app" /> */}
          <Route path="/app">
            <App />
          </Route>
        </Switch>
      </Router>
    );
  }

  // Else render the login page
  return (
    <Router history={BrowserHistory}>
      <Route id="route" path="/">
        <header>
          <img src={Docketeer} width={160} />
        </header>
        <br />
        <br />
        <br />
        <div className="renderContainers">
          <div className="header">
            <h1 className="tabTitle">Login</h1>
          </div>
          <div className="settings-container">
            <form className={classes.root} onSubmit={handleLogin}>
              {/* <input id="username" type="text" placeholder="username"></input> */}
              <TextField id="username" label="Username" variant="outlined" />
              <br />
              <br />
              {/* <input id="password" type="password" placeholder="password"></input> */}
              <TextField
                id="password"
                label="Password"
                type="password"
                variant="outlined"
              />
              {/* <input type="submit"></input> */}
              <br />
              <Button
                variant="contained"
                color="primary"
                type="submit"
                size="medium"
                className={classes.button}
              >
                Login
              </Button>
              <hr />
              <div
                className="g-signin2"
                data-onsuccess="onSignIn"
                style={{ width: "200px", borderRadius: "4px" }}
              ></div>
            </form>
          </div>
        </div>
      </Route>
    </Router>
  );
}