首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用react-native- Test -library测试警报

使用react-native- Test -library测试警报
EN

Stack Overflow用户
提问于 2019-10-01 06:43:46
回答 1查看 1.4K关注 0票数 0

react-native-testing-library能否找到使用Alert.alert()创建的警报

我的应用程序按预期创建了警报,但此测试失败:

代码语言:javascript
复制
// 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,注释)也会失败。

同样,警报在应用程序本身中工作,并传递由处理程序调用的分派操作的断言。

EN

回答 1

Stack Overflow用户

发布于 2020-04-27 05:12:34

Alert不在React应用程序堆栈中--它是一个系统特性,因此不能用react-native-testing-library直接测试。但是,您至少可以验证它是否已执行:

代码语言:javascript
复制
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()
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58176129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档