Files
iNaturalistReactNative/tests/unit/components/SharedComponents/Tabs/Tabs.test.js
T
2026-08-26 17:32:52 -05:00

101 lines
3.0 KiB
JavaScript

import { fireEvent, render, screen } from "@testing-library/react-native";
import Tabs, { SCROLLABLE_TAB_WIDTH_RATIO } from "components/SharedComponents/Tabs/Tabs";
import React from "react";
import { Dimensions, ScrollView } from "react-native";
const TAB_1 = "TAB_1";
const TAB_2 = "TAB_2";
const TAB_3 = "TAB_3";
const TAB_4 = "TAB_4";
const tab1Click = jest.fn();
const tab2Click = jest.fn();
const tabs = [
{
id: TAB_1,
text: TAB_1,
onPress: tab1Click,
},
{
id: TAB_2,
text: TAB_2,
onPress: tab2Click,
},
];
describe( "Tabs", () => {
it( "should render correctly", () => {
render( <Tabs tabs={tabs} activeId={TAB_1} /> );
expect( screen ).toMatchSnapshot();
} );
it( "should not have accessibility errors", () => {
// const tabComp = <Tabs tabs={tabs} activeId={TAB_1} />;
// Disabled during the update to RN 0.78
// expect( tabComp ).toBeAccessible();
} );
it( "should render per-tab content from renderComponent", async () => {
const { Text } = jest.requireActual( "react-native" );
const tabsWithComponents = tabs.map( tab => ( {
...tab,
renderComponent: () => <Text>{`${tab.id} content`}</Text>,
} ) );
render( <Tabs tabs={tabsWithComponents} activeId={TAB_1} /> );
expect( await screen.findByText( `${TAB_1} content` ) ).toBeTruthy();
expect( await screen.findByText( `${TAB_2} content` ) ).toBeTruthy();
} );
it( "should be clicked and display proper text", async () => {
render( <Tabs tabs={tabs} activeId={TAB_1} /> );
const tab1 = await screen.findByLabelText( TAB_1 );
const tab2 = await screen.findByLabelText( TAB_2 );
expect( tab1 ).toBeTruthy();
expect( tab2 ).toBeTruthy();
expect( tab1 ).toBeSelected();
expect( tab1 ).toBeExpanded();
expect( tab2 ).not.toBeSelected();
expect( tab2 ).toBeCollapsed();
fireEvent.press( tab2 );
expect( tab1Click ).not.toHaveBeenCalled();
expect( tab2Click ).toHaveBeenCalled();
} );
} );
describe( "scrollable Tabs", () => {
const { width } = Dimensions.get( "window" );
const tabWidth = width * SCROLLABLE_TAB_WIDTH_RATIO;
const scrollableTabs = [TAB_1, TAB_2, TAB_3, TAB_4].map( id => ( {
id,
text: id,
onPress: jest.fn( ),
} ) );
beforeEach( () => {
ScrollView.prototype.scrollTo.mockClear( );
} );
it( "should keep the strip at the start when the first tab is active", () => {
render( <Tabs tabs={scrollableTabs} activeId={TAB_1} scrollable /> );
expect( ScrollView.prototype.scrollTo ).toHaveBeenCalledWith(
{ x: 0, animated: false },
);
} );
it( "should scroll the newly active tab into view when the user changes tabs", () => {
render( <Tabs tabs={scrollableTabs} activeId={TAB_1} scrollable /> );
ScrollView.prototype.scrollTo.mockClear( );
screen.update( <Tabs tabs={scrollableTabs} activeId={TAB_3} scrollable /> );
expect( ScrollView.prototype.scrollTo ).toHaveBeenCalledWith(
{ x: 2.5 * tabWidth - width / 2, animated: true },
);
} );
} );