react-router#MemoryRouter JavaScript Examples

The following examples show how to use react-router#MemoryRouter. 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.stories.js    From Codelabz with Apache License 2.0 6 votes vote down vote up
Template = (args) => {
  const [List, setList] = useState(1);

  const acitvitylist = [
    {
      id: 1,
      text: "About",
    },
    {
      id: 2,
      text: "Feeds",
    },
  ];

  return (
    <ProviderWrapper>
      <MemoryRouter>
        <ActivityList
          {...args}
          value={List}
          toggle={(item) => {
            setList(item.id);
          }}
          acitvitylist={acitvitylist}
        />
      </MemoryRouter>
    </ProviderWrapper>
  );
}
Example #2
Source File: EmptyPosts.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
function renderComponent(location = `/${courseId}/`) {
  return render(
    <IntlProvider locale="en">
      <ResponsiveContext.Provider value={{ width: 1280 }}>
        <AppProvider store={store}>
          <MemoryRouter initialEntries={[location]}>
            <EmptyPosts subTitleMessage={messages.emptyMyPosts} />
          </MemoryRouter>
        </AppProvider>
      </ResponsiveContext.Provider>
    </IntlProvider>,
  );
}
Example #3
Source File: body.test.js    From Classroom-Bot with MIT License 6 votes vote down vote up
describe("routes using memory router", () => {
  it("should show Main component for / router (using memory router)", () => {
    const component = mount(
      <MemoryRouter initialentries="{['/']}">
        <Main />
      </MemoryRouter>
    );
    expect(component.find(Main)).toHaveLength(1);
  });
});
Example #4
Source File: TopicsView.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
function renderComponent() {
  render(
    <IntlProvider locale="en">
      <AppProvider store={store}>
        <DiscussionContext.Provider value={{ courseId }}>
          <MemoryRouter initialEntries={[`/${courseId}/topics/`]}>
            <Route path="/:courseId/topics/">
              <TopicsView />
            </Route>
            <Route path="/:courseId/category/:category">
              <TopicsView />
            </Route>
            <Route
              render={({ location }) => {
                lastLocation = location;
                return null;
              }}
            />
          </MemoryRouter>
        </DiscussionContext.Provider>
      </AppProvider>
    </IntlProvider>,
  );
}
Example #5
Source File: index.stories.js    From Codelabz with Apache License 2.0 6 votes vote down vote up
Template = (args) => {
  return (
    <ProviderWrapper>
      <MemoryRouter>
        <Activity {...args} />
      </MemoryRouter>
    </ProviderWrapper>
  );
}
Example #6
Source File: Route.test.js    From Doto with MIT License 6 votes vote down vote up
test("Settings page should redirect to / without logging in first", () => {
    const wrapper = mount(
        <MemoryRouter initialEntries={["/settings"]}>
            <Route />
        </MemoryRouter>,
    );
    expect(wrapper.find(SettingsPage)).toHaveLength(0);
    expect(wrapper.find(Login)).toHaveLength(1);
});
Example #7
Source File: DiscussionSidebar.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
function renderComponent(displaySidebar = true, location = `/${courseId}/`) {
  const wrapper = render(
    <IntlProvider locale="en">
      <ResponsiveContext.Provider value={{ width: 1280 }}>
        <AppProvider store={store}>
          <DiscussionContext.Provider value={{ courseId }}>
            <MemoryRouter initialEntries={[location]}>
              <DiscussionSidebar displaySidebar={displaySidebar} />
            </MemoryRouter>
          </DiscussionContext.Provider>
        </AppProvider>
      </ResponsiveContext.Provider>
    </IntlProvider>,
  );
  container = wrapper.container;
  return container;
}
Example #8
Source File: body.test.js    From Classroom-Bot with MIT License 6 votes vote down vote up
describe("routes using memory router", () => {
  it("should show Main component for / router (using memory router)", () => {
    const component = mount(
      <MemoryRouter initialentries="{['/main']}">
        <Main />
      </MemoryRouter>
    );
    expect(component.find(Main)).toHaveLength(1);
  });
});
Example #9
Source File: About.test.js    From ReactCookbook-source with MIT License 6 votes vote down vote up
describe('About component', () => {
  it('should show people by default', () => {
    render(
      <MemoryRouter initialEntries={[{ pathname: '/about' }]}>
        <Route path="/about/:tabId?">
          <About />
        </Route>
      </MemoryRouter>
    )

    expect(screen.getByText('Kip Russel')).toBeInTheDocument()

    fireEvent(
      screen.getByText('Offices'),
      new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
      })
    )

    expect(screen.getByText('South Dakota')).toBeInTheDocument()
  })
})
Example #10
Source File: DiscussionsHome.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
function renderComponent(location = `/${courseId}/`) {
  render(
    <IntlProvider locale="en">
      <ResponsiveContext.Provider value={{ width: 1280 }}>
        <AppProvider store={store}>
          <MemoryRouter initialEntries={[location]}>
            <DiscussionsHome />
          </MemoryRouter>
        </AppProvider>
      </ResponsiveContext.Provider>
    </IntlProvider>,
  );
}
Example #11
Source File: story-page.web.js    From polaris with Apache License 2.0 6 votes vote down vote up
StoryPage = ({ title, storyFn, children, url, width }) => (
  <ThemeProvider>
    <I18nextProvider i18n={i18n}>
      <MemoryRouter>
        <View style={[styles.root, { width }]}>
          <Title>{title}</Title>
          <Text style={styles.url}>{url}</Text>
          <Text style={styles.description}>{children}</Text>
          {storyFn()}
        </View>
      </MemoryRouter>
    </I18nextProvider>
  </ThemeProvider>
)
Example #12
Source File: index.stories.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
Template = (args) => (
  <ProviderWrapper>
    <MemoryRouter>
      <OrgDelete {...args} />
    </MemoryRouter>
  </ProviderWrapper>
)
Example #13
Source File: hooks.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('Hooks', () => {
  function ComponentWithHook() {
    const refContainer = useRef(null);
    useContainerSizeForParent(refContainer);
    return (
      <div>
        <div ref={refContainer} />
      </div>
    );
  }

  function renderComponent() {
    return render(
      <IntlProvider locale="en">
        <ResponsiveContext.Provider value={{ width: 1280 }}>
          <AppProvider store={store}>
            <MemoryRouter initialEntries={['/']}>
              <ComponentWithHook />
            </MemoryRouter>
          </AppProvider>
        </ResponsiveContext.Provider>
      </IntlProvider>,
    );
  }

  let parent;
  beforeEach(() => {
    store = initializeStore();
    parent = window.parent;
  });
  afterEach(() => {
    window.parent = parent;
  });
  test('useContainerSizeForParent enabled', async () => {
    delete window.parent;
    window.parent = { ...window, postMessage: jest.fn() };
    const { unmount } = renderComponent();
    // Once for LMS and one for learning MFE
    await waitFor(() => expect(window.parent.postMessage).toHaveBeenCalledTimes(2));
    // Test that size is reset on unmount
    unmount();
    await waitFor(() => expect(window.parent.postMessage).toHaveBeenCalledTimes(4));
    expect(window.parent.postMessage).toHaveBeenLastCalledWith(
      { type: 'plugin.resize', payload: { height: null } },
      getConfig().LMS_BASE_URL,
    );
  });
  test('useContainerSizeForParent disabled', async () => {
    window.parent.postMessage = jest.fn();
    renderComponent();
    await waitFor(() => expect(window.parent.postMessage).not.toHaveBeenCalled());
  });
});
Example #14
Source File: Route.test.js    From Doto with MIT License 5 votes vote down vote up
test("invalid path should redirect to 404", () => {
    const wrapper = mount(
        <MemoryRouter initialEntries={["/random"]}>
            <Route />
        </MemoryRouter>,
    );
    expect(wrapper.find(NotFound)).toHaveLength(1);
});
Example #15
Source File: preview.js    From twitter-frontend with GNU General Public License v3.0 5 votes vote down vote up
addDecorator(story => <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>);
Example #16
Source File: index.stories.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
Template = (args) => (
  <ProviderWrapper>
    <MemoryRouter>
      <Navbar {...args} />
    </MemoryRouter>
  </ProviderWrapper>
)
Example #17
Source File: About.stories.js    From ReactCookbook-source with MIT License 5 votes vote down vote up
ToAbout = () => (
  <MemoryRouter initialEntries={[{ pathname: '/about' }]}>
    <Route path="/about/:tabId?">
      <About />
    </Route>
  </MemoryRouter>
)
Example #18
Source File: index.stories.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
Template = (args) => (
  <ProviderWrapper>
    <MemoryRouter>
      <Orgusers {...args} />
    </MemoryRouter>
  </ProviderWrapper>
)
Example #19
Source File: PostsView.test.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
async function renderComponent({
  postId, topicId, category, myPosts,
} = { myPosts: false }) {
  let path = generatePath(Routes.POSTS.ALL_POSTS, { courseId });
  let page;
  if (postId) {
    path = generatePath(Routes.POSTS.ALL_POSTS, { courseId, postId });
    page = 'posts';
  } else if (topicId) {
    path = generatePath(Routes.POSTS.PATH, { courseId, topicId });
    page = 'posts';
  } else if (category) {
    path = generatePath(Routes.TOPICS.CATEGORY, { courseId, category });
    page = 'category';
  } else if (myPosts) {
    path = generatePath(Routes.POSTS.MY_POSTS, { courseId });
    page = 'my-posts';
  }
  await render(
    <IntlProvider locale="en">
      <AppProvider store={store}>
        <MemoryRouter initialEntries={[path]}>
          <DiscussionContext.Provider value={{
            courseId,
            postId,
            topicId,
            category,
            page,
          }}
          >
            <Switch>
              <Route path={Routes.POSTS.MY_POSTS}>
                <PostsView />
              </Route>
              <Route
                path={[Routes.POSTS.PATH, Routes.POSTS.ALL_POSTS, Routes.TOPICS.CATEGORY]}
                component={PostsView}
              />
            </Switch>
          </DiscussionContext.Provider>
        </MemoryRouter>
      </AppProvider>
    </IntlProvider>,
  );
}
Example #20
Source File: index.stories.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
Template = (args) => (
  <ProviderWrapper>
    <MemoryRouter>
      <MyTutorials {...args} />
    </MemoryRouter>
  </ProviderWrapper>
)
Example #21
Source File: MissionPlanner.test.js    From DMS_React with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('<AddMedicine />', () => {
  let wrapper;

  let store;

  beforeEach(() => {
    store = mockStore({ 
    users:["user1", "user2"]
  });
  store.dispatch=jest.fn();
  })






test('invalid path should redirect to 404', () => 
{  const wrapper = mount( 
        <Provider store={store}><MemoryRouter initialEntries={['dms.prokurainnovations.com/drone']}>   
        <MissionPlanner match={{url:"dms.prokurainnovations.com"}}/> 
      </MemoryRouter>  </Provider> 
      );  
      expect(wrapper.find(missionView)).toHaveLength(0);
      expect(wrapper.find(missionLists)).toHaveLength(0);

    });
    test('missionView', () => 
{  const wrapper = mount( 
        <Provider store={store}><MemoryRouter initialEntries={['dms.prokurainnovations.com/missionview']}>   
        <MissionPlanner match={{url:"dms.prokurainnovations.com"}}/> 
      </MemoryRouter>  </Provider> 
      );  
      expect(wrapper.find(missionView)).toHaveLength(1);
      expect(wrapper.find(missionLists)).toHaveLength(0);

    });
    test('missionLists', () => 
{  const wrapper = mount( 
        <Provider store={store}><MemoryRouter initialEntries={['dms.prokurainnovations.com/missionlist']}>   
        <MissionPlanner match={{url:"dms.prokurainnovations.com"}}/> 
      </MemoryRouter>  </Provider> 
      );  
      expect(wrapper.find(missionView)).toHaveLength(0);
      expect(wrapper.find(missionLists)).toHaveLength(1);

    });
  })
