Проверка предупреждений с помощью библиотеки react-native-testing
Можно react-native-testing-library
найти оповещение, созданное с помощью Alert.alert()
?
Мое приложение создает предупреждение, как ожидалось, но этот тест не работает:
// test
const Wrapper = props => (
<Fragment>
<SubscriptionProductDetailScreen
product={product}
testID={"SUBSCRIPTION_DETAIL_SCREEN"}
addToCart={addToCartSpy}
{...props}
/>
</Fragment>
);
function createWrapper(customProps) {
const wrapper = render(<Wrapper {...customProps} />);
return wrapper;
}
beforeEach(() => {
wrapper = createWrapper();
});
// later, inside a describe block:
it('should show an alert if no bars are selected', async () => {
pressSubmitButton()
expect(addToCartSpy).not.toHaveBeenCalled()
// const alert = await waitForElement(
// wrapper.queryByText("Please select up to 4 free items.")
// )
const alert = wrapper.queryByText("Please select up to 4 free items.")
expect(alert).not.toBeNull()
});
// brief excerpt from the component (the onPress handler for the submit button)
addToCart() {
const freeItems = this.state.items[0]
if (!freeItems || !freeItems.selections.length) {
Alert.alert("Error", "Please select up to 4 free items.")
return
}
const item: {...}
this.props.addToCart(item)
}
Асинхронная версия (waitForElement
, прокомментировал) тоже не удается.
Опять же, предупреждение работает в самом приложении, и утверждение о том, что действие отправки, вызванное обработчиком, проходит.
1 ответ
Alert
не входит в стек приложения React - это системная функция, поэтому ее нельзя напрямую протестировать с помощью react-native-testing-library
. Однако вы можете хотя бы проверить, было ли оно выполнено:
import { Alert } from 'react-native'
jest.mock('react-native', () => {
const RN = jest.requireActual('react-native')
return Object.setPrototypeOf(
{
Alert: {
...RN.Alert,
alert: jest.fn(),
},
},
RN,
)
})
test('...', () => {
// ...
expect(Alert.alert).toHaveBeenCalled()
})