Run*_*ror 14 jestjs react-native-testing-library
在我的新 React Native 应用程序中,我想添加一些 Jest 测试。
一个组件渲染背景图像,该图像直接位于项目assets文件夹中。
现在我偶然发现了如何测试此图像是否实际上是从该路径中获取的,因此存在于组件中并正确呈现。
我尝试将toHaveStylefrom@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>
);
};
Run Code Online (Sandbox Code Playgroud)
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')`,
); */
});
});
Run Code Online (Sandbox Code Playgroud)
Nat*_*hur 16
如果您使用的是@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')
});
Run Code Online (Sandbox Code Playgroud)
文档。
不幸的是,React Native 测试库似乎不包含getByAltText. (谢谢你,@P.Lorand!)
当我使用时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);
Run Code Online (Sandbox Code Playgroud)
我用@testing-library/react-native": "^7.1.0
这有点难说,因为我们看不到<ImageBackground>组件或它的作用……但如果它像<img>组件一样工作,我们可以做这样的事情。
通过其role / alt text / data-testid在图像组件上使用选择器:
const { getByDataTestId } = render(<Background background={background}>
</Background>);
Run Code Online (Sandbox Code Playgroud)
然后在该组件上查找属性:
expect(getByDataTestId('background')).toHaveAttribute('src', '../../../../assets/images/image.jpg')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11583 次 |
| 最近记录: |