inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

비동기 함수 테스트 중 특정 케이스 에러

미해결

테스트 with Jest: 제로초에게 제대로 배우기

비동기 함수 테스트 강의를 따라했을 때 제 컴파일러에서는 오류가 발생합니다. 다른 테스트 케이스들 말고 아래 두 케이스에서만요. test('okPromise 테스트', () => { const okSpy = jest.fn(okPromise); return okSpy.then((result) => { expect(result).toBe('ok'); }) }) test('noPromise 테스트', () => { const noSpy = jest.fn(noPromise); return noSpy.catch((result) => { expect(result).toBe('ok'); }) }) 각 테스트 별 에러 메세지는 다음과 같습니다. 'Mock<Promise<string>, [], any>' 형식에 'then' 속성이 없습니다.ts(2339) 'Mock<Promise<never>, [], any>' 형식에 'catch' 속성이 없습니다.ts(2339) 코드를 동일하게 작성했음에도 불구하고, 어떤 문제로 위 에러가 발생하는 걸까요?

  • supertest
  • jest
  • 소프트웨어-테스트
  • unittest
모락 댓글 1 좋아요 0 조회수 206

TS로 변경 시 "type": "module" 제거 이유가 궁금합니다.

미해결

테스트 with Jest: 제로초에게 제대로 배우기

확장자를 TS로 변경했을 때 코드에는 ESM의 import , export 를 사용했는데 왜 package.json파일의 ESM 관련 옵션인 "type": "module" 을 제거하는지 궁금합니다. GPT의 답변에 의하면 TS 파일은 컴파일 과정에서 CommonJS나 ESM이나 알맞게 변환을 하기 때문에 해당 옵션이 필요 없고, Jest와의 호환성을 위해 "type": "module" 을 제거해주는 것이고, JS파일은 기본적으로 CommonJS모듈 시스템을 사용하기 때문에 import문을 사용했으면 ESM방식으로 해석하도록 명시하기 위해서 "type": "module" 을 추가한다. 라고 설명을 해주는데 그럼 JS 파일의 경우 Jest와의 호환성을 고려하지 않는건지.. 이해가 잘 되지 않습니다. 혹시 설명을 해주실 수 있을까요?

  • supertest
  • jest
  • 소프트웨어-테스트
  • unittest
모락 댓글 2 좋아요 0 조회수 330

jest.config.js 파일 내용 다른 분들 참고

미해결

테스트 with Jest: 제로초에게 제대로 배우기

환경 : mac os 저의 경우에 npx ts-jest config:init 명령어를 통해 생성한 jest.config.js 파일의 내용이 다음과 같이 강의 영상과 달랐습니다. /** @type {import('ts-jest').JestConfigWithTsJest} **/ module.exports = { testEnvironment: "node", transform: { "^.+.tsx?$": ["ts-jest",{}], }, }; 강의 영상 내용에 맞춰서 preset: 'ts-jest' 설정을 추가해주어 Jest가 TypeScript 파일을 컴파일하고 실행할 수 있도록 해주니 잘 동작합니다.

  • supertest
  • jest
  • 소프트웨어-테스트
  • unittest
댓글 2 좋아요 0 조회수 354

강의 교안

미해결

테스트 with Jest: 제로초에게 제대로 배우기

안녕하세요 제로초님. 강의 교안이 어디있는지 모르겠습니다.

  • supertest
  • jest
  • 소프트웨어-테스트
  • unittest
gomteng03 댓글 2 좋아요 0 조회수 280

Cypress io가 유료인가요?

미해결

2시간으로 끝내는 프론트엔드 테스트 기본기

Cypress Colud Trial 13 days left라고 뜨는데 유료로 바뀌었나요?

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
ChangJun.dev 댓글 2 좋아요 0 조회수 283

테스트 자동화를 cypress cloud로 하는 이유

해결됨

2시간으로 끝내는 프론트엔드 테스트 기본기

안녕하세요, 선생님. 강의를 모두 듣고 개인 프로젝트에 적용해보고 있는 중에 궁금한 점이 생겨 질문 남깁니다. 이번 강의에 나온 cypress cloud를 사용해서 테스트 자동화를 해보았는데 문득 cypress가 아니라 cypress cloud를 사용해서 테스트 자동화를 하는 이유가 무엇인지 궁금하더라고요. https://docs.cypress.io/guides/continuous-integration/github-actions 위 문서를 찾아보니 cypress cloud는 테스트를 병렬로 진행해서 속도가 더 빠르다고 하는데 병렬 테스트를 위해 cypress cloud를 사용하는 것인지 궁금합니다. 아니면 뭔가 다른 이유가 있을까요?

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
메가 댓글 1 좋아요 0 조회수 239

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

미해결

따라하며 배우는 리액트 테스트 [2023.11 업데이트]

