Reputation: 303
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.
Upvotes: 9
Views: 2498
Reputation: 76
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'
}
}
}
);
Upvotes: 5
Reputation: 1534
It happened the same to me, I had to mock the import in my setupTests
file, do so in each of your test files or in a general file (like I did):
jest.mock("next/font/local", () => ({
Rubik: () => ({
style: {
fontFamily: "mocked",
},
}),
}));
In this case I just mocked that object because I only use those properties in my tests
Upvotes: 2