jestjs - Jest+React 原生测试库 : How to test an image src?

标签 jestjs react-native-testing-library

在我的新 React Native 应用程序中,我想添加一些 Jest 测试。
一个组件渲染背景图像,该图像直接位于 assets 中的项目中。文件夹。
现在我偶然发现了如何测试此图像是否实际上是从该路径中获取的,因此存在于组件中并正确呈现。
我尝试使用 toHaveStyle来自 @testing-library/jest-native使用容器,返回错误 toHaveStyle不是函数。然后我用 queryByTestId 尝试了同样的方法,同样的错误。当我这样做时 expect(getByTestId('background').toBeInTheDocument);然后我觉得这没用,因为它只检查是否存在具有此 testId 的元素,而不检查图像源。
请问这个怎么测试啊毕竟,测试图像源真的有意义吗?
这是我的代码:
1.) 应该测试的组件( Background ):

const Background: React.FC<Props> = () => {
  const image = require('../../../../assets/images/image.jpg');
    
  return (
    <View>
      <ImageBackground testID="background" source={image} style={styles.image}></ImageBackground>
    </View>
  );
};
2.) 测试:
import React from 'react';
import {render, container} from 'react-native-testing-library';
import {toHaveStyle} from '@testing-library/jest-native';
import '@testing-library/jest-native/extend-expect';
import Background from '../Background';

describe('Background', () => {   
  test('renders Background image', () => {
    const {getByTestId} = render(<Background></Background>);
    expect(getByTestId('background').toBeInTheDocument);

/*    const container = render(<Background background={background}></Background>);
expect(container).toHaveStyle(
  `background-image: url('../../../../assets/images/image.jpg')`,
); */

/*     expect(getByTestId('background')).toHaveStyle(
  `background-image: url('../../../../assets/images/image.jpg')`,
); */

  });
});

最佳答案

如果您使用的是 @testing-library/react而不是 @testing-library/react-native ,并且您有一个 alt属性,您可以避免使用 getByDataTestId而是使用 getByAltText .

it('uses correct src', async () => {
    const { getByAltText } = await render(<MyComponent />);

    const image = getByAltText('the_alt_text');

    expect(image.src).toContain('the_url');
    // or
    expect(image).toHaveAttribute('src', 'the_url')
});
Documentation .
不幸的是,似乎React Native Testing Library does not include getByAltText . (谢谢,@P.Lorand!)

关于jestjs - Jest+React 原生测试库 : How to test an image src?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509527/

相关文章:

javascript - Jest.js - 测试是否已调用组件方法(React.js)

react-native - react native 测试-立即行动

react-native - 使用 React Native 测试库和 Jest 测试 setTimeout

在 Jest 测试中,react-native-reanimated useSharedValue 不会更新

react-native - 用玩笑 react 原生元素不起作用

typescript - 如何确定哪个 Jest 测试在超时内无法运行?

reactjs - 当 CSS 使用 @import 时 Jest 失败

javascript - 如何使用 axios 和 async/await 断言错误

javascript - 模拟 Axios 来测试 .catch()

typescript - 当 TypeScript 阻止我时,如何将 testId 属性添加到用于测试库的 React Native 组件?