따라하며 배우는 리액트 테스트코드 강의에서 eslint가 적용되었다고 하는 파일자체를 받아 npm install을 헀는데, eslint가 작동되지않습니다. extension에서도 eslint를 받았고, npm install을 한 상태에서 test() let test = () => {} 와 같은 오류가 발생될 코드를 작성해도 eslint가 반응하지 못하는데 이유가 뭘까요 강의에는 설정이 적용되어있다고 하는데

  • react
  • 웹앱
  • React-Context
  • jest
  • 소프트웨어-테스트
  • eslint
tkdrnr1215 댓글 2 좋아요 0 조회수 322

jest.config.cjs로 작성했을 때 modules를 읽어올 수 없음

해결됨

2시간으로 끝내는 프론트엔드 테스트 기본기

강의 1분쯤에 jest.config.cjs로 쓰는 것과 package.json에서 작성하는 법 2가지를 알려주셨을 때 전자대로 적용해 실행하니 아래와 같은 에러가 발생했습니다! 이후에 package.json에 작성해서 실행하는 방법으로 변경하니 정상적으로 작동했는데 혹시 이 원인을 알 수 있을까요? modules를 import하지 못한 이유를 잘 모르겠습니다!

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
갈길toofar 댓글 1 좋아요 0 조회수 319

[공유] cy.visit() failed trying to load;

미해결

2시간으로 끝내는 프론트엔드 테스트 기본기

