리액트 테스트 라이브러리:테스트 스타일(특히 배경 이미지)
저는 TypeScript로 리액트 앱을 만들고 있습니다.저는 리액트 테스트 라이브러리와 함께 성분 테스트를 합니다.
착륙 페이지에 쓸 시차 부품을 만들고 있어요
컴포넌트는 소품을 통해 이미지를 전달하고 JSS를 통해 배경 이미지로 설정합니다.
<div
className={parallaxClasses}
style={{
backgroundImage: "url(" + image + ")",
...this.state
}}
>
{children}
</div>
다음은 제가 작성한 단위 테스트입니다.
import React from "react";
import { cleanup, render } from "react-testing-library";
import Parallax, { OwnProps } from "./Parallax";
afterEach(cleanup);
const createTestProps = (props?: object): OwnProps => ({
children: null,
filter: "primary",
image: require("../../assets/images/bridge.jpg"),
...props
});
describe("Parallax", () => {
const props = createTestProps();
const { getByText } = render(<Parallax {...props} />);
describe("rendering", () => {
test("it renders the image", () => {
expect(getByText(props.image)).toBeDefined();
});
});
});
그러나 다음과 같이 말할 수 없습니다.
● Parallax › rendering › it renders the image
Unable to find an element with the text: bridge.jpg. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
<body>
<div>
<div
class="Parallax-parallax-3 Parallax-primaryColor-4"
style="background-image: url(bridge.jpg); transform: translate3d(0,0px,0);"
/>
</div>
</body>
16 | describe("rendering", () => {
17 | test("it renders the image", () => {
> 18 | expect(getByText(props.image)).toBeDefined();
| ^
19 | });
20 | });
21 | });
at getElementError (node_modules/dom-testing-library/dist/query-helpers.js:30:10)
at getAllByText (node_modules/dom-testing-library/dist/queries.js:336:45)
at firstResultOrNull (node_modules/dom-testing-library/dist/query-helpers.js:38:30)
at getByText (node_modules/dom-testing-library/dist/queries.js:346:42)
at Object.getByText (src/components/Parallax/Parallax.test.tsx:18:14)
Jest 및 react-testing-library를 사용하여 이미지가 배경 이미지로 올바르게 설정되어 있는지 테스트하려면 어떻게 해야 합니까?
getByText
이미지 또는 CSS를 찾을 수 없습니다.이 기능은 지정한 텍스트를 사용하여 DOM 노드를 찾는 것입니다.
고객님의 경우, 제가 추가하겠습니다.data-testid
parameter를 사용합니다(<div data-testid="background">
를 사용하여 컴포넌트를 찾습니다.getByTestId
.
그 후 다음과 같이 테스트할 수 있습니다.
expect(getByTestId('background')).toHaveStyle(`background-image: url(${props.image})`)
를 인스톨 하고 있는 것을 확인합니다.
data-testid를 성분에 추가하지 않으려면 react-testing-library의 용기를 사용할 수 있습니다.
const {container} = render(<Parallax {...props})/>
expect(container.firstChild).toHaveStyle(`background-image: url(${props.image})`)
루트 노드의 백그라운드이미지를 테스트하고 있기 때문에 이 솔루션은 컴포넌트 테스트에 적합합니다.다만, 다음의 문서에 주의해 주세요.
컨테이너를 사용하여 렌더링된 요소를 쿼리하는 경우 다시 고려해야 합니다.다른 쿼리는 테스트 중인 컴포넌트에 대한 변경에 대해 보다 쉽게 대응할 수 있도록 설계되었습니다.컨테이너를 사용하여 요소를 쿼리하지 마십시오!
에 더하여toHaveStyle
JsDOM Matcher
, 를 사용할 수도 있습니다.style
현재 dom 요소가 사용할 수 있는 속성
요소 DOM API
expect(getByTestId('background').style.backgroundImage).toEqual(`url(${props.image})`)
또한, 당신은 다른 농담을 사용할 수 있다.DOM 매처
toHaveAttribute
매처
expect(getByTestId('background')).toHaveAttribute('style',`background-image: url(${props.image})`)
리액트 테스트 라이브러리를 사용한 컴포넌트 css 테스트의 심플한 솔루션.이것은 완벽하게 작동하고 있는 나에게 도움이 된다.
test('Should attach background color if user
provide color from props', () => {
render(<ProfilePic name="Any Name" color="red" data-
testid="profile"/>);
//or can fetch the specific element from the component
const profile = screen.getByTestId('profile');
const profilePicElem = document.getElementsByClassName(
profile.className,
);
const style = window.getComputedStyle(profilePicElem[0]);
//Assertion
expect(style.backgroundColor).toBe('red');
});
언급URL : https://stackoverflow.com/questions/53119123/react-testing-library-test-styles-specifically-background-image
'programing' 카테고리의 다른 글
Go를 사용하여 JSON을 예쁘게 인쇄하려면 어떻게 해야 하나요? (0) | 2023.03.21 |
---|---|
mongoDB가 어디에 데이터를 저장하는지 어떻게 알 수 있습니까?(디폴트 /data/db!에는 없습니다). (0) | 2023.03.21 |
세미콜론을 더 예쁘게 지우는 방법? (0) | 2023.03.21 |
Angular에서 실제 오류 메시지 대신 "Http failure response for (unknown url): 0 Unknown Error"가 나타난다. (0) | 2023.03.21 |
PHP 및 jQuery를 사용하여 보안 AJAX 요청을 보내는 방법 (0) | 2023.03.21 |