Search code examples
reactjstypescriptnext.jsjestjsnomachine-nx

TypeError: (0, _local.default) is not a function when using next/font/local in Jest


I am developing a UI library using MUI, React, and TypeScript, with Nx as the build system. For testing purposes, I am using Jest. However, I encountered an error when trying to add a font to my project following the instructions provided in the Next.js documentation.

The code snippet causing the issue is as follows:

import localFont from 'next/font/local';

const myFont = localFont({ src: './my-font.woff2' });

When running Jest tests, I receive the following error message:

TypeError: (0, _local.default) is not a function

I would appreciate any insights or suggestions on how to resolve this error and successfully add the font to my project while using Jest for testing. Thank you!

I expect that the localFont function from next/font/local should be successfully imported and executed without any errors in the Jest environment. The myFont variable should be assigned the appropriate value, allowing me to use the font in my UI library. I would like to understand why the error message "TypeError: (0, _local.default) is not a function" is occurring and find a solution to resolve it.


Solution

  • The question pertains to the use of 'localFont'. I recently had the same problem, but the solution above did not work for me, because I was also using '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'
          }
        }
      }
    );