ã¯ããã«
å人éçºã§ç°¡åãªã¢ããªãä½æããããã¦ããä¸ã§ããã¤ãã¦ããããã¹ãä½æãã¦ããªãã£ãã®ã§ãä»åæãç«ã£ã¦ãJavaScript ã®ã¦ããããã¹ãã§ãã使ããã Jest ã使ã£ããã¹ãã³ã¼ããæ¸ãã¦ã¿ãã¡ã¢ã§ãã
Â
ã³ã³ãã¼ãã³ãã®ãã¹ã
ãã¹ã対象ã³ã¼ã
Â
èªä½ã®ãã¿ã³ã³ã³ãã¼ãã³ãã«å¯¾ããã¦ããããã¹ããæ¸ãã¦ã¿ã¾ãã
Â
ãã¹ãã³ã¼ã
import { fireEvent, render, screen } from "@testing-library/react"; import Button from "../Button"; describe("Buttonã³ã³ãã¼ãã³ããã¹ã", () => { // ã¢ãã¯é¢æ°ãä½æ const handleClick = jest.fn(); beforeEach(() => { render(); }); test("ã¿ã¤ãã«ãæ£ãã表示ããããã¨", () => { const buttonElement = screen.getByRole("button"); expect(buttonElement).toHaveTextContent("Buttonãã¹ã"); }); test("ã¯ãªãã¯ã¤ãã³ããè¡ããããã¨", () => { const buttonElement = screen.getByRole("button"); // ã¯ãªãã¯ã¤ãã³ããã·ãã¥ã¬ã¼ã fireEvent.click(buttonElement); // ã¯ãªãã¯ã¤ãã³ããå¼ã°ãããã¨ãç¢ºèª expect(handleClick).toHaveBeenCalledTimes(1); }); });
- describe ã¯å¿ ãå®ç¾©ããªãã¨ãããªããã®ã§ã¯ããã¾ããããæ£å¸¸ç³»ãç°å¸¸ç³»ãã®ããã«ãã¹ãã°ã«ã¼ãã示ããªã©ãã¹ãã³ã¼ãã®å¯èªæ§åä¸ã«å½¹ç«ã¤ã¨æãã¾ã
- beforeEach ã§åãã¹ããã¨ã«å®è¡ããåå¦çãå®ç¾©ãã¦ãã¾ããã»ãã«ããbeforeAllãafterEach, afterAll ãªã©ã®åå¦çãå¾å¦çã使ç¨ã§ãã¾ã
- test é¢æ°å ã«å®è¡ãããã¹ãå 容ãè¨è¿°ãã¦ããã¾ã
- ã³ã³ãã¼ãã³ãã®ã¦ããããã¹ãã¯ãã³ã³ãã¼ãã³ããæç» -> ãã¹ã対象è¦ç´ ã®åå¾ãã¤ãã³ãçºè¡ -> çµæã®æ¤è¨¼ï¼expectï¼ãåºæ¬ã®æµãã¨ãªãã¾ã
Â
ãã¹ããå®è¡ããã¨ä¸è¨ã®ããã«è¡¨ç¤ºããã¾ãã
npm run test > [email protected] test > jest PASS src/components/__tests__/Button.test.tsx Buttonã³ã³ãã¼ãã³ããã¹ã â ã¿ã¤ãã«ãæ£ãã表示ãããã㨠(19 ms) â ã¯ãªãã¯ã¤ãã³ããè¡ãããã㨠(4 ms) Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 0.654 s Ran all test suites.
Â
jest é¢é£ã§ããã£ãç®æ
ä¸è¨ã®ãã¹ãã³ã¼ãã§ãrender é¢æ°ã§ã³ã³ãã¼ãã³ããæç»ãã¦ããç®æã§ã¨ãã£ã¿ã¼ã®ã³ã³ãã¤ã«ã¨ã©ã¼ãåºããããã¹ãå®è¡æã«ãexpect é¢æ°ã® toHaveTextContent ãæªå®ç¾©ã®æ¨ã®ã¨ã©ã¼ãåºãããã¦ä»¥ä¸ã®è¨å®ç³»ãã¡ã¤ã«ãç¨æãããã¨ã§ã¨ã©ã¼åé¿ã§ããã®ã§ããã®è¾ºã®ãã¡ã¤ã«ç¾¤ãä¸è¨ã«è¨è¼ãã¾ãã
ããåãããã«ãã¹ãã³ã¼ãã¯æ¸ãããã©ã³ã³ãã¤ã«ã¨ã©ã¼ãåºã¦ãããã¨ãã£ããããªã¨ã©ã¼ã«ééãã¦ããæ¹ã¯ãä¸è¨ã試ãã¦ã¿ã¦ãã ããã
Â
以ä¸ããããããã¸ã§ã¯ããã©ã«ãç´ä¸ã«é ç½®ãã¾ããã
babel.config.js
module.exports = { presets: [ "@babel/preset-env", ["@babel/preset-react", { runtime: "automatic" }], // JSXãµãã¼ãã追å "@babel/preset-typescript", // TypeScriptãµãã¼ã ], };
- babelãJSXå¼ãèªèããããã«å®ç¾©ã追å ãã¾ããããã㧠render é¢æ°ã®ã¨ã©ã¼ã解æ¶ãã¾ãã
Â
jest.config.js
module.exports = { testEnvironment: "jest-environment-jsdom", transform: { "^.+\\.(ts|tsx)$": "babel-jest", // TypeScriptãã¡ã¤ã«ããã©ã³ã¹ãã¤ã« "^.+\\.(js|jsx)$": "babel-jest", // JavaScriptãã¡ã¤ã«ããã©ã³ã¹ãã¤ã« }, moduleFileExtensions: ["ts", "tsx", "js", "jsx"], // æ¡å¼µåã追å setupFilesAfterEnv: ["/setupTests.ts"], };
Â
setupTests.ts
import "@testing-library/jest-dom";
- describe ã expect ãªã©ã®ãã¹ãé¢æ°ã使ç¨ã§ããããã«ããããã® import ãè¡ã£ã¦ãã¾ãã
- ãã®ãã¡ã¤ã«ããjest.config.js ã§èªã¿è¾¼ãããã«ãããã¨ã§ãdescribe ãè¨è¿°ããéã®ã¨ãã£ã¿ã¼ã®ã³ã³ãã¤ã«ã¨ã©ã¼ã解æ¶ãã¾ãã
Â
çµããã«
ã¦ããããã¹ãé¿ãã¦ãã¾ããããå®éãã£ã¦ã¿ãã¨ã³ã¼ãããã£ããããããããæ¸ããããä½ããã¦ããããã¹ããç¨æãã¦ãããã¨ã§å®å¿æãæã¦ã¾ããã
ä»å¾ã¦ããããã¹ããã»ããã§æ¸ããã¨ãç¿æ £ã«ãã¦ããããã¨æãã¾ãã