【发布时间】:2021-12-10 10:03:33
【问题描述】:
我在使用测试库的前端项目方面有一些经验,但我绝对不是专家。在大多数项目的代码审查过程中,发现一些具有这种结构的测试套件真的很常见:
// Original code: https://github.com/callstack/react-native-testing-library/blob/0ede61780bd8788dfa09572643a14c9988c7b92b/examples/reactnavigation/src/__tests__/AppNavigator.test.js#L24
test('clicking on one item takes you to the details screen', async () => {
const component = (
<NavigationContainer>
<AppNavigator />
</NavigationContainer>
);
const { findByText } = render(component);
const toClick = await findByText('Item number 5');
fireEvent(toClick, 'press');
// ---------------- is this neccessary? --------------------
const newHeader = await findByText('Showing details for 5');
const newBody = await findByText('the number you have chosen is 5');
expect(newHeader).toBeTruthy();
expect(newBody).toBeTruthy();
// ---------------------------------------------------------
});
我的疑问是,如果我们最终不会因为这种方法来检查 DOM 上是否存在元素而变得多余......
根据docs,如果我们使用getBy 或findBy,当没有匹配时应该会抛出错误。因此,我假设 getBy 无法返回虚假值,或者 findBy 无法解析虚假值。如果它是真的,那么也许我们不需要再次检查它。有意义吗?
所以我想知道如果我们这样做会不会很糟糕:
test('clicking on one item takes you to the details screen', async () => {
const component = (
<NavigationContainer>
<AppNavigator />
</NavigationContainer>
);
const { findByText } = render(component);
const toClick = await findByText('Item number 5');
fireEvent(toClick, 'press');
await findByText('Showing details for 5');
await findByText('the number you have chosen is 5');
});
Idk 如果有意义,但 afaik 检查这些调用是否没有引发错误应该足以验证 DOM 上是否存在元素,对吗?
【问题讨论】:
-
是的,在这种情况下就足够了。但是,为了一致性和可读性,我发现最好有明确的断言(以
expect语句的形式)。
标签: react-native react-testing-library testing-library react-native-testing-library