묻고 답해요
130만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결습관부터 바꿔주는 Node.js & Express 기초
Axios Mocking에 관한 질문입니다.
// 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 } 둘의 차이점에 대해서 알 수 있을까요?
-
해결됨실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트
공용 컴포넌트 유닛 테스트 관하여 질문이 있습니다!
안녕하세요! 강의를 듣고 테스트 코드를 연습중에 질문이 있어서 글을 작성하게 되었습니다.제가 테스트 코드를 작성하려는 프로젝트에서 공용 컴포넌트 중 Pagination 컴포넌트에 유닛 테스트 코드를 작성하려고 합니다.제가 생각한 테스트 흐름은 실제 유저가 Pagination 컴포넌트의 화살표 버튼 클릭시 현재 페이지가 1이 증가하는 것처럼 테스트 코드를 구현하려고 했습니다.하지만 Pagination 컴포넌트에는 setCurrentPage 함수를 주입 받아서 처리하기 때문에 유닛 테스트에서는 클릭으로 current page 값이 증가하는 것을 확인할 수는 없고 spy 함수를 통해 setCurrentPage가 실행되는 것까지만 확인하는게 맞는건가요?? 두서없는 글 읽어주셔서 감사합니다!
-
해결됨한 입 크기로 잘라먹는 타입스크립트(TypeScript)
타입스크립트 테스트코드 작성
안녕하세요 강의 도움 많이 받고 타입스크립트 + 리액트 조합으로 서비스 만들고 있습니다. 강의에 테스트코드 관련 내용은 없어 무관한 질문 죄송합니다 ㅠjest로 테스트 코드를 작성하려고 하는데 설정에 무슨 오류가 있는지 도무지 테스트가 되지 않습니다.. 여러 블로그 글이랑 챗 gpt참고해서 수정해도 안되는데 혹시 타입스크립트에서 jest 쓰려면 다른 설정을 해줘야 하는건가요?도움 주시면 감사드리겠습니다 ..
-
해결됨따라하며 배우는 리액트 테스트 [2023.11 업데이트]
toHaveTextContent 에서 에러가 자꾸 나는데 아무리 찾아도 잘 모르겠습니다.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 선생님 안녕하세요! 강의 너무 잘 듣고 있습니다! 감사해요오류를 잡으려고 노력해봤는데도 잘 안돼서 질문 남깁니다calculate.test.js파일의 toHaveTextContent()부분에서 모두 오류가 나고 있습니다. 선생님이 주신 소스코드와 제 코드를 모두 비교해봤는데 다 똑같더라구요. 제가 인지하지 못한 오류가 있는지 한 번 봐주실 수 있으실까요? 부탁드립니다ㅜ오류 부분calculate.test.jsimport { 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.jsimport 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.jsimport { 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} />; }
-
미해결따라하며 배우는 리액트 테스트 [2023.11 업데이트]
es6 jest 미지원 오류 문의
안녕하세요 강의 잘 듣고 있습니다. 강의를 듣다가 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)
-
미해결따라하며 배우는 리액트 테스트 [2023.11 업데이트]
axios 1.1.2 버전 issue ( SyntaxError: Cannot use import statement outside a module)
혹시나 에러가 나신다면, 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-axioshttps://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
npm run test:e2e
수강생분들의 질문을 기다립니다! - 에러에 해당하는 질문은 "에러가 발생한 상황에 대한 충분한 설명", "에러 메세지", "에러가 난 코드 스크린샷"을 함께 첨부해주세요. - 언어에 해당하는 질문은 구글링 및 서치 후에 구체적으로 질문해주시면 좋습니다. - 간단한 진로 및 방향성에 대한 질문은 메일로 보내주세요.- 패키지 버전 관리은 실무 환경과 트랜드에 맞추어 강의를 업데이트 하고 있습니다. 강의를 그대로 따라갔는데 에러가 발생한다면 패키지 버전을 강의에서 사용하는 버전과 동일하게 맞춰주세요!- 강의 노트, QA 목록, 공지 사항을 먼저 확인해주세요.- 논리적이고 구체적인 질문은 학습 효과를 올립니다 :) 강의를 보시다가 혹시나 npm run test:e2e 를 돌려봤는데 npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! amamov.com@1.8.0 test:e2e: jest --config ./test/jest-e2e.jsonnpm ERR! Exit status 1npm ERR! npm ERR! Failed at the amamov.com@1.8.0 test:e2e script.npm ERR! This is probably not a problem with npm. There is likely additional logging output above.npm ERR! A complete log of this run can be found in:npm ERR! /Users/anhyeongjun/.npm/_logs/2022-10-13T13_02_17_408Z-debug.log이런 error를 맞이하신다면 { "moduleFileExtensions": ["js", "json", "ts"], "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "moduleNameMapper": { "^src/(.*)$": "<rootDir>/../src/$1" } } moduleNameMapper이부분이 들어가있는지 확인하신 후 없으면 넣어주면 test가 성공적으로 진행될 수 있습니다. 다만 윤상석 선생님 추가해서 test를 돌려보면 Jest did not exit one second after the test run has completed.This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue. 이런 오류가 나는데 이유가 무엇일까요?
-
미해결[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
mockReturnValue 질문
db 에러가 발생하면 next(error) 호출부분 질문드립니다. User.findOne부분을 mocking해서 reject를 반환하게 해서 에러처리하는 부분을 테스트하는것으로 이해를 하고 있습니다. user 컨트롤러에서 findOne이 reject를 반환하니, User.findOne({where: {id : req.user.id}}); 이 controller 코드에서 req.user.id가 필요없다고 생각하여 req 객체를 빈 객체로 만들고 테스트를 진행하니, req.user가 undefined라는 에러가 나오며 테스트가 실패하였습니다. 이 부분을 혹시 User.findOne 부분을 mocking 하더라도 findOne 함수 실행을 끝까지 하고 reject를 반환한다고 이해해도 되는것일까요? test("db 에러 발생하면 next(error)호출", async () => { const error = "error for test"; User.findOne.mockReturnValue(Promise.reject(error)); await addFollowing(req, res, next); // req = {}로 넣어도 되지 않을까? expect(next).toBeCalledWith(error); }); ////////////////////////////// exports.addFollowing = async (req, res, next) => { try { //질문대상인 User.findOne const user = await User.findOne({ where: { id: req.user.id } }); // req.user가 :id 사람을 팔로잉 한다. if (user) { await user.addFollowing(parseInt(req.params.id, 10)); res.send("success"); } else { res.status(404).send("no user"); } } catch (error) { console.error(error); next(error); } };
-
미해결[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
Post controller test 질문입니다.
exports.createPost = async (req, res, next) => { try { const post = await Post.create({ content: req.body.content, img: req.body.url, UserId: req.user.id, }); /////////////////// const hashtags = req.body.content.match(/#[^\s#]*/g); if (hashtags) { const result = await Promise.all( hashtags.map((tag) => { return Hashtag.findOrCreate({ where: { title: tag.slice(1).toLowerCase() }, }); }) ); ///////////// await post.addHashtags(result.map((r) => r[0])); } res.redirect("/"); } catch (error) { console.error(error); next(error); } }; 위 코드는 제가 post 라우터 unit test를 하기위해서 post를 생성하는 미들웨어를 controller로 분리한 코드입니다. 저기서 슬래시로 감싸진 부분을 어떻게 테스트를 해야할지 모르겠어서 질문드립니다. 또한 jest.mock("../models/post"); jest.mock("../models/hashtag"); const Post = require("../models/post"); const Hashtag = require("../models/hashtag"); 로 모델을 mocking하고 시작하였는데 User.hasMany called with something that's not a subclass of Sequelize.Model 라는 테스트 에러가 나와서, 왜 user model에 대한 부분이 에러로 나오는지 이해가 가지 않아서 질문드립니다. 여기 저기를 주석 처리한 결과 위 4줄의 코드가 에러의 원인인 것 같아 질문드립니다.
-
미해결따라하며 배우는 리액트 테스트 [2023.11 업데이트]
jest와 @testing-library/jest-dom
너무 기초적인 질문인 것 같아 걱정이지만 질문드립니다~! 1. jest와 @testing-library/jest-dom는 어떤 차이가 있고 각각의 역할이 궁금합니다. 2. @testing-library와 함께 사용하는 이유와 jest만 따로 사용하지는 않는 이유가 궁금합니다.
-
미해결[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
Jest 테스트 코드 작성 관련 질문
타입스크립트로 Jest 테스트 코드를 작성해보고 있는데요. 유닛테스트를 작성하여, 직접 작성한 미들웨어에서 next() 함수가 호출되는지 확인해보려고 합니다. class-validator로 req.body가 number인지 검증하는 미들웨어이고, 테스트코드는 다음과 같습니다. import 'reflect-metadata'; import { CreateCheckInDto } from '../check-in/create-check-in.dto'; import { validation } from './validation.middleware'; describe('validation middleware', () => { it('simple test', () => { const req: any = { body: { cardId: '22' }, }; const res: any = {}; const next = jest.fn(); validation(CreateCheckInDto)(req, res, next); expect(next).toBeCalledTimes(1); }); }); 미들웨어 코드는 다음과 같습니다(class validator로 req.body를 검증하는 코드입니다). import { plainToInstance } from 'class-transformer'; import { validate, ValidationError } from 'class-validator'; import { NextFunction, Request, Response, RequestHandler } from 'express'; export function validation(type: any): RequestHandler { return (req: Request, res: Response, next: NextFunction) => { validate(plainToInstance(type, req.body)).then( (errors: ValidationError[]) => { if (errors.length > 0) { res.redirect('redirect'); } else { console.log('nextttttttttttttttt'); next(); } }, ); }; } console.log('nextttttttttttttttt'); 이게 콘솔로그로 찍히는 걸보면 next()부분까지 도달하는 것 같은데 테스트 결과는 기대와 다르게 아래와 같습니다. console.log nextttttttttttttttt at src/middleware/validation.middleware.ts:12:19 FAIL src/middleware/validation.middleware.spec.ts validation middleware ✕ simple test (22 ms) ● validation middleware › simple test expect(jest.fn()).toBeCalledTimes(expected) Expected number of calls: 1 Received number of calls: 0 13 | validation(CreateCheckInDto)(req, res, next); 14 | > 15 | expect(next).toBeCalledTimes(1); | ^ 16 | }); 17 | }); 18 | at Object.<anonymous> (src/middleware/validation.middleware.spec.ts:15:18) 왜 received number of calls가 0이 나오는지 실마리를 찾지 못하여 질문으로 올립니다. 원인해결을 위한 키워드라도 실마리를 주신다면 정말 감사하겠습니다!
-
미해결따라하며 배우는 도커와 CI환경 [2023.11 업데이트]
fullstack 빌드시 아래와 같이 jest 에러가 나는데 혹시 해결방법이 있을까요
(사진)
-
미해결[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
테스트 파트의 user.test.js 오류가 나는데 도저히 이유를 모르겠습니다.
jest.mock("../models/user"); // require을 통해 가지고 오는 객체들을 jest.mock으로 복사한다. const User = require("../models/user"); const {addFollowing} = require("./user"); describe("addFollowing", ()=>{ const req = { user : {id : 1}, params : {id : 2}, }; const res = { status : jest.fn(()=>res), send : jest.fn(), }; const next = jest.fn(); const console = { error : jest.fn(), }; test("사용자를 찾아 팔로잉을 추가하고 success를 응답해야 함", async()=>{ User.findOne.mockReturnValue(Promise.resolve({ addFollowing(id) { return Promise.resolve(true); } })); await addFollowing(req,res,next); expect(res.send).toBeCalledWith('success'); }); test("사용자를 못 찾으면 res.status(404).send(no user)를 호출해야 함", async ()=>{ User.findOne.mockReturnValue(Promise.resolve(null)); await addFollowing(req.res,next); expect(res.status).toBeCalledWith(404); expect(res.send).toBeCalledWith('no user'); }); test("DB에서 에러가 발생하면 next(error) 호출한다.", async()=>{ const err = "테스트용 에러"; User.findOne.mockReturnValue(Promise.reject(err)); await addFollowing(req,res,next); expect(console.error).toBeCalledWith(err); expect(next).toBeCalledWith(err); }); } 위의 코드는 user.test.js 코드입니다. user.js 코드는 깃헙에 올려주신 코드를 복사했습니다. console.error()를 테스트 하기 위해 가짜객체도 만들었습니다. test("사용자를 못 찾으면 res.status(404).send(no user)를 호출해야 함" 이 부분에서 Promise.resolve(null)을 했는데 테스트가 왜 try{} 부분이 아니라 catch{} 부분으로 가는 걸까요?? catch{} 부분에서 console.error(err) 부분도 처리가 안되고 , next(err) 부분도 테스트가 안됩니다. next(err)에서 next가 함수가 아니라고 타입 에러가 뜨는데 왜일까요? 콘솔창의 출력은 다음과 같습니다. 혹시나 하는 마음에 user.js 코드도 아래에 올리겠습니다. const User = require('../models/user'); exports.addFollowing = async (req, res, next) => { try { const user = await User.findOne({ where: { id: req.user.id } }); if (user) { await user.addFollowing(parseInt(req.params.id, 10)); res.send('success'); } else { res.status(404).send('no user'); } } catch (err) { console.error(err); next(err); } }; ㅎㅎㅎ ㅎㅎㅎ
-
해결됨따라하며 배우는 TDD 개발 [2023.11 업데이트]
mysql import 에러
mysql을 사용하여 진행 중인 프로젝트가 있는데 tdd를 적용해보려고 합니다. controllers/subscription.js const db = require('../routes/database.js'); exports.subscribeCalendar=()=>{}; 컨트롤러 코드는 위와 같고 test/unit/subscription.test.js const subscriptionController=require("../../controllers/subscription") describe("캘린더 구독",()=>{ test("subscribeCalendar 함수가 있을 겁니다.",()=>{ // subscriptionController.subscribeCalendar의 타입은 함수다. expect(typeof subscriptionController.subscribeCalendar).toBe("function") }) }) 테스트 코드는 위와 같은데 컨트롤러에서 db를 임포트 하기 전에는 에러가 안 떴는데 임포트 한 후에 테스트는 통과하지만 아래와 같은 에러 메시지가 뜹니다. 검색해보니 단위테스트 할 때는 db 관련 코드는 넣지 말라고 하는데 그 원인일까요? ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. 이미 mysql로 진행 중이라 몽구스로 변경하기가 어려운데 에러메시지 무시하면 될까요..?