묻고 답해요
131만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결따라하며 배우는 TDD 개발 [2023.11 업데이트]
Postman 사용방법에 대해서
안녕하세요 Postman을 윈도우에서 깔아서 쓰려고 하는데 자꾸만 셋업로그가 잘못되었다고 에러가 뜹니다. 다시 시도해 봐야 하나요? 아니면 postman을 launch부터 하고 나서 깔아야 하나요? 참고로 postman을 launch하고 나서 또 다시 다운로드 시도해봤습니다.
-
미해결따라하며 배우는 TDD 개발 [2023.11 업데이트]
jest.fn() 을 할당할때 타입스크립트에서 에러가 발생합니다.
Typescript를 쓰면서 공부중입니다. productModel.create = jest.fn();위 코드를 할당할 때Cannot assign to 'findByUsername' because it is a read-only property.라는 컴파일 에러가 발생합니다...타입스크립트에서는 어떻게 할당하면 될까요 ?
-
미해결따라하며 배우는 TDD 개발 [2023.11 업데이트]
라우터를 돌릴 때
안녕하세요. 어제 알려주신 대로 제어판에서 다시 편집하고 npm run start까지 돌리는 것 까지는 잘 되었습니다. 근데 문제는 chrome에 localhost:5000을 쳤을 때는 잘 나왔지만 localhost:5000/api/products라고 칠 때는이렇게 뜹니다.이거는 단순한 코딩 문제인가요? 아니면 제가 잘 못따라 오고 있는건가요?그리고 MongoDB 새로 가입했을 때 제가 뭔가 실수한 거 같은데, MongoDB 쪽 스킵하고 Jest쪽만 들어도 상관없나요? 아니면 MongoDB도 순차적으로 들어야 하나요?
-
해결됨따라하며 배우는 TDD 개발 [2023.11 업데이트]
npm run start를 실행할 때 부터가 이상합니다.
안녕하세요 방금 말씀드렸다시피, 설치하는 거까지는 기기가 다른 것 제외하고는 별 다른 이상이 없었지만, npm run start를 실행할 때 부터가이렇게 뜹니다. 이럴 경우에는 무슨 문제인가요? 그리고 기기를 아예 바꿔야 하나요?
-
미해결따라하며 배우는 TDD 개발 [2023.11 업데이트]
node.js에 대한 이상점
안녕하세요. 어제 강의에서 알려주신대로 node.js를 설치하고 npm init, npm install express mongoose --save, npm install jest supertest node-mocks-http --save-dev까지 설치해서 실행까지 했는데, 문제는 테스트를 실행할 때, 버전이 맞지 않는다고 테스크 결과 자체가 뜨지 않는다는 겁니다. 제가 현재 윈도우를 쓰고 있는데 강의하고 있는 컴터는 맥북이라 달라서 그런지 조금 헷갈립니다. 기존에 작업했던거 전부 삭제하고 다시 깔아야 하낭요? 일단 제가 node.js를 깔았을때 node_modules가 폴더 형식으로 뜨고, package.json은 빨간 문양이 뜹니다.
-
해결됨따라하며 배우는 리액트 테스트 [2023.11 업데이트]
This could be because the text is broken up by multiple elements. 에러
선생님 안녕하세요아무리 봐도 오류 이유를 모르겠어서 질문드립니다.제 오류는 아래와 같습니다. (코드상 에러난 부분 ✅ 했습니다)> TestingLibraryElementError: Unable to find an element with the text: /loading/i. 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. // CompletePage.js import axios from "axios"; import React, { useEffect, useContext, useState } from "react"; import ErrorBanner from "../../components/ErrorBanner"; import { OrderContext } from "../../contexts/OrderContext"; function CompletePage({ setStep }) { const [OrderDatas, , resetOrderDatas] = useContext(OrderContext); const [orderHistory, setOrderHistory] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); useEffect(() => { orderCompleted(OrderDatas); }, [OrderDatas]); const orderCompleted = async (OrderDatas) => { try { let response = await axios.post( "http://localhost:5001/order", OrderDatas ); setOrderHistory(response.data); setLoading(false); } catch (error) { setError(true); } }; if (error) { return <ErrorBanner message="에러가 발생했습니다." />; } const orderTable = orderHistory.map((item) => ( <tr key={item.orderNumber}> <td>{item.orderNumber}</td> <td>{item.price}</td> </tr> )); const handleClick = () => { resetOrderDatas(); setStep(0); }; if (loading) { return <div>loading</div>; ✅ } else { return ( <div style={{ textAlign: "center" }}> <h2>주문이 성공했습니다.</h2> <h3>지금까지 모든 주문</h3> <table style={{ margin: "auto" }}> <thead> <tr> <th>주문 번호</th> <th>주문 가격</th> </tr> </thead> <tbody>{orderTable}</tbody> </table> <button onClick={handleClick}>첫페이지로</button> </div> ); } } export default CompletePage; //App.test.js import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import App from "./App"; test("From order to order completion", async () => { render(<App />); const event = userEvent.setup(); const americaInput = await screen.findByRole("spinbutton", { name: "America", }); await event.clear(americaInput); await event.type(americaInput, "2"); // England 여행 상품 3개 추가합니다. const englandInput = await screen.findByRole("spinbutton", { name: "England", }); await event.clear(englandInput); await event.type(englandInput, "3"); // insurance 옵션체크 const insuranceCheckbox = await screen.findByRole("checkbox", { name: "Insurance", }); await event.click(insuranceCheckbox); //모든 주문을 한 이후 주문 버튼 클릭! const orderButton = screen.getByRole("button", { name: "주문", }); await event.click(orderButton); ////////// 주문확인페이지 /////// const summaryHeading = screen.getByRole("heading", { name: "주문 확인" }); expect(summaryHeading).toBeInTheDocument(); const productHeading = screen.getByRole("heading", { name: "여행 상품: 5000", }); expect(productHeading).toBeInTheDocument(); const optionsHeading = screen.getByRole("heading", { name: "옵션: 500", }); expect(optionsHeading).toBeInTheDocument(); expect(screen.getByText("2 America")).toBeInTheDocument(); expect(screen.getByText("3 England")).toBeInTheDocument(); expect(screen.getByText("Insurance")).toBeInTheDocument(); const confirmCheckbox = screen.getByRole("checkbox", { name: "주문하려는것을 확인 하셨나요?", }); await event.click(confirmCheckbox); const confirmOrderButton = screen.getByRole("button", { name: "주문 확인", }); await event.click(confirmOrderButton); //// 주문 완료 //// const loading = screen.getByText(/loading/i); ✅ expect(loading).toBeInTheDocument(); const completeHeader = await screen.findByRole("heading", { name: "주문이 성공했습니다.", }); expect(completeHeader).toBeInTheDocument(); const loadingDisappeared = screen.queryByText("loading"); expect(loadingDisappeared).not.toBeInTheDocument(); const firstPageButton = screen.getByRole("button", { name: "첫페이지로", }); event.click(firstPageButton); const productsTotal = screen.getByText("상품 총 가격: 0"); expect(productsTotal).toBeInTheDocument(); const optionsTotal = screen.getByText("옵션 총 가격: 0"); expect(optionsTotal).toBeInTheDocument(); await waitFor(() => { screen.getByRole("spinbutton", { name: "America" }); }); }); 제가 에러를 이해한 바로는 return 문이 여러 경우로 나뉘어서 그렇다고 생각했습니다. 제대로 이해한게 맞을까요..?( This could be because the text is broken up by multiple elements.)실제로 아래 else return문에 loading을 넣어주니 해결이 되긴 했습니다. 하지만 아래 ✅와 같이 작성해주면 에러가 뜨네요..왜 이러는건지 혹시 아실까요? ㅠㅠif (loading) { return <div>loading</div>; ✅ } else { return ( <div style={{ textAlign: "center" }}> <h2>주문이 성공했습니다.</h2> <h3>지금까지 모든 주문</h3> <table style={{ margin: "auto" }}> <thead> <tr> <th>주문 번호</th> <th>주문 가격</th> </tr> </thead> <tbody>{orderTable}</tbody> </table> <button onClick={handleClick}>첫페이지로</button> </div> ); }선생님 코드를 보고 복붙했는데도 해결이 안되네요.ㅜ
-
해결됨따라하며 배우는 리액트 테스트 [2023.11 업데이트]
Type.test.js파일에 궁금한점이 생겼습니다
강사님 안녕하세요 ~~ 늘 잘 듣고 있습니다.복습을 하다 궁금한점이 생겼는데요!Type.test.js에서 Products컴포넌트의 img태그를 변수 productImages로 집어주신걸 보았습니다. 근데 img태그는 Type.js가 아닌 Products.js에 있는건데,그렇담 Products.test.js 파일을 따로만들어 테스트를 해야하는것이 아닌가 하는 궁금증이 생겼습니다.그냥 Type페이지에 Products 컴포넌트가 들어있기 때문에 Type.test.js에 사용한건가요?test("displays product images from server", async () => { render(<Type orderType="products" />); const productImages = await screen.findAllByRole("img", { name: /product$/i, }); expect(productImages).toHaveLength(2); const altText = productImages.map((element) => element.alt); expect(altText).toEqual(["America product", "England product"]); });
-
미해결따라하며 배우는 TDD 개발 [2023.11 업데이트]
nodemocks 오류나니까 뺴고 설치하셔요
npm i jest supertest --save-devnpm install --save-dev node-mocks-httphttps://www.npmjs.com/package/node-mocks-http
-
해결됨따라하며 배우는 리액트 테스트 [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줄의 코드가 에러의 원인인 것 같아 질문드립니다.
-
미해결Vue.js 끝장내기 - 실무에 필요한 모든 것
실습 답안 링크
Jest 실습 답안 Sign up 테스트코드 실습 답안이 없습니당.. 혹시 어디서 볼 수 있는지 알수있을까용
-
미해결따라하며 배우는 리액트 테스트 [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로 진행 중이라 몽구스로 변경하기가 어려운데 에러메시지 무시하면 될까요..?