위 화면처럼 connect ECONNREFUSED::1:54382등 locahost에 접근할 수 없다고 나오면 cypress.config.ts에서 baseurl 설정해야합니다. ( https://parkparkpark.tistory.com/186) import { defineConfig } from "cypress"; export default defineConfig({ e2e: { baseUrl: "http://localhost:3000", setupNodeEvents(on, config) { // implement node event listeners here }, }, });

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
류준열 댓글 2 좋아요 4 조회수 424

Axios Mocking에 관한 질문입니다.

미해결

습관부터 바꿔주는 Node.js & Express 기초

// Axios.test.ts import axios from 'axios'; import ManagerService from "./ManagerService"; jest.mock('axios'); const mockedAxios = axios as jest.Mocked<typeof axios>; describe("Axios Test", () => { let managerService = new ManagerService(); it("should mock axios get call", async () => { mockedAxios.get.mockResolvedValue({ data: [ { corporation: "inflearn" } ], }); const test = await managerService.axiosTest("inflearn"); expect(test).toEqual([ { corporation: "inflearn" } ]); expect(mockedAxios.get).toHaveBeenCalledWith(`${process.env.SERVER_URL}/corporation/info`, { params: { corporation: "inflearn" }, }); }); }); 위와 똑같은 코드로 테스트를 진행했고, 본 코드에서는 약간의 차이만 있었습니다. 하지만 아직 왜 그렇게 되는지 알지 못하여서 강사님께 여쭤보려고 합니다. 1번 코드 ( 테스트가 잘 동작하는 코드 ) axiosTest = async (corporation: string) => { const response = await axios.get(`${process.env.SERVER_URL}/corporation/info`, { params: { corporation: corporation, }, }); if (!response) { throw new Error("값이 없음"); } return response.data; }; 2번 코드 ( 값이 없음으로 에러가 발생하는 코드 ) axiosTest = async (corporation : string) => { const site = await axios({ method: 'get', url: `${process.env.SERVER_URL}/corporation/info`, params: { corporation : corporation }, }) if(!site) { throw new Error("값이 없음"); } return site.data } 둘의 차이점에 대해서 알 수 있을까요?

  • node.js
  • express
  • jest
  • test
  • axios
  • mock
감사합니두~ 댓글 1 좋아요 0 조회수 361

안녕하세요. 질문 있습니다.

미해결

2시간으로 끝내는 프론트엔드 테스트 기본기

섹션3 recoil을 테스트하는 방법 3:50에 cy.url().should('include','/'); 를 통해서 root page로 잘 이동하는지 확인한다고 하신부분에서, '/' 는 어떤 페이지에서든 include가 되어 테스트가 통과될것 같은데 혹시 rootpage를 검증하기위한 다른 방법은 없을까요?

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
김연수 댓글 3 좋아요 2 조회수 467

공용 컴포넌트 유닛 테스트 관하여 질문이 있습니다!

해결됨

실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트

안녕하세요! 강의를 듣고 테스트 코드를 연습중에 질문이 있어서 글을 작성하게 되었습니다. 제가 테스트 코드를 작성하려는 프로젝트에서 공용 컴포넌트 중 Pagination 컴포넌트에 유닛 테스트 코드를 작성하려고 합니다. 제가 생각한 테스트 흐름은 실제 유저가 Pagination 컴포넌트의 화살표 버튼 클릭시 현재 페이지가 1이 증가하는 것처럼 테스트 코드를 구현하려고 했습니다. 하지만 Pagination 컴포넌트에는 setCurrentPage 함수를 주입 받아서 처리하기 때문에 유닛 테스트에서는 클릭으로 current page 값이 증가하는 것을 확인할 수는 없고 spy 함수를 통해 setCurrentPage가 실행되는 것까지만 확인하는게 맞는건가요?? 두서없는 글 읽어주셔서 감사합니다!

  • javascript
  • react
  • 소프트웨어-테스트
  • jest
  • @tesing-library
임성규 댓글 1 좋아요 1 조회수 376

타입스크립트 테스트코드 작성

해결됨

한 입 크기로 잘라먹는 타입스크립트(TypeScript)

안녕하세요 강의 도움 많이 받고 타입스크립트 + 리액트 조합으로 서비스 만들고 있습니다. 강의에 테스트코드 관련 내용은 없어 무관한 질문 죄송합니다 ㅠ jest로 테스트 코드를 작성하려고 하는데 설정에 무슨 오류가 있는지 도무지 테스트가 되지 않습니다.. 여러 블로그 글이랑 챗 gpt참고해서 수정해도 안되는데 혹시 타입스크립트에서 jest 쓰려면 다른 설정을 해줘야 하는건가요? 도움 주시면 감사드리겠습니다 ..

  • typescript
  • react
  • jest
syeshe 댓글 1 좋아요 0 조회수 318

TypeError: user_model_1.default.create is not a function

미해결

따라하며 배우는 TDD 개발 [2023.11 업데이트]

학습중 repository pattern을 적용하여 테스트를 적용해 보던 중 TypeError: user_model_1.default.create is not a function 라는 에러와 마주하게 되었습니다. user.repository.ts import User from "../model/user.model"; export class UserRepository { createUser = async(user) => { const newUser = await User.create({ ...user }) return newUser } findUserById = async(id:string) => { const user = await User.findById('65cba34813b2fbec74a558a8') if(!user) throw new Error('존재하지 않는 유저정보 입니다.') return user } } user.repository.test.ts import { UserRepository } from "../../app/repository/user.repository" const createMock = jest.fn() const findByIdMock = jest.fn() jest.mock("../../app/model/user.model", () => { return { User: jest.fn(() => { return { create:createMock, findById:findByIdMock } }) } }) describe('user repository Create', () => { let sut:UserRepository; const newUser = { id:"abcdefrwgsf123123", name:"test name", email:"test@nanana.com" } beforeEach(() => { sut = new UserRepository() }) afterEach(() => { jest.clearAllMocks() }) it('create api', async () => { createMock.mockReturnValueOnce(newUser) const actual = await sut.createUser({name:newUser.name, email:newUser.email}) expect(createMock).toHaveBeenCalledTimes(1) expect(actual).toStrictEqual(newUser) expect(createMock).toHaveBeenCalledWith({name:newUser.name, email:newUser.email}) }) }) jest실행시 create api의 createMock.mockReturnValue() 까지는 실행이되지만 await sut.createUser() 부분에서 에러가 나는것으로 확인되었습니다.

  • node.js
  • mongodb
  • express
  • supertest
  • tdd
  • jest
  • mongoose
  • 소프트웨어-테스트
양진영 댓글 1 좋아요 0 조회수 284

jest 테스트코드 작성을 위한 사전세팅 중 문제가 발생했습니다.

미해결

2시간으로 끝내는 프론트엔드 테스트 기본기

안녕하세요 jest 테스트코드 작성을 위한 사전세팅중 위와 같이 코드를 작성 후 실행하였더니 이러한 에러가 발생하였습니다. jest를 사용하며 import라는 구문을 사용하지 못한다는 에러같은데 해결 방법이 있을까요??

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
swoo1429 댓글 3 좋아요 0 조회수 844

테스트 실행이 안되는 문제..

미해결

2시간으로 끝내는 프론트엔드 테스트 기본기

공유해주신 프로젝트 clone해서 수정 없이 npm run unit-test 명령어 실행 시, 아래 이미지와 같이 export().toBeInTheDocument() 를 찾지 못해 진도를 나가지 못하고 있습니다.. 혹시 해결방안을 알려주실 수 있으실까요? 구글링 검색 시, import "@testing-library/jest-dom"; 을 테스트 파일 가장 상위에 두라고 하는데 이미 되어 있고 다른 해결책들도 실행해보았지만 해결하지 못했습니다. 노드 버전은 20.10.0 , 18.19.0 , 18.14.0 에서 실행했을 때, 모두 실패했습니다..

  • react
  • jest
  • 소프트웨어-테스트
  • Cypress
  • storybook
  • chatgpt
mktae 댓글 1 좋아요 0 조회수 651

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

해결됨

따라하며 배우는 리액트 테스트 [2023.11 업데이트]

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 선생님 안녕하세요! 강의 너무 잘 듣고 있습니다! 감사해요 오류를 잡으려고 노력해봤는데도 잘 안돼서 질문 남깁니다 calculate.test.js파일의 toHaveTextContent()부분에서 모두 오류가 나고 있습니다. 선생님이 주신 소스코드와 제 코드를 모두 비교해봤는데 다 똑같더라구요. 제가 인지하지 못한 오류가 있는지 한 번 봐주실 수 있으실까요? 부탁드립니다ㅜ 오류 부분 calculate.test.js import { render, screen } from "../../../test-utils"; import userEvent from "@testing-library/user-event"; import Type from "../Type"; import OrderPage from "../OrderPage"; test("update products total when products change", async () => { render(<Type orderType="products" />); const productsTotal = screen.getByText("상품 총 가격: ", { exact: false }); expect(productsTotal).toHaveTextContent("0"); // 아메리카 여행 상품 한개 올리기 const americaInput = await screen.findByRole("spinbutton", { name: "America", }); userEvent.clear(americaInput); userEvent.type(americaInput, "1"); // 이 상품을 하나 산다는 뜻 expect(americaInput).toHaveTextContent("1000"); }); - 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; orderContext.js import { createContext, useState, useMemo, useEffect } from "react"; export const OrderContext = createContext(); const pricePerItem = { products: 1000, options: 500, }; function calculateSubtotal(orderType, orderCounts) { let optionCount = 0; for (const count of orderCounts[orderType].values()) { optionCount += count; } return optionCount * pricePerItem[orderType]; } export function OrderContextProvider(props) { const [orderCounts, setOrderCounts] = useState({ products: new Map(), options: new Map(), }); const [totals, setTotals] = useState({ products: 0, options: 0, total: 0, }); useEffect(() => { const productsTotal = calculateSubtotal("products", orderCounts); const optionsTotal = calculateSubtotal("options", orderCounts); const total = productsTotal + optionsTotal; setTotals({ products: productsTotal, options: optionsTotal, total, }); }, [orderCounts]); const value = useMemo(() => { function updateItemCount(itemName, newItemCount, orderType) { const newOrderCounts = { ...orderCounts }; const orderCountsMap = orderCounts[orderType]; orderCountsMap.set(itemName, parseInt(newItemCount)); setOrderCounts(newOrderCounts); } return [{ ...orderCounts, totals }, updateItemCount]; }, [orderCounts, totals]); return <OrderContext.Provider value={value} {...props} />; }

  • React-Context
  • 웹앱
  • react
  • jest
sos 댓글 2 좋아요 0 조회수 664

es6 jest 미지원 오류 문의

미해결

따라하며 배우는 리액트 테스트 [2023.11 업데이트]

안녕하세요 강의 잘 듣고 있습니다. 강의를 듣다가 axios를 설치하고 import 하는 과정에서 다음과 같은 문제가 발생했습니다. 구글링을 해보니 jest가 es6를 지원하지 않아서 발생하는 문제라고 하던데 구글링해서 찾아본 방법들은 해결이 되지 않아 문의 드립니다. FAIL src/pages/OrderPage/tests/Type.test.js ● Test suite failed to run Jest encountered an unexpected token Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. By default "node_modules" folder is ignored by transformers. Here's what you can do: • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it. • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/configuration For information about custom transformations, see: https://jestjs.io/docs/code-transformation Details: C:\Users\multicampus\Desktop\projects\react-test-app\react-shop-test\node_modules\axios\index.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js'; ^^^^^^ SyntaxError: Cannot use import statement outside a module > 1 | import axios from 'axios'; | ^ 2 | import React, { useEffect, useState } from 'react' 3 | import { Products } from './Products'; 4 | at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14) at Object.<anonymous> (src/pages/OrderPage/Type.js:1:1) at Object.<anonymous> (src/pages/OrderPage/tests/Type.test.js:2:1) at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13) at runJest (node_modules/@jest/core/build/runJest.js:404:19)

  • 웹앱
  • React-Context
  • react
  • jest
k915k1004 댓글 1 좋아요 0 조회수 875

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

미해결

따라하며 배우는 리액트 테스트 [2023.11 업데이트]

혹시나 에러가 나신다면, package.json폴더에 "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"", "eject": "react-scripts eject" }, 로 변경 후 test를 종료 후 재 실행시키면 됩니다. 방법은 test에서 직접 스크립트 수정하거나 jest.config.js파일을 만들어 moduleNameMapper을 사용하시면 됩니다! 참고 https://stackoverflow.com/questions/73958968/cannot-use-import-statement-outside-a-module-with-axios https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring

  • jest
  • 웹앱
  • react
  • React-Context
손서연 댓글 5 좋아요 4 조회수 2255

인기 태그

인프런 TOP Writers

주간 인기글