@testing-library/react-native#fireEvent TypeScript Examples
The following examples show how to use
@testing-library/react-native#fireEvent.
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: ListItem.test.tsx From natds-rn with ISC License | 6 votes |
describe('ListItem component', () => {
it('Should render ListItem component correctly', () => {
const { toJSON } = renderList()
expect(toJSON()).toMatchSnapshot()
})
it('Should render ListItem with state selected', () => {
const { toJSON } = renderList({ selected: true })
expect(toJSON()).toMatchSnapshot()
})
it('Should render ListItem with ripple if is clickable', () => {
const { toJSON } = renderList({ onPress: jest.fn() })
expect(toJSON()).toMatchSnapshot()
})
it('Should not render ListItem with ripple if is selected', () => {
const { toJSON } = renderList({ onPress: jest.fn(), selected: true })
expect(toJSON()).toMatchSnapshot()
})
it('Should call the given onPress function', () => {
const onPress = jest.fn()
const { queryByTestId } = renderList({ onPress })
const listItem = queryByTestId('list-item-wrapper')
if (listItem) {
fireEvent.press(listItem)
}
expect(onPress).toHaveBeenCalled()
})
})
Example #2
Source File: CodeInput.spec.tsx From mobile with Apache License 2.0 | 6 votes |
describe('CodeInput', () => {
const changeMock = jest.fn();
let componentQuery: any;
beforeEach(async () => {
componentQuery = await waitFor(() =>
render(
<StorageServiceProvider>
<ThemeProvider>
<CodeInput value="" onChange={changeMock} accessibilityLabel="codeInput" />
</ThemeProvider>
</StorageServiceProvider>,
),
);
});
afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
it('returns trimmed text', async () => {
const textInput = componentQuery.getByTestId('textInput');
fireEvent.changeText(textInput, ' MYSECRETCODE ');
expect(changeMock).toHaveBeenCalledWith('MYSECRETCODE');
});
// eslint-disable-next-line jest/no-commented-out-tests
/* TODO: uncomment after https://github.com/cds-snc/covid-alert-app/pull/844 is merged
it('disallows special characters on input', () => {
const changeMock = jest.fn();
const textInput = componentQuery.getByHintText('codeInput');
fireEvent.changeText(textInput, ' MY?SECRETCODE ');
expect(changeMock).toBeCalledWith('MYSECRETCODE');
});
*/
});
Example #3
Source File: CreditCardForm.test.tsx From rn-credit-card with MIT License | 6 votes |
it('validates credit card number', async () => {
const { queryByText, getByTestId } = get.render()
// does not display validation message until input is filled
const cardInput = getByTestId('TextField.cardNumber')
fireEvent.changeText(cardInput, '55555555')
await waitFor(() => {
expect(queryByText(/This card number looks invalid./)).toBeNull()
})
// invalid card
fireEvent.changeText(cardInput, '5555555555554440')
await waitFor(() => {
expect(queryByText(/This card number looks invalid./)).not.toBeNull()
})
// valid card
fireEvent.changeText(cardInput, '5555 5555 5555 4444')
await waitFor(() => {
expect(queryByText(/This card number looks invalid./)).toBeNull()
})
})
Example #4
Source File: CreditCardForm.test.tsx From rn-credit-card with MIT License | 6 votes |
it('validates expiration date', async () => {
const { queryByText, getByTestId } = get.render()
const input = getByTestId('TextField.expiration')
// passed expiration date
fireEvent.changeText(input, '1018')
await waitFor(() =>
expect(queryByText(/This expiration date looks invalid./)).not.toBeNull(),
)
// valid date
fireEvent.changeText(input, '10/23')
await waitFor(() =>
expect(queryByText(/This expiration date looks invalid./)).toBeNull(),
)
})
Example #5
Source File: FloatingCart.tsx From rocketseat-gostack-11-desafios with MIT License | 6 votes |
describe('Dashboard', () => {
it('should be able to calculate the cart total', async () => {
const { getByText } = render(<FloatingCart />);
expect(getByText('8000')).toBeTruthy();
});
it('should be able to show the total quantity of itens in the cart', async () => {
const { getByText } = render(<FloatingCart />);
expect(getByText('15 itens')).toBeTruthy();
});
it('should be able to navigate to the cart', async () => {
const { getByTestId } = render(<FloatingCart />);
act(() => {
fireEvent.press(getByTestId('navigate-to-cart-button'));
});
expect(navigate).toHaveBeenCalledWith('Cart');
});
});
Example #6
Source File: CreditCardForm.test.tsx From rn-credit-card with MIT License | 6 votes |
it('submits the form', async () => {
const { getByText, getByTestId } = get.render()
fireEvent.changeText(getByTestId('TextField.holderName'), 'Halil Bilir')
fireEvent.changeText(getByTestId('TextField.cardNumber'), '5555555555554444')
fireEvent.changeText(getByTestId('TextField.expiration'), '0224')
fireEvent.changeText(getByTestId('TextField.cvv'), '333')
fireEvent.press(getByText('Submit'))
await waitFor(() =>
expect(get.onSubmit).toHaveBeenLastCalledWith({
holderName: 'Halil Bilir',
// cardNumber and expiration are now formatted
cardNumber: '5555 5555 5555 4444',
expiration: '02/24',
cvv: '333',
}),
)
})
Example #7
Source File: AppProvider.test.tsx From DoobooIAP with MIT License | 6 votes |
describe('[AppProvider] rendering test', () => {
let json: renderer.ReactTestRendererJSON;
const component = (
<AppProvider>
<FakeChild />
</AppProvider>
);
it('should match component and snapshot', () => {
json = renderer.create(component).toJSON();
expect(json).toMatchSnapshot();
expect(json).toBeTruthy();
});
it('should call [resetUser] when button pressed', () => {
testingLib = render(component);
const btn = testingLib.queryByTestId('BUTTON');
act(() => {
fireEvent.press(btn);
});
});
it('should call [default] when button pressed', () => {
testingLib = render(component);
const btn = testingLib.queryByTestId('BUTTON_NOT_VALID');
act(() => {
fireEvent.press(btn);
});
});
});
Example #8
Source File: createElement.test.tsx From react-performance-testing with MIT License | 6 votes |
test('should get correct value when Component is updated', async () => { const Child = () => <p>test</p>; const Counter = () => { const [count, setCount] = React.useState(0); return ( <View> <Text>{count}</Text> <Child /> <Button title="button" onPress={() => setCount((c) => c + 1)} /> </View> ); }; const { renderCount } = perf(React); const { getByText } = render(<Counter />); fireEvent.press(getByText('button')); await wait(() => expect(renderCount.current).toEqual({ Counter: { value: 2 }, Child: { value: 2 }, }), ); });
Example #9
Source File: Link.test.tsx From natds-rn with ISC License | 6 votes |
describe('Link component', () => {
it('should render the correct color token', () => {
const { queryByTestId } = render(link(defaultProps))
expect(queryByTestId('link')).toHaveStyle({ color: '#227bbd' })
})
it('should render with underline style', () => {
const { queryByTestId } = render(
link({ ...defaultProps, type: 'underline' })
)
expect(queryByTestId('link')).toHaveStyle({
textDecorationLine: 'underline'
})
})
it('should render without underline style as default', () => {
const { queryByTestId } = render(link(defaultProps))
expect(queryByTestId('link')).toHaveStyle({
textDecorationLine: 'none'
})
})
it('should call the given onPress function', () => {
const onPress = jest.fn()
const { getByTestId } = render(link({ ...defaultProps, onPress }))
fireEvent.press(getByTestId('link'))
expect(onPress).toHaveBeenCalled()
})
it('should take a snapshot', () => {
const component = render(link(defaultProps)).toJSON()
expect(component).toMatchSnapshot()
})
})
Example #10
Source File: CreditCardForm.test.tsx From rn-credit-card with MIT License | 6 votes |
it('validates cvv', async () => {
const { queryByText, getByTestId } = get.render()
const input = getByTestId('TextField.cvv')
// invalid input
fireEvent.changeText(input, '4444')
await waitFor(() =>
expect(queryByText('This security code looks invalid.')).not.toBeNull(),
)
// valid input
fireEvent.changeText(input, '333')
await waitFor(() =>
expect(queryByText('This security code looks invalid.')).toBeNull(),
)
})
Example #11
Source File: Tab.test.tsx From natds-rn with ISC License | 6 votes |
describe('Tab component actions', () => {
it('Should call the given onChange function', () => {
const onChangeMock = jest.fn()
const { queryByTestId } = renderTab(render, {
...defaultProps,
onChange: onChangeMock
})
const secondTab = queryByTestId('ds-tab').children[1]
fireEvent.press(secondTab)
expect(onChangeMock).toHaveBeenCalledTimes(1)
})
it('Should have bottom border on the first active tab as default', () => {
// corrigir
const { queryByTestId } = renderTab(render, defaultProps)
const firstTab = queryByTestId('ds-tab-item-0')
expect(firstTab).toHaveStyle({
borderBottomColor: '#F4F4'
})
})
it('Should add bottom border on tab item when the given tab is pressed', () => {
const { queryByTestId } = renderTab(render, defaultProps)
const thirdTab = queryByTestId('ds-tab-item-2')
fireEvent.press(thirdTab)
expect(thirdTab).toHaveStyle({
borderBottomColor: '#F4F4'
})
})
})
Example #12
Source File: Button.test.tsx From lets-fork-native with MIT License | 6 votes |
test('Button', () => {
const handlePress = jest.fn()
const { getByText } = render(
<Button
onPress={handlePress}
size="sm"
color="purple"
>
Press Me
</Button>,
)
const button = getByText('Press Me')
fireEvent.press(button)
expect(handlePress).toBeCalledTimes(1)
})
Example #13
Source File: Input.test.tsx From lets-fork-native with MIT License | 6 votes |
test('Input', () => {
const handleChange = jest.fn()
const famousWomanInHistory = 'Ada Lovelace'
const { getByPlaceholderText } = render(
<Input placeholder="Input" value="" handleChange={handleChange} />,
)
const input = getByPlaceholderText('Input')
fireEvent.changeText(input, famousWomanInHistory)
expect(handleChange).toBeCalledWith(famousWomanInHistory)
})
Example #14
Source File: Menu.test.tsx From lets-fork-native with MIT License | 6 votes |
test('Menu', () => {
const navigation: any = { // eslint-disable-line
navigate: jest.fn(),
}
const { getAllByTestId, getAllByRole } = render(
<Menu navigation={navigation} />,
)
let modal = getAllByTestId('modal')
expect(modal[0].props.visible).toEqual(false)
const buttons = getAllByRole('button')
fireEvent.press(buttons[0])
modal = getAllByTestId('modal')
expect(modal[0].props.visible).toEqual(true)
fireEvent.press(buttons[1])
expect(navigation.navigate).toBeCalledWith('Share')
fireEvent.press(buttons[2])
expect(navigation.navigate).toBeCalledWith('Match')
})
Example #15
Source File: MultiSelect.test.tsx From lets-fork-native with MIT License | 6 votes |
test('MultiSelect', () => {
const handleSelect = jest.fn()
const { getAllByRole, getByText, getAllByTestId } = render(
<MultiSelect items={CATEGORIES} handleSelect={handleSelect} />,
)
let modal = getAllByTestId('modal')
expect(modal[0].props.visible).toEqual(false)
const openButton = getByText(/Filter by Categories/i)
fireEvent.press(openButton)
modal = getAllByTestId('modal')
expect(modal[0].props.visible).toEqual(true)
// Clicking first button adds category to selected categories
const categoryButtons = getAllByRole('button')
fireEvent.press(categoryButtons[0])
expect(handleSelect).toBeCalledWith([CATEGORIES[0].id])
// Clicking first button again removes
fireEvent.press(categoryButtons[0])
expect(handleSelect).toBeCalledWith([])
})
Example #16
Source File: Price.test.tsx From lets-fork-native with MIT License | 6 votes |
test('Price', () => {
const handleSelected = jest.fn()
const { getByRole } = render(
<Price n={1} selected={[false, false]} setSelected={handleSelected}>
$
</Price>,
)
const button = getByRole('button')
fireEvent.press(button)
expect(handleSelected).toBeCalledWith([true, false])
})
Example #17
Source File: Share.test.tsx From lets-fork-native with MIT License | 6 votes |
test('Share', () => {
const shareSpy = jest.spyOn(RNShare, 'share')
const { getAllByRole } = render(
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Details"
>
{(props): React.ReactElement => (
<Share {...props} party={party} />
)}
</Stack.Screen>
</Stack.Navigator>
</NavigationContainer>,
)
const button = getAllByRole('button')[1]
fireEvent.press(button)
expect(shareSpy).toBeCalledTimes(1)
})
Example #18
Source File: SwitchableText.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(
name: string,
props?: ObjectPartial<SwitchableTextProps>,
rerenderProps?: ObjectPartial<SwitchableTextProps>,
) {
test(name, async () => {
const {getByTestId, rerender} = render(
<SwitchableText {...defaultProps} {...props} />,
);
if (props?.texts ? props.texts.length > 0 : defaultProps.texts.length > 0) {
const text = getByTestId('text');
fireEvent(text, 'layout', {nativeEvent: {layout: {width: 100}}});
}
if (rerenderProps) {
rerender(
<SwitchableText {...defaultProps} {...props} {...rerenderProps} />,
);
}
});
}
Example #19
Source File: ButtonGroup.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(
name: string,
props?: ObjectPartial<ButtonGroupProps>,
rerenderProps?: ObjectPartial<ButtonGroupProps>,
) {
test(name, async () => {
const {getAllByTestId, rerender} = render(
<ButtonGroup {...defaultProps} {...props} />,
);
const buttons = getAllByTestId('button');
for (const button of buttons) {
fireEvent.press(button);
}
if (rerenderProps) {
rerender(<ButtonGroup {...defaultProps} {...props} {...rerenderProps} />);
}
});
}
Example #20
Source File: Collapse.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<CollapseProps>) {
test(name, async () => {
const {getByTestId, rerender} = render(
<Collapse {...defaultProps} {...props} />,
);
const view = getByTestId('view');
fireEvent(view, 'layout', {nativeEvent: {layout: {}}});
rerender(
<Collapse {...defaultProps} {...props} visible={!props?.visible} />,
);
fireEvent(view, 'layout', {nativeEvent: {layout: {}}});
});
}
Example #21
Source File: ExpansionPanel.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<ExpansionPanelProps>) {
test(name, async () => {
const {getByTestId, rerender} = render(
<ExpansionPanel {...defaultProps} {...props} />,
);
const panel = getByTestId('panel');
fireEvent(panel, 'press');
fireEvent(panel, 'layout', {nativeEvent: {layout: {}}});
rerender(<ExpansionPanel {...props} visible={!props?.visible} />);
});
}
Example #22
Source File: Marquee.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<MarqueeProps>) {
test(name, async () => {
const {getByTestId} = render(<Marquee {...defaultProps} {...props} />);
const container = getByTestId('container');
const width =
props?.containerStyle?.width || defaultProps.containerStyle?.width || 0;
fireEvent(container, 'layout', {
nativeEvent: {
layout: {
width,
},
},
});
if (width) {
const marquee = getByTestId('marquee');
fireEvent(marquee, 'contentSizeChange');
}
});
}
Example #23
Source File: Radio.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<RadioProps>) {
test(name, async () => {
const {getAllByTestId} = render(<Radio {...defaultProps} {...props} />);
const radioItems = getAllByTestId('radio-item');
for (const radioItem of radioItems) {
fireEvent.press(radioItem);
}
});
}
Example #24
Source File: Modal.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<ModalProps>) {
test(name, async () => {
const {getByTestId, rerender} = render(
<Modal {...defaultProps} {...props} />,
);
const backdrop = getByTestId('backdrop');
fireEvent.press(backdrop);
rerender(<Modal {...defaultProps} {...props} visible={!props?.visible} />);
});
}
Example #25
Source File: Slider.test.tsx From react-native-design-kit with MIT License | 6 votes |
function runTest(name: string, props?: ObjectPartial<SliderProps>) {
test(name, async () => {
const {getByTestId} = render(<Slider {...defaultProps} {...props} />);
const trackContainer = getByTestId('track-container');
fireEvent(trackContainer, 'responderStart');
fireEvent(trackContainer, 'responderMove');
fireEvent(trackContainer, 'layout', {nativeEvent: {layout: {width: 250}}});
const thumbContainer = getByTestId('thumb-container');
fireEvent(thumbContainer, 'layout', {
nativeEvent: {layout: {width: 10, height: 20}},
});
fireEvent(trackContainer, 'startShouldSetResponder');
fireEvent(trackContainer, 'responderStart', {
nativeEvent: {pageX: 50, locationX: 50},
});
fireEvent(trackContainer, 'responderMove', {
nativeEvent: {pageX: 100, locationX: 100},
});
if (props?.button) {
const buttonStart = getByTestId('button-start');
const buttonEnd = getByTestId('button-end');
fireEvent.press(buttonStart);
fireEvent.press(buttonEnd);
}
});
}
Example #26
Source File: Header.spec.tsx From react-native-network-logger with MIT License | 6 votes |
test('share button renders when provided with value', async () => {
const { getByTestId } = render(
<Header shareContent="share me">My Title</Header>
);
expect(getByTestId('header-text').props.children).toEqual('My Title');
expect(getByTestId('header-share')).toBeDefined();
act(() => {
fireEvent.press(getByTestId('header-share'));
});
expect(Share.share).toHaveBeenCalledWith({ message: 'share me' });
});
Example #27
Source File: Picker.test.tsx From react-native-design-kit with MIT License | 5 votes |
function runTest(name: string, props?: ObjectPartial<PickerProps<string>>) {
test(name, async () => {
const {getByTestId} = render(<Picker {...defaultProps} {...props} />);
const button = getByTestId('button');
fireEvent.press(button);
});
}
Example #28
Source File: Checkbox.test.tsx From natds-rn with ISC License | 5 votes |
describe('Checkbox component', () => {
describe('render', () => {
it('should render checkbox correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox />)
expect(toJSON()).toMatchSnapshot()
})
it('should render checkbox selected correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox selected />)
expect(toJSON()).toMatchSnapshot()
})
it('should render checkbox indeterminate selected correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox indeterminate selected />)
expect(toJSON()).toMatchSnapshot()
})
it('should render checkbox with label correctly', () => {
const { getByTestId } = renderWithTheme(<Checkbox label="testing-label" />)
expect(getByTestId('checkbox-label')).toHaveTextContent('testing-label')
})
it('should render checkbox disabled correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox disabled />)
expect(toJSON()).toMatchSnapshot()
})
it('should render checkbox selected but disabled correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox disabled selected />)
expect(toJSON()).toMatchSnapshot()
})
it('should render checkbox indeterminate selected but disabled correctly', () => {
const { toJSON } = renderWithTheme(<Checkbox disabled selected />)
expect(toJSON()).toMatchSnapshot()
})
it('should render icon inside box when selected is true', () => {
const { getByTestId } = renderWithTheme(<Checkbox selected />)
expect(getByTestId('natds-icon')).toBeTruthy()
})
})
describe('actions', () => {
it('should call the onPress function when the user touches the checkbox', () => {
const onPress = jest.fn()
const { getByTestId } = renderWithTheme(<Checkbox onPress={onPress} value="testing-value" />)
const checkbox = getByTestId('checkbox')
fireEvent.press(checkbox)
expect(onPress).toHaveBeenCalledWith('testing-value')
})
it('should call the onPress function when the user touches the checkbox label', () => {
const onPress = jest.fn()
const { getByTestId } = renderWithTheme(<Checkbox onPress={onPress} value="testing-value" label="testing-label" />)
const checkboxLabel = getByTestId('checkbox-label')
fireEvent.press(checkboxLabel)
expect(onPress).toHaveBeenCalledWith('testing-value')
})
})
})
Example #29
Source File: App.spec.tsx From rocketseat-gostack-11-desafios with MIT License | 5 votes |
describe('Dashboard', () => {
it('should be able to list products', async () => {
apiMock.onGet('products').reply(200, [
{
id: '1234',
title: 'Cadeira Rivatti',
image_url:
'https://http2.mlstatic.com/cadeira-rivatti-branca-pes-madeira-confortavel-bonita-D_NQ_NP_981901-MLB20422264882_092015-F.jpg',
price: 400,
},
{
id: '123456',
title: 'Poltrona de madeira',
image_url:
'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRod5Tf0R0LkCjClrgAJU0tM713nyqHTP2lFbXU1o5zheYpwgfonTTde8swBNlahgij4hGeOgn7hQ&usqp=CAc',
price: 600,
},
]);
const { getByText, getByTestId } = render(<Dashboard />);
await wait(() => expect(getByText('Cadeira Rivatti')).toBeTruthy(), {
timeout: 200,
});
expect(getByText('Cadeira Rivatti')).toBeTruthy();
expect(getByTestId('add-to-cart-1234')).toBeTruthy();
expect(getByText('Poltrona de madeira')).toBeTruthy();
expect(getByTestId('add-to-cart-123456')).toBeTruthy();
});
it('should be able to add item to cart', async () => {
const useCartMocked = mocked(useCart);
const addToCart = jest.fn();
useCartMocked.mockReturnValue({
addToCart,
products: [],
increment: jest.fn(),
decrement: jest.fn(),
});
const products = [
{
id: '1234',
title: 'Cadeira Rivatti',
image_url:
'https://http2.mlstatic.com/cadeira-rivatti-branca-pes-madeira-confortavel-bonita-D_NQ_NP_981901-MLB20422264882_092015-F.jpg',
price: 400,
},
{
id: '123456',
title: 'Poltrona de madeira',
image_url:
'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRod5Tf0R0LkCjClrgAJU0tM713nyqHTP2lFbXU1o5zheYpwgfonTTde8swBNlahgij4hGeOgn7hQ&usqp=CAc',
price: 600,
},
];
apiMock.onGet('products').reply(200, products);
const { getByText, getByTestId } = render(<Dashboard />);
await wait(() => expect(getByText('Cadeira Rivatti')).toBeTruthy(), {
timeout: 200,
});
act(() => {
fireEvent.press(getByTestId('add-to-cart-1234'));
});
expect(addToCart).toHaveBeenCalledWith(products[0]);
});
});