react-router#Router JavaScript Examples
The following examples show how to use
react-router#Router.
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: app-router.js From albedo with MIT License | 6 votes |
export default function AppRouter({history}) {
return <Layout>
<Router history={history}>
<CatcherView>
<Switch>
<Route path="/playground">
<DynamicModule load={() => import(/* webpackChunkName: "playground" */ './demo/demo-view')}
moduleKey="playground"/></Route>
<Route path="/wallet">
<DynamicModule load={() => import(/* webpackChunkName: "wallet" */ './wallet/wallet-router')}
moduleKey="wallet"/></Route>
<Route path="/login" component={Login}/>
<Route path="/import" component={ImportAccount}/>
<Route path="/signup" component={CreateAccount}/>
<Route path="/confirm" component={Intent}/>
<Route path="/result" component={TxResultView}/>
<Route path="/account" component={AccountDashboard}/>
<Route path="/extension" component={AccountDashboard}/>
<Route path="/account-settings" component={AccountSettings}/>
<Route path="/blocked" component={BlockedPageView}/>
<Route path="/install-extension" component={InstallExtensionView}/>
<Route path="/web-stellar-handler" component={WebStellarLinkHandler}/>
<Route path="/" exact component={IntroView}/>
<Route component={NotFound}/>
</Switch>
</CatcherView>
</Router>
</Layout>
}
Example #2
Source File: routes.jsx From howlongistheline.org with Mozilla Public License 2.0 | 6 votes |
renderRoutes = () => (
// <Provider store={store}>
<Router history={browserHistory}>
<MuiPickersUtilsProvider utils={MomentUtils}>
<CookiesProvider>
<ToastContainer />
<Switch>
<Route exact path="/" component={Nearme} />
<Route exact path="/addLine" component={AddLine} />
<Route exact path="/editLine" component={EditLine} />
<Route exact path="/shopDetails" component={ShopDetails} />
<Route exact path="/feedback" component={FeedBack} />
<Route exact path="/FAQ" component={faq} />
<Route exact path="/learntocode" component={learntocode} />
<Route exact path="/duplicated" component={duplicated} />
<Route exact path="/stocks" component={Stocks} />
<Route exact path="/editLocation" component={EditLocation} />
</Switch>
</CookiesProvider>
</MuiPickersUtilsProvider>
</Router>
// </Provider>
)
Example #3
Source File: react-router-dom.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
HashRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(HashRouter, _React$Component);
function HashRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.history = createHashHistory(_this.props);
return _this;
}
var _proto = HashRouter.prototype;
_proto.render = function render() {
return React.createElement(Router, {
history: this.history,
children: this.props.children
});
};
return HashRouter;
}(React.Component)
Example #4
Source File: react-router-dom.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
BrowserRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(BrowserRouter, _React$Component);
function BrowserRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.history = createBrowserHistory(_this.props);
return _this;
}
var _proto = BrowserRouter.prototype;
_proto.render = function render() {
return React.createElement(Router, {
history: this.history,
children: this.props.children
});
};
return BrowserRouter;
}(React.Component)
Example #5
Source File: product-list-page.spec.js From horondi_client_fe with MIT License | 6 votes |
describe('ProductListPage with correct values', () => {
beforeEach(() => {
render(
<MockedProvider mocks={mockAllFilteredProducts(isWrongNameFilter)} addTypename>
<ThemeProvider theme={themeValue}>
<Router history={history}>
<ProductListPage width='sm' />
</Router>
</ThemeProvider>
</MockedProvider>
);
});
it('should render loader', () => {
const loader = screen.findByTestId('loader');
expect(loader).toBeDefined();
});
it('should render products', async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
const products = await screen.getAllByTestId('product');
expect(products).toHaveLength(2);
});
});
Example #6
Source File: product-list-page.spec.js From horondi_client_fe with MIT License | 6 votes |
describe('ProductListPage with incorrect query', () => {
beforeAll(() => {
isWrongNameFilter = true;
render(
<MockedProvider mocks={mockAllFilteredProducts(isWrongNameFilter)} addTypename>
<ThemeProvider theme={themeValue}>
<Router history={history}>
<ProductListPage width='sm' />
</Router>
</ThemeProvider>
</MockedProvider>
);
});
it('should render not-found-product image', async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(screen.getByTestId('backpack-icon')).toBeDefined();
});
});
Example #7
Source File: react-router-dom.js From Learning-Redux with MIT License | 6 votes |
HashRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(HashRouter, _React$Component);
function HashRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.history = createHashHistory(_this.props);
return _this;
}
var _proto = HashRouter.prototype;
_proto.render = function render() {
return React.createElement(Router, {
history: this.history,
children: this.props.children
});
};
return HashRouter;
}(React.Component)
Example #8
Source File: react-router-dom.js From Learning-Redux with MIT License | 6 votes |
BrowserRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(BrowserRouter, _React$Component);
function BrowserRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.history = createBrowserHistory(_this.props);
return _this;
}
var _proto = BrowserRouter.prototype;
_proto.render = function render() {
return React.createElement(Router, {
history: this.history,
children: this.props.children
});
};
return BrowserRouter;
}(React.Component)
Example #9
Source File: reduxstagram.js From Learning-Redux with MIT License | 6 votes |
/*
Error Logging
*/
// import Raven from 'raven-js';
// import { sentry_url } from './data/config';
// if(window) {
// Raven.config(sentry_url).install();
// }
/*
Rendering
This is where we hook up the Store with our actual component and the router
*/
render(
<Provider store={store}>
{/* Tell the Router to use our enhanced history */}
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={PhotoGrid} />
<Route path="/view/:postId" component={Single}></Route>
</Route>
</Router>
</Provider>,
document.getElementById("root")
);
Example #10
Source File: reduxstagram.js From Learning-Redux with MIT License | 6 votes |
router = ( <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={PhotoGrid}></IndexRoute> <Route path="/view/:postId" component={Single}></Route> </Route> </Router> </Provider> )
Example #11
Source File: index.js From Lambda with MIT License | 6 votes |
ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRedirect to="/home" /> <Route path="home" component={Home} /> <Route path="button" component={ButtonVisual} /> <Route path="nav-item" component={NavItemVisual} /> <Route path="menu-item" component={MenuItemVisual} /> <Route path="list-group-item" component={ListGroupItemVisual} /> </Route> </Router>, mountNode );
Example #12
Source File: react-router-config.js From the-eye-knows-the-garbage with MIT License | 6 votes |
function matchRoutes(routes, pathname,
/*not public API*/
branch) {
if (branch === void 0) {
branch = [];
}
routes.some(function (route) {
var match = route.path ? matchPath(pathname, route) : branch.length ? branch[branch.length - 1].match // use parent match
: Router.computeRootMatch(pathname); // use default "root" match
if (match) {
branch.push({
route: route,
match: match
});
if (route.routes) {
matchRoutes(route.routes, pathname, branch);
}
}
return match;
});
return branch;
}
Example #13
Source File: matchRoutes.js From the-eye-knows-the-garbage with MIT License | 6 votes |
function matchRoutes(routes, pathname, /*not public API*/ branch = []) {
routes.some(route => {
const match = route.path
? matchPath(pathname, route)
: branch.length
? branch[branch.length - 1].match // use parent match
: Router.computeRootMatch(pathname); // use default "root" match
if (match) {
branch.push({ route, match });
if (route.routes) {
matchRoutes(route.routes, pathname, branch);
}
}
return match;
});
return branch;
}
Example #14
Source File: BookingPage.js From git-brunching with GNU General Public License v3.0 | 6 votes |
BookingPage = (props) => {
const memoryHistory = createMemoryHistory();
const history = useHistory();
const { selected } = props;
return (
<div className={style.container}>
{selected == null ? <NotFound />
: (
<div className={style.contentContainer}>
{/* A surrounding div for styling purposes */}
<div className={style.headerContainer}>
<div className={style.header}>
<div
className={style.logo}
onClick={() => { if (window.confirm('Are you sure you want to leave before booking? Progress will not be saved'))changePath("/", history)}}
>
<Logo />
</div>
<h1 className={style.restaurantName}>{selected.Name}</h1>
</div>
</div>
{/* Memory is used to navigate as we don't want to change URL each time */}
<Router history={memoryHistory}>
<Switch>
<Route path="/details" component={() => <ContentContainer type="detail" />} />
<Route path="/confirmation" component={() => <ContentContainer type="confirmation" />} />
<Route path="/complete" component={() => <ConfirmedBooking history={history} />} />
<Route path="/" component={() => <ContentContainer type="time" mainHistory={history} />} />
</Switch>
</Router>
</div>
)}
</div>
);
}
Example #15
Source File: index.jsx From Spoke with MIT License | 6 votes |
ReactDOM.render( <MuiThemeProvider muiTheme={muiTheme}> <ErrorBoundary> <ApolloProvider store={store.data} client={ApolloClientSingleton}> <Suspense fallback={<LoadingIndicator />}> <Router history={history} routes={makeRoutes()} /> </Suspense> </ApolloProvider> </ErrorBoundary> </MuiThemeProvider>, document.getElementById("mount") );
Example #16
Source File: index.js From TimesOfInternet with MIT License | 6 votes |
ReactDOM.render( <Router history={hist}> <Switch> <Route path="/" exact component={BlogPostPage} /> <Route path="/about" component={AboutUsPage} /> <Route path="/contact" component={ContactUsPage} /> <Route component={ErrorPage} /> </Switch> </Router>, document.getElementById("root") );
Example #17
Source File: Root.js From react-stack-grid with MIT License | 5 votes |
Root = ({ routes }) => (
<Router history={hashHistory}>
{routes()}
</Router>
)
Example #18
Source File: index.js From the-eye-knows-the-garbage with MIT License | 5 votes |
ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App} /> </Router> ), document.getElementById('root'));
Example #19
Source File: PlayerRouter.js From Oud with MIT License | 5 votes |
function PlayerRouter() {
return (
<Router>
<Route path="/" component={Player} />
</Router>
);
}
Example #20
Source File: HashRouter.js From Learning-Redux with MIT License | 5 votes |
render() {
return <Router history={this.history} children={this.props.children} />;
}
Example #21
Source File: BrowserRouter.js From Learning-Redux with MIT License | 5 votes |
render() {
return <Router history={this.history} children={this.props.children} />;
}
Example #22
Source File: Root.prod.js From Learning-Redux with MIT License | 5 votes |
Root = ({ store, history }) => (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
)
Example #23
Source File: Root.dev.js From Learning-Redux with MIT License | 5 votes |
Root = ({ store, history }) => (
<Provider store={store}>
<div>
<Router history={history} routes={routes} />
<DevTools />
</div>
</Provider>
)
Example #24
Source File: IndexLinkContainer.spec.js From Lambda with MIT License | 5 votes |
describe("IndexLinkContainer", () => {
["Button", "NavItem", "MenuItem", "ListGroupItem"].forEach((name) => {
describe(name, () => {
const Component = ReactBootstrap[name];
describe("active state", () => {
function renderComponent(location) {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory(location)}>
<Route
path="/"
component={() => (
<IndexLinkContainer to="/">
<Component>Root</Component>
</IndexLinkContainer>
)}
>
<IndexRoute />
<Route path="foo" />
</Route>
</Router>
);
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
return ReactDOM.findDOMNode(component);
}
it("should be active on the index route", () => {
expect(renderComponent("/").className).to.match(/\bactive\b/);
});
it("should not be active on a child route", () => {
expect(renderComponent("/foo").className).to.not.match(/\bactive\b/);
});
});
});
});
});
Example #25
Source File: App.js From mesh-demo with Apache License 2.0 | 5 votes |
routes = ( <Router history={hashHistory}> <Route path='/productList' component={Product} /> <Route path='/checkout' component={CheckOut} /> <Redirect from = '/' to = '/productList' /> <Redirect from = '/*' to = '/' /> </Router> )
Example #26
Source File: edit-schedule.test.js From what-front with MIT License | 4 votes |
describe('Tests EditSchedule', () => {
describe('Render && Form of EditSchedule', () => {
let historyMock;
beforeEach(() => {
useSelector
.mockReturnValue(scheduleMockDataLoading)
.mockReturnValue(scheduleMockData)
.mockReturnValue(studentGroupMockDataLoading)
.mockReturnValue(studentGroupMockData)
.mockReturnValue(mentorsMockData)
.mockReturnValue(themesMockData);
commonHelpers.transformDateTime = jest
.fn()
.mockReturnValue({ formInitialValue: '2021-06-17T02:47' });
historyMock = { push: jest.fn(), location: jest.fn(), listen: jest.fn() };
});
afterEach(cleanup);
it('should loader appear when scheduleSelector .isLoading is true', () => {
const mockedScheduleSelector = {
data: scheduleMockDataLoading,
isLoading: true,
};
useSelector.mockReturnValue(mockedScheduleSelector);
const { container } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={mockedScheduleSelector}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const loader = container.querySelector('.spinner-border');
expect(loader).toBeInTheDocument();
});
it('should loader appear when groupSelector .isLoading is true', () => {
const mockedGroupSelector = {
data: studentGroupMockDataLoading,
isLoading: true,
};
useSelector.mockReturnValue(mockedGroupSelector);
const { container } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={mockedGroupSelector}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const loader = container.querySelector('.spinner-border');
expect(loader).toBeInTheDocument();
});
it('should the component be rendered', () => {
const { getByTestId } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(getByTestId('editForm')).toBeInTheDocument();
});
it('should the Form be rendered correctly', () => {
const { getByTestId } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const groupName = getByTestId('groupName');
const eventStart = getByTestId('eventStart');
const eventFinish = getByTestId('eventFinish');
expect(getByTestId('editForm')).toBeInTheDocument();
expect(groupName.value).toBe('122-18-3');
expect(eventStart.value).toBe('2021-06-17T02:47');
expect(eventFinish.value).toBe('2021-06-17T02:47');
expect(groupName).toBeDisabled();
});
it('should weekDays list = 7 ', () => {
const { container } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const weekDaysList = container.querySelector('#weekDays-list');
fireEvent.click(weekDaysList);
expect(weekDaysList.children.length).toEqual(7);
expect(weekDaysList.children[0].value).toBe('Monday');
});
it('should day of week be chosen', () => {
const { getByPlaceholderText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const weekDay = getByPlaceholderText("Select day('s) of week");
fireEvent.change(weekDay, {
target: { value: helpersData.daysOfWeek[3].name },
});
expect(weekDay.value).toBe('Thursday');
});
});
describe('Redirect correctly', () => {
let historyMock;
let data;
let mockEditedScheduleSelector;
let mockDeletedScheduleSelector;
beforeEach(() => {
data = scheduleMockData;
data.isLoading = false;
mockEditedScheduleSelector = {
isLoading: false,
isLoaded: true,
error: '',
};
mockDeletedScheduleSelector = {
isLoading: false,
isLoaded: true,
error: '',
};
useSelector
.mockReturnValue(mockEditedScheduleSelector)
.mockReturnValue(mockDeletedScheduleSelector)
.mockReturnValue(scheduleMockData)
.mockReturnValue(studentGroupMockData)
.mockReturnValue(mentorsMockData)
.mockReturnValue(themesMockData);
historyMock = { push: jest.fn(), location: jest.fn(), listen: jest.fn() };
});
afterEach(cleanup);
it('should redirrect to page 404 in case of error', () => {
const noData = {
data: '',
isLoading: true,
isLoaded: true,
};
useSelector.mockReturnValue(noData);
render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={noData}
groupData={noData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(historyMock.push).toHaveBeenCalledWith(paths.NOT_FOUND);
});
it('should redirrect to schedule page and show success alert after successful editing', () => {
mockEditedScheduleSelector = {
...data,
isLoaded: true,
};
useSelector
.mockReturnValueOnce(mockEditedScheduleSelector)
.mockReturnValueOnce(mockDeletedScheduleSelector);
render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(useActionsFns.dispatchAddAlert).toHaveBeenCalledWith(
'The schedule has been successfully edited',
'success'
);
});
it('should show error alert after unsuccessful editing', () => {
mockEditedScheduleSelector = {
...data,
isLoaded: false,
error: 'some error',
};
useSelector
.mockReturnValueOnce(mockEditedScheduleSelector)
.mockReturnValueOnce(mockDeletedScheduleSelector);
render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(useActionsFns.dispatchAddAlert).toHaveBeenCalledWith(
mockEditedScheduleSelector.error
);
});
it('should redirrect to schedule page and show success alert after successful deleting', () => {
mockDeletedScheduleSelector = {
...data,
isLoaded: true,
};
useSelector
.mockReturnValueOnce(mockEditedScheduleSelector)
.mockReturnValueOnce(mockDeletedScheduleSelector);
render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(useActionsFns.dispatchAddAlert).toHaveBeenCalledWith(
'The schedule has been successfully deleted',
'success'
);
});
it('should show error alert after unsuccessful deleting', () => {
mockDeletedScheduleSelector = {
...data,
isLoaded: false,
error: 'some error',
};
useSelector
.mockReturnValueOnce(mockEditedScheduleSelector)
.mockReturnValueOnce(mockDeletedScheduleSelector);
render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
expect(useActionsFns.dispatchAddAlert).toHaveBeenCalledWith(
mockDeletedScheduleSelector.error
);
});
it('should open modalWindow when click delete', async () => {
const { getByText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const handleShowModal = jest.fn();
const removeBtn = getByText(/Delete/i);
await waitFor(() => {
fireEvent.click(removeBtn);
handleShowModal();
});
expect(handleShowModal).toHaveBeenCalledTimes(1);
expect(
getByText(/Are you sure you want to exclude this schedule?/i)
).toBeInTheDocument();
});
it('should close modalWindow and delete course when click delete on modalWindow', async () => {
const { getByText, getByRole } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const handleDelete = jest.fn();
const removeBtn = getByText('Delete');
await waitFor(() => {
fireEvent.click(removeBtn);
});
expect(getByRole('button', { name: 'Delete' })).toBeInTheDocument();
expect(getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
const deleteBtn = getByRole('button', { name: 'Delete' });
await waitFor(() => {
fireEvent.click(deleteBtn);
handleDelete();
});
expect(handleDelete).toHaveBeenCalled();
expect(useActionsFns.removeSchedule).toHaveBeenCalled();
});
it('should day of week not Found', () => {
React.useState = jest
.fn()
.mockReturnValue(['', useStates.dayInputError.setDayInputError]);
const { getByPlaceholderText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const weekDay = getByPlaceholderText("Select day('s) of week");
fireEvent.change(weekDay, { target: { value: 'day' } });
expect(useStates.dayInputError.setDayInputError).toHaveBeenCalled();
});
it('should call addDayOfWeek and change state', async () => {
React.useState = jest
.fn()
.mockReturnValue([[], useStates.weekDays.setWeekDays]);
const { container, getByPlaceholderText, getByText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const addDayOfWeek = jest.fn();
const clearField = jest.fn();
const addDayOfWeekBtn = container.querySelector('#add-weekDay-btn');
const weekDay = getByPlaceholderText("Select day('s) of week");
await waitFor(() => {
fireEvent.change(weekDay, {
target: { value: helpersData.daysOfWeek[3].name },
});
});
await waitFor(() => {
fireEvent.click(addDayOfWeekBtn);
addDayOfWeek();
clearField();
});
expect(addDayOfWeek).toHaveBeenCalledTimes(1);
expect(useStates.weekDays.setWeekDays).toHaveBeenCalled();
expect(getByText(/Thursday/i)).toBeInTheDocument();
});
it('should call removeDayOfWeek and change state', async () => {
React.useState = jest
.fn()
.mockReturnValue([[], useStates.weekDays.setWeekDays]);
const { container, getByPlaceholderText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const addDayOfWeek = jest.fn();
const removeDayOfWeek = jest.fn();
const addDayOfWeekBtn = container.querySelector('#add-weekDay-btn');
const weekDay = getByPlaceholderText("Select day('s) of week");
await waitFor(() => {
fireEvent.change(weekDay, {
target: { value: helpersData.daysOfWeek[3].name },
});
});
await waitFor(() => {
fireEvent.click(addDayOfWeekBtn);
addDayOfWeek();
});
const dayContainer = container.querySelector('#chosenWeekDay');
const removeBtn = dayContainer.children[0];
expect(removeBtn).toHaveTextContent('X');
await waitFor(() => {
fireEvent.click(removeBtn);
removeDayOfWeek();
});
expect(removeDayOfWeek).toHaveBeenCalledTimes(1);
expect(useStates.weekDays.setWeekDays).toHaveBeenCalled();
});
it('should change interval', async () => {
React.useState = jest
.fn()
.mockReturnValue([1, useStates.interval.setInterval]);
const { getByTestId } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const intervalInput = getByTestId('interval');
await waitFor(() => {
fireEvent.change(intervalInput, { target: { value: 3 } });
});
expect(useStates.interval.setInterval).toHaveBeenCalled();
expect(intervalInput.value).toBe('3');
});
it('should handleReset', async () => {
React.useState = jest
.fn()
.mockReturnValue([1, useStates.interval.setInterval]);
const { container, getByTestId, getByRole, getByPlaceholderText } = render(
<Router history={historyMock}>
<EditSchedule
id={1}
schedulesData={scheduleMockData}
groupData={studentGroupMockData}
themesData={themesMockData}
mentorsData={mentorsMockData}
/>
</Router>
);
const handleReset = jest.fn();
const setInterval = jest.fn();
const setWeekDays = jest.fn();
const intervalInput = getByTestId('interval');
const cancleBtn = getByRole('button', { name: 'Clear' });
const addDayOfWeekBtn = container.querySelector('#add-weekDay-btn');
const weekDay = getByPlaceholderText("Select day('s) of week");
await waitFor(() => {
fireEvent.change(intervalInput, { target: { value: 3 } });
fireEvent.change(weekDay, {
target: { value: helpersData.daysOfWeek[3].name },
});
fireEvent.click(addDayOfWeekBtn);
});
expect(intervalInput.value).toBe('3');
await waitFor(() => {
fireEvent.click(cancleBtn);
handleReset();
setInterval(1);
setWeekDays([]);
});
expect(handleReset).toHaveBeenCalled();
expect(setInterval).toHaveBeenCalled();
expect(setWeekDays).toHaveBeenCalled();
expect(useStates.interval.setInterval).toHaveBeenCalled();
expect(intervalInput.value).toBe('1');
});
});
});
Example #27
Source File: ConnectedRouter.js From the-eye-knows-the-garbage with MIT License | 4 votes |
createConnectedRouter = function createConnectedRouter(structure) {
var _createSelectors = createSelectors(structure),
getLocation = _createSelectors.getLocation;
/*
* ConnectedRouter listens to a history object passed from props.
* When history is changed, it dispatches action to redux store.
* Then, store will pass props to component to render.
* This creates uni-directional flow from history->store->router->components.
*/
var ConnectedRouter =
/*#__PURE__*/
function (_PureComponent) {
_inherits(ConnectedRouter, _PureComponent);
function ConnectedRouter(props) {
var _this;
_classCallCheck(this, ConnectedRouter);
_this = _possibleConstructorReturn(this, _getPrototypeOf(ConnectedRouter).call(this, props));
var store = props.store,
history = props.history,
onLocationChanged = props.onLocationChanged;
_this.inTimeTravelling = false; // Subscribe to store changes to check if we are in time travelling
_this.unsubscribe = store.subscribe(function () {
// Extract store's location
var _getLocation = getLocation(store.getState()),
pathnameInStore = _getLocation.pathname,
searchInStore = _getLocation.search,
hashInStore = _getLocation.hash; // Extract history's location
var _history$location = history.location,
pathnameInHistory = _history$location.pathname,
searchInHistory = _history$location.search,
hashInHistory = _history$location.hash; // If we do time travelling, the location in store is changed but location in history is not changed
if (pathnameInHistory !== pathnameInStore || searchInHistory !== searchInStore || hashInHistory !== hashInStore) {
_this.inTimeTravelling = true; // Update history's location to match store's location
history.push({
pathname: pathnameInStore,
search: searchInStore,
hash: hashInStore
});
}
});
var handleLocationChange = function handleLocationChange(location, action) {
var isFirstRendering = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// Dispatch onLocationChanged except when we're in time travelling
if (!_this.inTimeTravelling) {
onLocationChanged(location, action, isFirstRendering);
} else {
_this.inTimeTravelling = false;
}
}; // Listen to history changes
_this.unlisten = history.listen(handleLocationChange); // Dispatch a location change action for the initial location.
// This makes it backward-compatible with react-router-redux.
// But, we add `isFirstRendering` to `true` to prevent double-rendering.
handleLocationChange(history.location, history.action, true);
return _this;
}
_createClass(ConnectedRouter, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unlisten();
this.unsubscribe();
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
history = _this$props.history,
children = _this$props.children;
return React.createElement(Router, {
history: history
}, children);
}
}]);
return ConnectedRouter;
}(PureComponent);
ConnectedRouter.propTypes = {
store: PropTypes.shape({
getState: PropTypes.func.isRequired,
subscribe: PropTypes.func.isRequired
}).isRequired,
history: PropTypes.shape({
action: PropTypes.string.isRequired,
listen: PropTypes.func.isRequired,
location: PropTypes.object.isRequired,
push: PropTypes.func.isRequired
}).isRequired,
basename: PropTypes.string,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
onLocationChanged: PropTypes.func.isRequired
};
var mapDispatchToProps = function mapDispatchToProps(dispatch) {
return {
onLocationChanged: function onLocationChanged(location, action, isFirstRendering) {
return dispatch(_onLocationChanged(location, action, isFirstRendering));
}
};
};
var ConnectedRouterWithContext = function ConnectedRouterWithContext(props) {
var Context = props.context || ReactReduxContext;
if (Context == null) {
throw 'Please upgrade to react-redux v6';
}
return React.createElement(Context.Consumer, null, function (_ref) {
var store = _ref.store;
return React.createElement(ConnectedRouter, _extends({
store: store
}, props));
});
};
ConnectedRouterWithContext.propTypes = {
context: PropTypes.object
};
return connect(null, mapDispatchToProps)(ConnectedRouterWithContext);
}
Example #28
Source File: LinkContainer.spec.js From Lambda with MIT License | 4 votes |
describe("LinkContainer", () => {
["Button", "NavItem", "MenuItem", "ListGroupItem"].forEach((name) => {
describe(name, () => {
const Component = ReactBootstrap[name];
it("should make the correct href", () => {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/")}>
<Route
path="/"
component={() => (
<LinkContainer
to={{
pathname: "/foo",
query: { bar: "baz" },
hash: "#the-hash",
}}
>
<Component>Foo</Component>
</LinkContainer>
)}
/>
</Router>
);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(
router,
"A"
);
expect(anchor.getAttribute("href")).to.equal("/foo?bar=baz#the-hash");
});
it("should not add extra DOM nodes", () => {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/")}>
<Route
path="/"
component={() => (
<LinkContainer
to={{
pathname: "/foo",
query: { bar: "baz" },
}}
>
<Component>Foo</Component>
</LinkContainer>
)}
/>
</Router>
);
const container = ReactTestUtils.findRenderedComponentWithType(
router,
LinkContainer
);
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
expect(ReactDOM.findDOMNode(container)).to.equal(
ReactDOM.findDOMNode(component)
);
});
describe("when clicked", () => {
it("should transition to the correct route", () => {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/")}>
<Route
path="/"
component={() => (
<LinkContainer to="/target">
<Component>Target</Component>
</LinkContainer>
)}
/>
<Route
path="/target"
component={() => <div className="target" />}
/>
</Router>
);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(
router,
"A"
);
ReactTestUtils.Simulate.click(anchor, { button: 0 });
const target = ReactTestUtils.findRenderedDOMComponentWithClass(
router,
"target"
);
expect(target).to.exist;
});
it("should call user defined click handlers", () => {
const onClick = sinon.spy();
const childOnClick = sinon.spy();
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/")}>
<Route
path="/"
component={() => (
<LinkContainer to="/target" onClick={onClick}>
<Component onClick={childOnClick}>Foo</Component>
</LinkContainer>
)}
/>
<Route
path="/target"
component={() => <div className="target" />}
/>
</Router>
);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(
router,
"A"
);
ReactTestUtils.Simulate.click(anchor, { button: 0 });
expect(onClick).to.have.been.calledOnce;
expect(childOnClick).to.have.been.calledOnce;
});
});
describe("active state", () => {
function renderComponent(location) {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory(location)}>
<Route
path="/"
component={() => (
<LinkContainer to="/foo">
<Component>Foo</Component>
</LinkContainer>
)}
>
<Route path="foo" />
<Route path="bar" />
</Route>
</Router>
);
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
return ReactDOM.findDOMNode(component);
}
it("should be active when on the target route", () => {
expect(renderComponent("/foo").className).to.match(/\bactive\b/);
});
it("should not be active when on a different route", () => {
expect(renderComponent("/bar").className).to.not.match(/\bactive\b/);
});
it("should respect explicit active prop on container", () => {
const router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/foo")}>
<Route
path="/"
component={() => (
<LinkContainer to="/bar" active>
<Component>Bar</Component>
</LinkContainer>
)}
>
<Route path="foo" />
<Route path="bar" />
</Route>
</Router>
);
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
expect(ReactDOM.findDOMNode(component).className).to.match(
/\bactive\b/
);
});
});
describe("disabled state", () => {
let router;
beforeEach(() => {
router = ReactTestUtils.renderIntoDocument(
<Router history={createMemoryHistory("/")}>
<Route
path="/"
component={() => (
<LinkContainer to="/target" disabled>
<Component>Target</Component>
</LinkContainer>
)}
/>
<Route
path="/target"
component={() => <div className="target" />}
/>
</Router>
);
});
it("should not transition on click", () => {
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(component), {
button: 0,
});
const target = ReactTestUtils.scryRenderedDOMComponentsWithClass(
router,
"target"
);
expect(target).to.be.empty;
});
it("should render with disabled class", () => {
const component = ReactTestUtils.findRenderedComponentWithType(
router,
Component
);
expect(ReactDOM.findDOMNode(component).className).to.match(
/\bdisabled\b/
);
});
});
});
});
});