inflearn logo
강의

講義

知識共有

フォローして学ぶリアクトテスト [2023.11アップデート]

商品価格、オプション価格を加算した合計金額の算出

toHaveTextContent 에서 에러가 자꾸 나는데 아무리 찾아도 잘 모르겠습니다.

解決済みの質問

610

sos

投稿した質問数 3

0

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!
- 먼저 유사한 질문이 있었는지 검색해보세요.
- 서로 예의를 지키며 존중하는 문화를 만들어가요.
- 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.

 

선생님 안녕하세요! 강의 너무 잘 듣고 있습니다! 감사해요

오류를 잡으려고 노력해봤는데도 잘 안돼서 질문 남깁니다

calculate.test.js파일의 toHaveTextContent()부분에서 모두 오류가 나고 있습니다. 선생님이 주신 소스코드와 제 코드를 모두 비교해봤는데 다 똑같더라구요. 제가 인지하지 못한 오류가 있는지 한 번 봐주실 수 있으실까요? 부탁드립니다ㅜ

질문.jpg

- Type.js

import React, { useContext, useEffect, useState } from "react";
import Products from "./Products";
import axios from "axios";
import ErrorBanner from "../../components/ErrorBanner";
import Options from "./Options";
import { OrderContext } from "../../contexts/OrderContext";

const Type = ({ orderType }) => {
  const [items, setItems] = useState([]);
  const [error, setError] = useState(false);
  const [orderDatas, updateItemCount] = useContext(OrderContext);
  // OrderContext.js의  return [{ ...orderCounts, totals }, updateItemCount]; 을 구조분해
  useEffect(() => {
    loadItems(orderType);
  }, [orderType]);
  const loadItems = async (orderType) => {
    try {
      let response = await axios.get(`http://localhost:5000/${orderType}`);
      setItems(response.data);
    } catch (error) {
      setError(true);
    }
  };
  if (error) {
    return <ErrorBanner message="에러가 발생했습니다" />;
  }
  const ItemComonents = orderType === "products" ? Products : Options;
  const optionItems = items.map((item) => (
    <ItemComonents
      style={{ border: "2px solid red" }}
      key={item.name}
      name={item.name}
      imagePath={item.imagePath}
      updateItemCount={(itemName, newItemCount) =>
        updateItemCount(itemName, newItemCount, orderType)
      }
    />
  ));
  let orderTypeKorean = orderType === "products" ? "상품" : "옵션";

  return (
    <div>
      <h2>주문종류</h2>
      <p>하나의 가격</p>
      <p>
        {orderTypeKorean} 총 가격: {orderDatas.totals[orderType]}
      </p>
      <div
        style={{
          display: "flex",
          flexDirection: orderType === "options" && "column", //
        }}
      >
        {optionItems}
      </div>
    </div>
  );
};

export default Type;

 

React-Context 웹앱 react jest

回答 2

1

sos

이전에 해결하지 못한 문제였지만, 복습을 하면서 해결했습니다.

혹시 저와 같은 오류를 겪으신 분들께 도움이 될까 싶어 해결 방법을 남겨봅니다.

toHaveTextContent의 오류라 생각한 문제는 사실 userEvent가 제대로 작동하지 않아 발생한 문제였습니다.

공식문서에 보면, userEvent.setup()을 호출해 사용하는 방법을 추천하고 있습니다. 저는 이렇게 불러옴으로 문제를 해결했습니다.

We recommend invoking userEvent.setup() before the component is rendered.

https://testing-library.com/docs/user-event/intro/

//package.json 
"@testing-library/user-event": "^14.4.3"
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { OrderContextProvider } from "../../../contexts/OrderContext";
import Type from "../Type";

test("update product's total when products change", async () => {
  ✅ const event = userEvent.setup();
  render(<Type orderType="products" />, { wrapper: OrderContextProvider });

  const productsTotal = screen.getByText("총 가격:", { exact: false });
  expect(productsTotal).toHaveTextContent("0");

  //아메리카 여행 상품 한 개 올리기
  const americaInput = await screen.findByRole("spinbutton", {
    name: "America",
  });

✅  await event.clear(americaInput);
✅  await event.type(americaInput, "1");
  expect(productsTotal).toHaveTextContent("1000");
});

0

John Ahn

안녕하세요!

현재 가격 계산하는 부분의 기능에 오타가 있을 것 같은데

깃허브 저장소에 프로젝트를 올리셨다면

깃허브 저장소 주소 주시면

직접 한번 해보겠습니다!

감사합니다.

제공해주신 코드를 vscode에서 켜도 eslint가 안됩니다.

0

278

2

ERROR

0

209

1

테스트 시간을 단축할 수 있는 방법에 대하여 문의드립니다.

0

360

1

useState 배열값 변경의 경우 테스트 멈춤

0

411

1

test was not wrapped in act관련 질문

0

290

2

안녕하세요! 로딩 상태 테스트에 관련된 질문입니다.

0

394

1

강의 관련 내용 github 업로드 질문

0

307

1

이미지가 안보인다 하셔서 다시 질문드립니다.

0

414

2

Test Fail이 발생합니다 ㅠㅠ

0

356

1

스타일 컴포넌트 테스트 방법

0

438

1

msw 에러

0

632

1

toHaveTextContent 에러

0

442

1

msw안돼는사람

0

579

1

This could be because the text is broken up by multiple elements. 에러

0

1716

2

Type.test.js파일에 궁금한점이 생겼습니다

0

351

1

28강 수강 중 JSX 작성 방법에 대해 궁금해져서 질문 남깁니다!

0

398

1

aria-*

0

438

1

This XML file does not appear to have any style information associated with it. The document tree is shown below. 에러

1

14089

1

컴포넌트 props내려줄때 코드는 어떻게 해야하나요

0

248

0

es6 jest 미지원 오류 문의

0

857

1

test 여러 개 실행 - fail 발생

0

292

1

useMemo

0

282

1

axios 1.1.2 버전 issue ( SyntaxError: Cannot use import statement outside a module)

4

2224

5

2가지 질문사항입니다!

0

310

2