在我的新 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/