Example #22
Source File: About.test.js    From ReactCookbook-source with MIT License 5 votes vote down vote up
describe('About component', () => {
  it.skip('this will break because there is no router', () => {
    render(<About />)

    expect(screen.getByText('Kip Russel')).toBeInTheDocument()
  })
  it('should show people', () => {
    render(
      <MemoryRouter>
        <About />
      </MemoryRouter>
    )

    expect(screen.getByText('Kip Russel')).toBeInTheDocument()
  })
  it('should show offices if in route', () => {
    render(
      <MemoryRouter initialEntries={[{ pathname: '/about/offices' }]}>
        <About />
      </MemoryRouter>
    )

    expect(screen.getByText('South Dakota')).toBeInTheDocument()
  })
  it('should be able to click to offices', () => {
    render(
      <MemoryRouter initialEntries={[{ pathname: '/about' }]}>
        <About />
      </MemoryRouter>
    )

    expect(screen.getByText('Kip Russel')).toBeInTheDocument()

    fireEvent(
      screen.getByText('Offices'),
      new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
      })
    )

    expect(screen.getByText('South Dakota')).toBeInTheDocument()
  })
})
Example #23
Source File: index.test.js    From agenda with MIT License 4 votes vote down vote up
describe('ContactEdit Component Snapshot', () => {
    let store;
    let component;
    let contact;
    const match = {
        params: {
            id: null
        }
    };

    beforeEach(() => {
        contact = {
            firstName: '',
            lastName: '',
            email: '',
            gender: '',
            birthDate: '',
            phoneNumber: '',
            address: '',
            role: '',
            notes: ''
        };

        store = mockStore({
            contacts: {
                contact
            }
        });
    });

    test('should mount Component', () => {
        const snapshot = renderer.create(
            <Provider store={store}>
                <MemoryRouter>
                    <ContactEdit {...{match}}/>
                </MemoryRouter>
            </Provider>
        ).toJSON();

        expect(snapshot).toMatchSnapshot();
    });

    function mountComponent() {
        return mount(
            <Provider store={store}>
                <MemoryRouter>
                    <ContactEdit {...{match}}/>
                </MemoryRouter>
            </Provider>
        );
    }

    it('should render with given state from store', () => {
        component = mountComponent();
        forEach([
            'firstName',
            'lastName',
            'email',
            'gender',
            'birthDate',
            'phoneNumber',
            'address',
            'role',
            'notes'
        ], field => {
            const inputField = component.find(Input).find({name: field});
            expect(inputField.exists()).toBe(true);
        });
    });

    it('should call onChange event for firstName with the expected params', () => {
        component = mountComponent();
        const inputField = component.find(Input).find({name: 'firstName'});
        expect(inputField.exists()).toBe(true);
        // Busco el Ășltimo componente, (el hijo)
        inputField.last().simulate('change', {target: {value: 'fake-firstName'}});
        expect(store.getActions()).toEqual([
            {
                type: UPDATE_CONTACT_DATA,
                contact: {
                    ...contact,
                    firstName: 'fake-firstName'
                }
            }
        ]);
    });

    it('should call onChange event for lastName with the expected params', () => {
        component = mountComponent();
        const inputField = component.find(Input).find({name: 'lastName'});
        expect(inputField.exists()).toBe(true);
        inputField.last().simulate('change', {target: {value: 'fake'}});
        expect(store.getActions()).toEqual([
            {
                type: UPDATE_CONTACT_DATA,
                contact: {
                    ...contact,
                    lastName: 'fake'
                }
            }
        ]);

        inputField.last().simulate('change', {target: {value: 'fake-lastName'}});
        expect(store.getActions()).toEqual([
            {
                type: UPDATE_CONTACT_DATA,
                contact: {
                    ...contact,
                    lastName: 'fake'
                }
            },
            {
                type: UPDATE_CONTACT_DATA,
                contact: {
                    ...contact,
                    lastName: 'fake-lastName'
                }
            }
        ]);
    });
});
Example #24
Source File: MostLoanedDocumentsList.test.js    From react-invenio-app-ils with MIT License 4 votes vote down vote up
describe('MostLoanedDocumentsList tests', () => {
  let component;
  afterEach(() => {
    if (component) {
      component.unmount();
    }
  });

  it('should load the component', () => {
    const component = shallow(
      <MostLoanedDocumentsList
        data={{ hits: [], total: 0 }}
        fetchMostLoanedDocuments={() => {}}
      />
    );
    expect(component).toMatchSnapshot();
  });

  it('should fetch documents on mount', () => {
    const mockedFetchLoans = jest.fn();
    component = mount(
      <MostLoanedDocumentsList
        data={{ hits: [], total: 0 }}
        fetchMostLoanedDocuments={mockedFetchLoans}
      />
    );
    expect(mockedFetchLoans).toHaveBeenCalled();
  });

  it('should render documents', () => {
    const data = {
      hits: [
        {
          id: 1,
          updated: stringDate,
          created: stringDate,
          pid: 'doc1',
          metadata: {
            ...testData[0],
            pid: 'doc1',
            loan_count: 1,
            extension_count: 1,
            items: { total: 2 },
            eitems: { total: 2 },
            circulation: {
              past_loans_count: 1,
            },
            relations: {},
          },
        },
        {
          id: 2,
          updated: stringDate,
          created: stringDate,
          pid: 'doc2',
          metadata: {
            ...testData[1],
            pid: 'doc2',
            loan_count: 1,
            extension_count: 1,
            items: { total: 2 },
            eitems: { total: 2 },
            circulation: {
              past_loans_count: 1,
            },
            relations: {},
          },
        },
      ],
      total: 2,
    };
    component = mount(
      <MemoryRouter>
        <MostLoanedDocumentsList
          data={data}
          fetchMostLoanedDocuments={() => {}}
        />
      </MemoryRouter>
    );

    const rows = component.find('Item');
    expect(rows).toHaveLength(2);
  });
});
Example #25
Source File: Users.test.js    From DMS_React with GNU Affero General Public License v3.0 4 votes vote down vote up
describe('<AddMedicine />', () => {
    let wrapper;
  
    let store;
  
    beforeEach(() => {
      store = mockStore({ 
      users:["user1", "user2"]
    });
    store.dispatch=jest.fn();
    })
  
    afterEach(() => {
      jest.clearAllMocks();
    });
    it("route",()=>{try{
        wrapper = mount( 
           <Provider store={store} >
           <MemoryRouter initialEntries={['/random']}>   
          <Users users={{users1:"sa", users2:"as"}}/> 
         </MemoryRouter>  
         </Provider>
   
         );  
         expect(wrapper).toMatchSnapshot();
        }
        catch{}
   })
      
it("route",()=>{try{
     wrapper = mount( 
        <Provider store={store} >
        <MemoryRouter initialEntries={['/random']}>   
       <Users users={{users1:"sa", users2:"as"}}/> 
      </MemoryRouter>  
      </Provider>

      );  
      expect(wrapper.find(ListUsers)).toHaveLength(0);
      expect(wrapper.find(EditUser)).toHaveLength(0);
      expect(wrapper.find(CreateUser)).toHaveLength(0);
     }
     catch{}
})
it("route",()=>{
    try{

    wrapper = mount( 
        <Provider store={store} >
       <MemoryRouter initialEntries={['/app/users/list-users']}>   
      <Users users={{users1:"sa", users2:"as"}}/> 
     </MemoryRouter>        </Provider>

     );  
     expect(wrapper.find(ListUsers)).toHaveLength(1);
     expect(wrapper.find(EditUser)).toHaveLength(0);
     expect(wrapper.find(CreateUser)).toHaveLength(0);
        }
        catch{}
})
it("route",()=>{
    try{
    wrapper = mount( 
        <Provider store={store} >
       <MemoryRouter initialEntries={['/app/users/create-user']}>   
    <Users users={{users1:"sa", users2:"as"}}/> 
     </MemoryRouter>  
     </Provider>

     );  
     expect(wrapper.find(ListUsers)).toHaveLength(0);
     expect(wrapper.find(EditUser)).toHaveLength(0);
     expect(wrapper.find(CreateUser)).toHaveLength(1);
    }
    catch{}
})
it("route",()=>{
    try{
    wrapper = mount( 
        <Provider store={store} >
       <MemoryRouter initialEntries={['/app/users/edit-user']}>   
      <Users users={{users1:"sa", users2:"as"}}/> 
     </MemoryRouter>  
           </Provider>

     );  
     expect(wrapper.find(ListUsers)).toHaveLength(0);
     expect(wrapper.find(EditUser)).toHaveLength(1);
     expect(wrapper.find(CreateUser)).toHaveLength(0);
    }catch{

    }
})
})