programing

리액트 테스트 라이브러리:테스트 스타일(특히 배경 이미지)

javamemo 2023. 3. 21. 21:24
반응형

리액트 테스트 라이브러리:테스트 스타일(특히 배경 이미지)

저는 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-testidparameter를 사용합니다(<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

반응형