diff --git a/src/pages/Record.js b/src/pages/Record.js index 5119f88..59f8edf 100644 --- a/src/pages/Record.js +++ b/src/pages/Record.js @@ -9,7 +9,7 @@ class Record extends Component { } mount() { const pTag = document.querySelector(".date_info"); - const { date } = router.getParams(); + const { date } = router.getPathParams(); const today = new Date(); if (date) { pTag.innerText = date; diff --git a/src/utils/router.js b/src/utils/router.js index a2bd356..97743f2 100644 --- a/src/utils/router.js +++ b/src/utils/router.js @@ -29,7 +29,7 @@ export const route = (path) => { if (route.params.length === 0) { route.component(); } else { - const params = getParamsFromRoute(route, path); + const params = getPathParamsFromRoute(route, path); route.component(params); } } else { @@ -42,13 +42,13 @@ const navigate = (path) => { route(path); }; -const getParams = () => { +const getPathParams = () => { const pathname = window.location.pathname; const route = routerRegistry.find((route) => route.testRegExp.test(pathname)); - return getParamsFromRoute(route, pathname); + return getPathParamsFromRoute(route, pathname); }; -const getParamsFromRoute = (route, path) => { +export const getPathParamsFromRoute = (route, path) => { const params = {}; if (route && route.params.length > 0) { const matches = RegExp(route.testRegExp).exec(path); @@ -81,5 +81,5 @@ const init = () => { export default { init, navigate, - getParams, + getPathParams, }; diff --git a/test/utils/router.test.js b/test/utils/router.test.js index f3aa320..afd8830 100644 --- a/test/utils/router.test.js +++ b/test/utils/router.test.js @@ -1,17 +1,35 @@ -import { addRoute, routerRegistry } from "../../src/utils/router"; +import { + addRoute, + getPathParamsFromRoute, + routerRegistry, +} from "../../src/utils/router"; describe("addRoute 테스트", () => { test("path가 pathParam을 포함하지 않는 경우", () => { addRoute("/test", () => {}); expect(RegExp(routerRegistry[0].testRegExp).exec("/test")).toBeTruthy(); expect(RegExp(routerRegistry[0].testRegExp).exec("/text")).toBeFalsy(); + routerRegistry.pop(); }); test("path가 pathParam을 포함하는 경우", () => { addRoute("/test/:data", () => {}); expect( - RegExp(routerRegistry[1].testRegExp).exec("/test/testData") + RegExp(routerRegistry[0].testRegExp).exec("/test/testData") ).toBeTruthy(); - expect(RegExp(routerRegistry[1].testRegExp).exec("/test")).toBeFalsy(); + expect(RegExp(routerRegistry[0].testRegExp).exec("/test")).toBeFalsy(); + routerRegistry.pop(); + }); +}); + +describe("getPathParamsFromRoute 테스트", () => { + test("route에 저장된 정규표현식과 일치하는 데이터 리턴", () => { + addRoute("/test/:data", () => {}); + const route = routerRegistry[0]; + const param = getPathParamsFromRoute(route, "/test/123"); + expect(param).toEqual({ + data: "123", + }); + routerRegistry.pop(); }); });