react-router-dom#MemoryRouter JavaScript Examples

The following examples show how to use react-router-dom#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: Footer.test.js    From Merch-Dropper-fe with MIT License 6 votes vote down vote up
it("expect to render Footer component", () => {
  const wrapper = mount(
    <Provider store={store}>
      <MemoryRouter initialEntries={["/"]}>
        <Footer />
      </MemoryRouter>
    </Provider>
  );

  const div = wrapper.find("div").get(0);
  const ul = wrapper.find("ul a");

  expect(wrapper).toBeTruthy();
  expect(div.props.style).toHaveProperty("display", "block");
  expect(ul).toHaveLength(2);
  expect(ul.containsMatchingElement(<a>Home</a>)).toBeTruthy();
  expect(ul.containsMatchingElement(<a>Store</a>)).toBeTruthy();
});
Example #2
Source File: renderWithProviders.js    From shopping-cart-fe with MIT License 6 votes vote down vote up
export default function renderWithProviders (ui) {
  return {
    ...render(<Provider store={store}>
      <MemoryRouter>
        {ui}
      </MemoryRouter>
              </Provider>)
  }
}
Example #3
Source File: App.test.js    From video-journal-for-teams-fe with MIT License 6 votes vote down vote up
describe("App Component", () => {
	it("should render self without error", () => {
		shallow(
			<MemoryRouter>
				<App />
			</MemoryRouter>
		);
	});
});
Example #4
Source File: Groups.test.js    From edge-frontend with Apache License 2.0 6 votes vote down vote up
describe('Groups', () => {
  const mockStore = configureStore();
  it('should render correctly', () => {
    const { container } = render(
      <RegistryContext.Provider
        value={{
          getRegistry: () => ({
            register: jest.fn(),
          }),
        }}
      >
        <Provider store={mockStore({})}>
          <MemoryRouter initialEntries={['/fleet-managment']}>
            <Route path="/fleet-managment">
              <Groups />
            </Route>
          </MemoryRouter>
        </Provider>
      </RegistryContext.Provider>
    );
    expect(container.querySelector('div')).toMatchSnapshot();
  });
});
Example #5
Source File: AffectedClustersTable.spec.ct.js    From ocp-advisor-frontend with Apache License 2.0 6 votes vote down vote up
describe('empty successful affected clusters table', () => {
  beforeEach(() => {
    mount(
      <MemoryRouter>
        <Intl>
          <Provider store={getStore()}>
            <AffectedClustersTable
              query={{
                isError: false,
                isFetching: false,
                isUninitialized: false,
                isSuccess: true,
                data: { disabled: [], enabled: [] },
              }}
            />
          </Provider>
        </Intl>
      </MemoryRouter>
    );
  });

  it('cannot add filters to empty table', () => {
    cy.get('#name-filter').type('foobar');
    cy.get(TOOLBAR).find(CHIP_GROUP).should('not.exist');
  });

  it('renders no clusters message', () => {
    checkEmptyState('No clusters', true);
  });

  it('renders table headers', () => {
    checkTableHeaders(TABLE_HEADERS);
  });
});
Example #6
Source File: TasksPopover.tests.js    From tasks-frontend with Apache License 2.0 6 votes vote down vote up
describe('TasksPopover', () => {
  let props;
  let mockStore = configureStore();

  beforeEach(() => {
    props = {
      body: TASKS_PAGE_POPOVER_BODY,
      content: <OutlinedQuestionCircleIcon />,
      footer: TASKS_PAGE_POPOVER_FOOTER,
      header: TASKS_PAGE_POPOVER_HEADER,
      label: 'test-aria-label',
    };
  });

  it('should render correctly', async () => {
    const store = mockStore(props);
    const { asFragment } = render(
      <MemoryRouter keyLength={0}>
        <Provider store={store}>
          <TasksPopover {...props} />
        </Provider>
      </MemoryRouter>
    );

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #7
Source File: PersonForm.test.jsx    From sgmr-service with MIT License 6 votes vote down vote up
renderPage = ({
  type, source, pageNumber,
}) => {
  render(
    <MemoryRouter initialEntries={[{ pathname: `/page-${pageNumber}` }]}>
      <PersonForm type={type} source={source} />
    </MemoryRouter>,
  );
}
Example #8
Source File: Nav.test.js    From Lambda with MIT License 6 votes vote down vote up
describe("Links", () => {
  let wrap;
  beforeEach(() => {
    wrap = mount(
      <MemoryRouter initialEntries={["/"]} initialIndex={0}>
        <Nav />
      </MemoryRouter>
    );
  });

  describe("Links", () => {
    it("Home", () => {
      const home = wrap.find("Link").findWhere((n) => n.prop("to") === "/");
      expect(home).toHaveLength(1);
    });

    it("About", () => {
      const about = wrap
        .find("Link")
        .findWhere((n) => n.prop("to") === "/about");
      expect(about).toHaveLength(1);
    });
  });
});
Example #9
Source File: App.test.js    From inventory-management-web with MIT License 6 votes vote down vote up
it('opens homepage after successful login', async () => {
  axiosMock.post.mockResolvedValue({
    data: { auth_token: '49848aadad98a8c8acc8a4c84' },
  });
  const { getByText, getAllByDisplayValue, getByTestId } = render(<App />, {
    wrapper: MemoryRouter,
  });
  const submitBtn = getByTestId('submit');
  const inputs = getAllByDisplayValue('');
  const emailInput = inputs[0];
  const passwordInput = inputs[1];
  await act(async () => {
    await fireEvent.change(emailInput, {
      target: { value: '[email protected]' },
    });
    fireEvent.change(passwordInput, { target: { value: 'admin' } });

    fireEvent.click(submitBtn);
  });

  expect(axiosMock.post).toHaveBeenCalled();
  const homepage = getByText('Inventory Management Home');
  expect(homepage).toBeInTheDocument();
});
Example #10
Source File: App.test.js    From ReactCookbook-source with MIT License 6 votes vote down vote up
describe('<App />', () => {
  test('renders without exploding', () => {
    const div = document.createElement('div');
    ReactDOM.render(
      <MemoryRouter>
        <App />
      </MemoryRouter>,
      div
    );
  });
});
Example #11
Source File: MissionControl.test.js    From resilience-app with GNU General Public License v3.0 6 votes vote down vote up
renderWithStoreAndRouter = (
  ui,
  { initialState = initState, store = createStore(() => initState), route, ...renderOptions } = {}
) => {
  function Wrapper({ children }) {
    return (
      <Provider store={store}>
        <MemoryRouter initialEntries={[route || ""]} initialIndex={0}>
          <ThemeProvider theme={theme}>{children}</ThemeProvider>
        </MemoryRouter>
      </Provider>
    );
  }
  return render(ui, { wrapper: Wrapper, ...renderOptions });
}
Example #12
Source File: EditProvider.spec.jsx    From feedadoc with MIT License 6 votes vote down vote up
describe("editing a provider", () => {
  it("renders without crashing", () => {
    const { getByText } = render(
      <MockedProvider mocks={[]} addTypename={false}>
        <MemoryRouter initialEntries={["/providers/token/edit"]}>
          <EditProvider />
        </MemoryRouter>
      </MockedProvider>
    );
    getByText('Update your request');
  });
});
Example #13
Source File: JobProfilesContainer.test.js    From ui-data-export with Apache License 2.0 6 votes vote down vote up
setupJobProfilesContainer = initialEntries => {
  renderWithIntl(
    <SettingsComponentBuilder>
      <MemoryRouter initialEntries={initialEntries}>
        <JobProfilesContainer
          resources={{
            jobProfiles: {
              hasLoaded: true,
              records: [],
              other: {
                totalRecords: 0,
              },
            },
          }}
          mutator={{ jobProfiles: { POST: noop } }}
          match={{ params: { }, path: '/data-export/job-profiles', url: '/' }}
        />
      </MemoryRouter>,
    </SettingsComponentBuilder>,
    translationsProperties
  );
}
Example #14
Source File: about-us.spec.js    From horondi_admin with MIT License 6 votes vote down vote up
describe('AboutUs component tests', () => {
  beforeEach(() => {
    render(
      <MockedProvider mocks={aboutUsPageDataMock} addTypename={false}>
        <MemoryRouter initialEntries={[routes.pathToAboutUs]}>
          <ThemeProvider theme={themeValue}>
            <Switch>
              <Route path={routes.pathToAboutUs} exact component={AboutUs} />
              <Route
                path={routes.pathToAboutUsTitleEdit}
                exact
                component={AboutUsTitleEdit}
              />
              <Route
                path={routes.pathToAboutUsFooterImgEdit}
                exact
                component={AboutUsFooterImgEdit}
              />
            </Switch>
          </ThemeProvider>
        </MemoryRouter>
      </MockedProvider>
    );
  });

  it('Edit button for editing title successfully navigates to AboutUsTitleEdit page on click', async () => {
    const editButtons = await screen.findAllByTestId('edit_btn');
    const titleEditButton = editButtons[0];
    fireEvent.click(titleEditButton);
    expect(await screen.findByText(enTitle)).toBeInTheDocument();
  });

  it('Edit button for editing section successfully navigates to AboutUsFooterImgEdit page on click', async () => {
    const editButtons = await screen.findAllByTestId('edit_btn');
    const footerImgEditButton = editButtons[4];
    fireEvent.click(footerImgEditButton);
    expect(await screen.findByText(imgLabel)).toBeInTheDocument();
  });
});
Example #15
Source File: test-helpers.js    From tutorial with MIT License 6 votes vote down vote up
export function visit(url) {
  return render(
    <MemoryRouter initialEntries={[url]}>
      <QueryParamProvider ReactRouterRoute={Route}>
        <App />
      </QueryParamProvider>
    </MemoryRouter>
  );
}
Example #16
Source File: User.test.js    From id.co.moonlay-eworkplace-admin-web with MIT License 6 votes vote down vote up
it('renders without crashing', () => {
  const wrapper = mount(
    <MemoryRouter>
      <User match={{params: {id: "1"}, isExact: true, path: "/users/:id", name: "User details"}}/>
    </MemoryRouter>
  );
  expect(wrapper.containsMatchingElement(<strong>Samppa Nori</strong>)).toEqual(true)
  wrapper.unmount()
});
Example #17
Source File: sideBarNavigation.spec.js    From rainbow-modules with MIT License 6 votes vote down vote up
describe('<SideBarNavigation />', () => {
    test('should render the right amount of children', () => {
        const component = mount(
            <Application>
                <MemoryRouter>
                    <SideBarNavigation>
                        <SideBarOption />
                        <SideBarOption />
                        <SideBarOption />
                    </SideBarNavigation>
                </MemoryRouter>
            </Application>,
        );
        const sideBar = component.find(SideBarNavigation);
        expect(sideBar.find(SideBarOption).length).toBe(3);
    });
});
Example #18
Source File: UnAuthOnlyRoute.test.jsx    From frontend-app-authn with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('UnAuthOnlyRoute', () => {
  const routerWrapper = () => (
    <MemoryRouter initialEntries={[LOGIN_PAGE]}>
      <TestApp />
    </MemoryRouter>
  );

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should have called with forceRefresh true', () => {
    const user = {
      username: 'gonzo',
      other: 'data',
    };
    auth.getAuthenticatedUser = jest.fn(() => user);
    auth.fetchAuthenticatedUser = jest.fn(() => ({ then: () => auth.getAuthenticatedUser() }));

    mount(routerWrapper());

    expect(auth.fetchAuthenticatedUser).toBeCalledWith({ forceRefresh: true });
  });

  it('should have called with forceRefresh false', () => {
    auth.getAuthenticatedUser = jest.fn(() => null);
    auth.fetchAuthenticatedUser = jest.fn(() => ({ then: () => auth.getAuthenticatedUser() }));

    mount(routerWrapper());

    expect(auth.fetchAuthenticatedUser).toBeCalledWith({ forceRefresh: false });
  });
});
Example #19
Source File: SupportToolsTab.test.jsx    From frontend-app-support-tools with GNU Affero General Public License v3.0 6 votes vote down vote up
SupportToolsTabWrapper = (props) => (
  <IntlProvider locale="en">
    <MemoryRouter>
      <UserMessagesProvider>
        <SupportToolsTab {...props} />
      </UserMessagesProvider>
    </MemoryRouter>
  </IntlProvider>
)
Example #20
Source File: LteSmallBox.test.jsx    From react-lte with MIT License 6 votes vote down vote up
test('Should render component without crash', () => {
  const dom = <LteSmallBox title={title} message={message} icon={faAddressBook} href={href} />;
  const { container } = render(dom, { wrapper: MemoryRouter });

  expect(container.querySelector('.inner > h3')).toHaveTextContent(title);
  expect(container.querySelector('.inner > p')).toHaveTextContent(message);
  expect(container.querySelector('.icon > svg')).toHaveClass('fa-address-book');
  expect(container.querySelector('a')).toHaveAttribute('href', href);
});
Example #21
Source File: List.test.js    From web-client with Apache License 2.0 6 votes vote down vote up
it("renders with or without a name", () => {
    const history = createMemoryHistory();
    act(() => {
        ReactDOM.createRoot(container)
            .render(<MemoryRouter>
                <AuthContext.Provider value={{ user: null }}>
                    <UsersList history={history} />
                </AuthContext.Provider>
            </MemoryRouter>
            );
    });
    expect(container.innerHTML).toMatch(/Create user<\/button>/);
});
Example #22
Source File: index.stories.js    From Codelabz with Apache License 2.0 6 votes vote down vote up
sidebar = (args) => (
  <ProviderWrapper>
    <MemoryRouter>
            {window.innerWidth > 750 && <Grid
                container
                style={{
                    display: "flex",
                    alignItems: "left",
                    justifyContent: "center",
                    flexDirection: "column",
                    maxHeight: "35rem",
                    margin: "0 0 2rem 0",
                    background: "white",
                    boxShadow: ".5px 2px 5px gray",
                }}
                direction="column"
                style={{
                    width: "100%",
                    overflow: "auto",
                    maxHeight: "25rem",
                    backgroundColor: "transparent",
                    border: "none",
                    boxShadow: "none"
                }}
            >
                <Grid item
                   
                    style={{ minWidth: "100%"}}
                >
                    <SideBar {...args}/>
                </Grid>
            </Grid>}
            {window.innerWidth <= 750 && open && <SideBar {...args} />}
    </MemoryRouter>
  </ProviderWrapper> 
)
Example #23
Source File: index.js    From yi-note with GNU General Public License v3.0 6 votes vote down vote up
render() {
    const container = document.createElement('div');
    container.id = APP_ID;
    container.classList.add(APP_ID);
    document.body.appendChild(container);

    ReactDOM.render(
      <StoreProvider store={this.#store}>
        <MemoryRouter>
          <GlobalStyle />
          <App />
        </MemoryRouter>
      </StoreProvider>,
      container
    );
  }
Example #24
Source File: App.test.js    From littlelink-server with MIT License 6 votes vote down vote up
describe('<App />', () => {
  test('renders without exploding', () => {
    const div = document.createElement('div');
    ReactDOM.render(
      <MemoryRouter>
        <App />
      </MemoryRouter>,
      div,
    );
  });
  test('<App /> snapshot', () => {
    const tree = renderer
      .create(
        <MemoryRouter>
          <App />
        </MemoryRouter>,
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});
Example #25
Source File: GenreCard.test.js    From Oud with MIT License 5 votes vote down vote up
describe('Genre Card Component', () => {
  let component;
  beforeEach(() => {
    const props = {
      item
    }
    component = setup(props);
  })
  it('Should render card-container in right way', () => {
    const wrapper = findByTestAttr(component, "card-container");
    expect(wrapper.length).toBe(1);
  });
  it('Should render card-container in right way', () => {
    const wrapper = findByTestAttr(component, "card");
    expect(wrapper.length).toBe(1);
  });
  it('Should render over layer in right way', () => {
    const wrapper = findByTestAttr(component, "overlayer");
    expect(wrapper.length).toBe(1);
  });
  it('Should render playlist image in right way', () => {
    const wrapper = findByTestAttr(component, "playlist-image");
    expect(wrapper.length).toBe(1);
  });
  it('Should render playlist title in right way', () => {
    const wrapper = findByTestAttr(component, "playlist-title");
    expect(wrapper.length).toBe(1);
  });
  it('Should render playlist link in right way', () => {
    const wrapper = findByTestAttr(component, "playlist-link");
    expect(wrapper.length).toBe(1);
  });
  it('Should render playlist inner text in right way', () => {
    component.setState({ name: "Hemdan" })
    const wrapper = findByTestAttr(component, "playlist-link");
    expect(wrapper.text()).toBe(item.name);
  });
  describe('snapshot test', () => {
    it('renders component correctly', () => {
      const wrapper = mount(
        <MemoryRouter>
          <GenreCard.WrappedComponent item={item} />
        </MemoryRouter >
      )
      expect(wrapper).toMatchSnapshot()
    });
  });
  describe('testing prop types', () => {
    it('should pass true props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { ...item }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeUndefined();
    });
    it('should pass false props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { item: 0 }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeDefined();
    });
    it('should pass false props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { item: true }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeDefined();
    });
    it('should pass false props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { item: jest.fn }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeDefined();
    });
    it('should pass false props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { item: [15] }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeDefined();
    });
    it('should pass false props', () => {
      const result = checkPropTypes(GenreCard.WrappedComponent.propTypes, { item: "" }, 'prop', GenreCard.WrappedComponent.name);
      expect(result).toBeDefined();
    });
  })
});
Example #26
Source File: Navbar.test.js    From Merch-Dropper-fe with MIT License 5 votes vote down vote up
describe("Navbar displays logo and brand name", () => {
  beforeEach(() => {
    useAuth0.mockReturnValue({
      loginWithRedirect: jest.fn(),
      logout: jest.fn(),
    });
  });

  it("renders with logo", () => {
    const wrapper = mount(
      <Provider store={store}>
        <MemoryRouter initialEntries={["/"]}>
          <NavBar />
        </MemoryRouter>
      </Provider>
    );
    const logo = wrapper.find(".BrandLogo");
    const name = wrapper.find(".DesktopWrapper .BrandTitle");

    expect(logo).toBeTruthy();
    expect(name).toBeTruthy();
    expect(name.text()).toEqual("Merch Dropper");
  });

  it("redirects to homepage when logo is clicked", () => {
    let historyMock = {
      push: jest.fn(),
      listen: jest.fn(),
      location: { pathname: "/" },
    };
    const wrapper = mount(
      <Provider store={store}>
        <Router history={historyMock}>
          <NavBar />
        </Router>
      </Provider>
    );

    const logo = wrapper.find(".DesktopWrapper .BrandLogo");

    logo.simulate("click");

    expect(historyMock.push).toHaveBeenCalledTimes(1);
  });

  it("redirects to homepage when brand name is clicked", () => {
    let historyMock = {
      push: jest.fn(),
      listen: jest.fn(),
      location: { pathname: "/" },
    };
    const wrapper = mount(
      <Provider store={store}>
        <Router history={historyMock}>
          <NavBar />
        </Router>
      </Provider>
    );

    const brand = wrapper.find(".DesktopWrapper .BrandTitle");

    brand.simulate("click");

    expect(historyMock.push).toHaveBeenCalledTimes(1);
  });
});
Example #27
Source File: app.view.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
export default function App() {
  // eslint-disable-next-line no-unused-vars
  const [, setIsWeb3Connected] = useState(false);

  useEffect(async () => {
    await Web3.connect();
    setIsWeb3Connected({
      isWeb3Connected: true,
    });
  }, []);

  /*
   * TODO: for path /wallet and /bridge component should render when web3connect is complete
   * like implement a loader till web3connect is not complete
   * for example with blank page:
   *   const web3Boiler = <div>Web3 connection is pending</div>;
   *   '{isWeb3Connected ? <Route path="/wallet" render={() => <Wallet />} /> : web3Boiler}'
   *   instead of '<Route path="/wallet" render={() => <Wallet />} />'
   */
  return (
    <MemoryRouter>
      <ToastContainer />
      <UserProvider>
        <AccountProvider>
          <Switch>
            {/* <Route path="/" exact render={() => <MainPage />} /> */}
            <Route path="/" exact render={() => <Wallet />} />
            <Route path="/bridge" render={() => <Bridge />} />
            <Route path="/transactionPage" render={() => <TransactionPage />} />
            <Route
              path="/issues"
              render={() => {
                window.location = NF3_GITHUB_ISSUES_URL;
              }}
            />
            {/* <Redirect to="/" /> */}
          </Switch>
        </AccountProvider>
      </UserProvider>
    </MemoryRouter>
  );
}
Example #28
Source File: Login.test.js    From treetracker-admin-client with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('Login Page', () => {
  describe('Layout', () => {
    it('has "Greenstand" logo', () => {
      const { container } = render(<Login />, { wrapper: MemoryRouter });
      const logo = screen.queryByAltText('Greenstand logo');
      expect(logo).toBeInTheDocument();
    });
    it('has "Admin Panel" header', () => {
      const { container } = render(<Login />, { wrapper: MemoryRouter });
      console.log(container.querySelector('div > h2').innerHTML);
      const header = screen.queryByRole('heading', { name: 'Admin Panel' });
      expect(header).toBeInTheDocument();
    });
    it('has username input', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      expect(emailInput).toBeInTheDocument();
    });
    it('has password input', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const passwordInput = screen.queryByLabelText(/password/i);
      expect(passwordInput).toBeInTheDocument();
    });
    it('has "Remember me" checkbox', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const checkbox = screen.queryByRole('checkbox', { name: 'Remember me' });
      expect(checkbox).toBeInTheDocument();
    });
    it('has "LOG IN" button', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });
      expect(loginButton).toBeInTheDocument();
    });
  });
  describe('Interactions', () => {
    it('keeps the "LOG IN" button disabled until one of the input fields is empty', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      const passwordInput = screen.queryByLabelText(/password/i);
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });

      userEvent.type(emailInput, 'admin');
      expect(loginButton).toBeDisabled();
      userEvent.clear(emailInput);

      userEvent.type(passwordInput, 'P4ssword');
      expect(loginButton).toBeDisabled();
      userEvent.clear(passwordInput);

      userEvent.type(emailInput, 'admin');
      userEvent.type(passwordInput, 'P4ssword');
      expect(loginButton).toBeEnabled();
    });
    it('displays spinner after clicking the "LOG IN" button', () => {
      render(<Login />, { wrapper: MemoryRouter });
      const emailInput = screen.queryByLabelText(/username/i);
      const passwordInput = screen.queryByLabelText(/password/i);
      const loginButton = screen.queryByRole('button', { name: 'LOG IN' });

      userEvent.type(emailInput, 'admin');
      userEvent.type(passwordInput, 'P4ssword');
      expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();

      userEvent.click(loginButton);

      const progressbar = screen.queryByRole('progressbar');
      expect(progressbar).toBeInTheDocument();
    });
  });
});
Example #29
Source File: DetailsHeader.test.js    From edge-frontend with Apache License 2.0 5 votes vote down vote up
describe('DetailsHeader', () => {
  it('renders correctly', async () => {
    const openUpdateWizard = jest.fn();
    const imageData = {
      data: {
        Data: {
          images: [
            {
              image: {
                ID: 100,
                Version: 1,
                ImageType: 'rhel-edge-installer',
                CreatedAt: '2022-01-24T18:27:24.331554Z',
                UpdatedAt: Date.now(),
                Status: 'BUILDING',
                Installer: {
                  ImageBuildISOURL: '',
                },
              },
            },
            {
              image: {
                ID: 200,
                Version: 2,
                ImageType: 'rhel-edge-installer',
                CreatedAt: '2022-01-24T18:27:24.331554Z',
                Status: 'SUCCESS',
                Installer: {
                  ImageBuildISOURL: 'test.com',
                },
              },
            },
          ],
          image_set: {
            ID: 101,
            Name: 'test image',
            Account: '1234',
          },
        },
      },
    };

    const registry = init(logger);

    const { container } = render(
      <RegistryContext.Provider
        value={{
          getRegistry: () => registry,
        }}
      >
        <Provider store={registry.getStore()}>
          <DetailsHeader
            imageData={imageData}
            openUpdateWizard={openUpdateWizard}
          />
        </Provider>
      </RegistryContext.Provider>,
      { wrapper: MemoryRouter }
    );

    expect(screen.getAllByRole('listitem')[0].children[0].innerHTML).toEqual(
      'Manage Images'
    );
    expect(screen.getAllByRole('listitem')[1].innerHTML).toContain(
      'test image'
    );
    expect(screen.getByRole('heading', { name: /test image/i })).toBeDefined();
    expect(screen.getByText(/last updated/i).children[0].innerHTML).toContain(
      'Just now'
    );
    fireEvent.click(screen.getByRole('button', { name: /actions/i }));
    fireEvent.click(
      screen.getByRole('button', { name: /create new version/i })
    );
    expect(openUpdateWizard).toBeCalled();

    expect(container.querySelector('div')).toMatchSnapshot();
  });
});