使用本机测试库测试警报

时间:2019-09-30 22:43:46

标签: react-native react-native-testing-library

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 个答案:

答案 0 :(得分:0)

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()
})
相关问题