在我新的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')`,
); */
});
});
答案 0 :(得分:13)
如果您使用的是 @testing-library/react
而不是 @testing-library/react-native
,并且您的图像具有 alt
属性,则可以避免使用 getByDataTestId
而是使用 {{1 }}。
getByAltText
不幸的是,似乎React Native Testing Library does not include getByAltText
。 (谢谢你,@P.Lorand!)
答案 1 :(得分:2)
说起来有点困难,因为我们看不到UIViewController
组件或其功能...但是,如果它像UIActivityIndicator
组件一样工作,我们可以做类似的事情。
通过图像组件的角色/ alt文本/ data-testid在图像组件上使用选择器:
<ImageBackground>
然后在该组件上查找属性:
<img>
答案 2 :(得分:2)
当我使用 getByAltText
和 getByDataTestId
时,我遇到了 is not a function
错误。
所以对我有用的是:
const imgSource = require('../../../../assets/images/image.jpg');
const { queryByTestId } = render(<MyComponent testID='icon' source={imgSource}/>);
expect(queryByTestId('icon').props.source).toBe(imgSource);
我使用 @testing-library/react-native": "^7.1.0
答案 3 :(得分:1)
我今天遇到了这个问题,发现如果您的 URI 是 URL 而不是必需文件,那么将源 uri
拼接到 testID
上效果很好。
export const imageID = 'image_id';
...
<Image testID={`${imageID}_${props.uri}`} ... />
import {
imageID
}, from '.';
...
const testURI = 'https://picsum.photos/200';
const { getByTestId } = render(<Component uri={testURI} />);
expect(getByTestId()).toBeTruthy();