In my new React Native app, I want to add some Jest tests.
One component renders a background image, which is located directly in the project in assets
folder.
Now I stumbled about how to test if this image is actually taken from this path, therefore present in the component, and rendered correctly.
I tried using toHaveStyle
from @testing-library/jest-native
with a container, which returned the error toHaveStyle
is not a function. Then I tried the same with queryByTestId
, same error. When I do expect(getByTestId('background').toBeInTheDocument);
then I feel this is useless, because it only checks if an element with this testId is present, but not the image source.
Please, how can I test this? Does it actually make sense to test an image source after all?
Here is my code:
1.) The component that should be tested (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.) The test:
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')`,
); */
});
});
image.getAttribute('src')
– Scantling