๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿชฒ debug

[Jest + RTL (next/link)] TypeError: Cannot read properites of null (reading 'useContext') ft. jest.mock

ํ…Œ์ŠคํŠธ ์•ˆ๋Œ์•„๊ฐ

 

ํ…Œ์ŠคํŠธ ๋„์ž… ๊ณ ๊ตฐ๋ถ„ํˆฌ ์ค‘..

 

ํ…์ŠคํŠธ ์ปดํฌ๋„ŒํŠธ๋Š” ์ž˜ ๋Œ์•„๊ฐ€๋Š”๋ฐ ํ…์ŠคํŠธ๋ฅผ ๊ฐ์‹ธ์ฃผ๋Š” ๋งํฌ ์ปดํฌ๋„ŒํŠธ๋Š” ํ…Œ์ŠคํŠธ ์ž์ฒด๊ฐ€ ์•ˆ๋์—ˆ๋‹ค.

๊ทธ๋Ÿฌ๋‹ค UnstyledLink ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋‹ค์‹œ ๋ณด๋‹ˆ next/link ์‚ฌ์šฉ๋•Œ๋ฌธ์ธ๊ฐ€ ํ•ด์„œ ๊ฒ€์ƒ‰์„ ํ•˜๋‹ˆ mock์„ ์ถ”๊ฐ€ํ•ด์ค˜์•ผ ํ–ˆ๋‹ค.

 

๋”ฐ๋ผ์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ–ˆ๋”๋‹ˆ ์ž˜ ๋Œ์•„๊ฐ„๋‹ค.

import "@testing-library/jest-dom";
import "@testing-library/jest-dom/jest-globals";
import { render, screen } from "@testing-library/react";

import UnstyledLink, { LinkProps } from "../_link";

////////////////////////////////////// ๐Ÿ’– ์ถ”๊ฐ€ //////////////////////////////////////
jest.mock("next/link", () => {
  const { cloneElement } = jest.requireActual("react");
  return ({ children, ...rest }: LinkProps) =>
    cloneElement(children, { ...rest });
});
////////////////////////////////////// ๐Ÿ’– ์ถ”๊ฐ€ //////////////////////////////////////

it("link has '๋–ก๋ณถ์ด'", () => {
  render(<UnstyledLink href="#">๋–ก๋ณถ์ด</UnstyledLink>);
  screen.debug();
  expect(screen.getByText("๋–ก๋ณถ์ด")).toBeInTheDocument();
});

 


๐Ÿ“š References 

https://stackoverflow.com/questions/71254835/jest-testing-link-next-link

 

Jest - testing Link (next/link)

I am trying to write unit tests to confirm my nav links work correctly. My MainNavigation.js file: import Link from 'next/link'; const MainNavigation = () => { return ( <header> ...

stackoverflow.com