TypeError: (0, _local.default) 在 Jest 中使用 next/font/local 时不是一个函数

Ali*_*ghi 5 nomachine-nx typescript reactjs jestjs next.js

我正在使用 MUI、React 和 TypeScript 开发一个 UI 库,并以 Nx 作为构建系统。出于测试目的,我使用 Jest。但是,当我尝试按照 Next.js 文档中提供的说明将字体添加到我的项目时遇到错误。

导致该问题的代码片段如下:

import localFont from 'next/font/local';

const myFont = localFont({ src: './my-font.woff2' });
Run Code Online (Sandbox Code Playgroud)

运行 Jest 测试时,我收到以下错误消息:

TypeError: (0, _local.default) is not a function
Run Code Online (Sandbox Code Playgroud)

对于如何解决此错误并在使用 Jest 进行测试时成功将字体添加到我的项目中的任何见解或建议,我将不胜感激。谢谢你!

我希望localFont函数 fromnext/font/local能够在 Jest 环境中成功导入并执行,并且不会出现任何错误。应为该myFont变量分配适当的值,以便我可以在 UI 库中使用该字体。我想了解为什么会出现错误消息“TypeError: (0, _local.default) is not a function”,并找到解决方案来解决它。

小智 3

问题与“localFont”的使用有关。我最近遇到了同样的问题,但上面的解决方案对我不起作用,因为我也在使用“next/font/local”

/*
  NextJS's font optimization has built-in automatic self-hosting for any font file.  The optimization automatically
  downloads any Google font and places Google and local fonts into an app's static assets all at BUILD time.  
  When running tests it's important to mock the module import 'next/font/google' and 'next/font/local' depending on
  which font optimization you're using.

  A mock for the function, localFont().
*/
jest.mock("next/font/local", () => function() {
  return {
        style: {
          fontFamily: 'my_font'
      }
    }
  }
);
Run Code Online (Sandbox Code Playgroud)