비동기 함수 테스트 강의를 따라했을 때 제 컴파일러에서는 오류가 발생합니다. 다른 테스트 케이스들 말고 아래 두 케이스에서만요. 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) 코드를 동일하게 작성했음에도 불구하고, 어떤 문제로 위 에러가 발생하는 걸까요?
확장자를 TS로 변경했을 때 코드에는 ESM의 import , export 를 사용했는데 왜 package.json파일의 ESM 관련 옵션인 "type": "module" 을 제거하는지 궁금합니다. GPT의 답변에 의하면 TS 파일은 컴파일 과정에서 CommonJS나 ESM이나 알맞게 변환을 하기 때문에 해당 옵션이 필요 없고, Jest와의 호환성을 위해 "type": "module" 을 제거해주는 것이고, JS파일은 기본적으로 CommonJS모듈 시스템을 사용하기 때문에 import문을 사용했으면 ESM방식으로 해석하도록 명시하기 위해서 "type": "module" 을 추가한다. 라고 설명을 해주는데 그럼 JS 파일의 경우 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 파일을 컴파일하고 실행할 수 있도록 해주니 잘 동작합니다.
안녕하세요, 선생님. 강의를 모두 듣고 개인 프로젝트에 적용해보고 있는 중에 궁금한 점이 생겨 질문 남깁니다. 이번 강의에 나온 cypress cloud를 사용해서 테스트 자동화를 해보았는데 문득 cypress가 아니라 cypress cloud를 사용해서 테스트 자동화를 하는 이유가 무엇인지 궁금하더라고요. https://docs.cypress.io/guides/continuous-integration/github-actions 위 문서를 찾아보니 cypress cloud는 테스트를 병렬로 진행해서 속도가 더 빠르다고 하는데 병렬 테스트를 위해 cypress cloud를 사용하는 것인지 궁금합니다. 아니면 뭔가 다른 이유가 있을까요?
따라하며 배우는 리액트 테스트코드 강의에서 eslint가 적용되었다고 하는 파일자체를 받아 npm install을 헀는데, eslint가 작동되지않습니다. extension에서도 eslint를 받았고, npm install을 한 상태에서 test() let test = () => {} 와 같은 오류가 발생될 코드를 작성해도 eslint가 반응하지 못하는데 이유가 뭘까요 강의에는 설정이 적용되어있다고 하는데
강의 1분쯤에 jest.config.cjs로 쓰는 것과 package.json에서 작성하는 법 2가지를 알려주셨을 때 전자대로 적용해 실행하니 아래와 같은 에러가 발생했습니다! 이후에 package.json에 작성해서 실행하는 방법으로 변경하니 정상적으로 작동했는데 혹시 이 원인을 알 수 있을까요? modules를 import하지 못한 이유를 잘 모르겠습니다!
// 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 } 둘의 차이점에 대해서 알 수 있을까요?
섹션3 recoil을 테스트하는 방법 3:50에 cy.url().should('include','/'); 를 통해서 root page로 잘 이동하는지 확인한다고 하신부분에서, '/' 는 어떤 페이지에서든 include가 되어 테스트가 통과될것 같은데 혹시 rootpage를 검증하기위한 다른 방법은 없을까요?
안녕하세요! 강의를 듣고 테스트 코드를 연습중에 질문이 있어서 글을 작성하게 되었습니다. 제가 테스트 코드를 작성하려는 프로젝트에서 공용 컴포넌트 중 Pagination 컴포넌트에 유닛 테스트 코드를 작성하려고 합니다. 제가 생각한 테스트 흐름은 실제 유저가 Pagination 컴포넌트의 화살표 버튼 클릭시 현재 페이지가 1이 증가하는 것처럼 테스트 코드를 구현하려고 했습니다. 하지만 Pagination 컴포넌트에는 setCurrentPage 함수를 주입 받아서 처리하기 때문에 유닛 테스트에서는 클릭으로 current page 값이 증가하는 것을 확인할 수는 없고 spy 함수를 통해 setCurrentPage가 실행되는 것까지만 확인하는게 맞는건가요?? 두서없는 글 읽어주셔서 감사합니다!
안녕하세요 강의 도움 많이 받고 타입스크립트 + 리액트 조합으로 서비스 만들고 있습니다. 강의에 테스트코드 관련 내용은 없어 무관한 질문 죄송합니다 ㅠ jest로 테스트 코드를 작성하려고 하는데 설정에 무슨 오류가 있는지 도무지 테스트가 되지 않습니다.. 여러 블로그 글이랑 챗 gpt참고해서 수정해도 안되는데 혹시 타입스크립트에서 jest 쓰려면 다른 설정을 해줘야 하는건가요? 도움 주시면 감사드리겠습니다 ..
공유해주신 프로젝트 clone해서 수정 없이 npm run unit-test 명령어 실행 시, 아래 이미지와 같이 export().toBeInTheDocument() 를 찾지 못해 진도를 나가지 못하고 있습니다.. 혹시 해결방안을 알려주실 수 있으실까요? 구글링 검색 시, import "@testing-library/jest-dom"; 을 테스트 파일 가장 상위에 두라고 하는데 이미 되어 있고 다른 해결책들도 실행해보았지만 해결하지 못했습니다. 노드 버전은 20.10.0 , 18.19.0 , 18.14.0 에서 실행했을 때, 모두 실패했습니다..
안녕하세요 강의 잘 듣고 있습니다. 강의를 듣다가 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)
혹시나 에러가 나신다면, 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