DEV Community

Sean Atukorala
Sean Atukorala

Posted on

[Solved] SyntaxError: Unexpected token '.' Jest Error for Next.js Apps

Problem:

Running into the following error when trying to run unit tests for a Next.js application using the jest command:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){.container {
                                                                                      ^

    SyntaxError: Unexpected token '.'

      2 | import Image from 'next/image'
      3 |
    > 4 | import styles from '@/pages/index.module.css'
        |                                              ^
      5 |
      6 | export default function Home() {
      7 |   return (

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1773:14)
      at Object.<anonymous> (pages/index.tsx:4:46)
Enter fullscreen mode Exit fullscreen mode

Solution:

This error could be caused by a number of issues and is related to Jest wanting to process CommonJS code. But it is unable to process .css files for some reason and therefore throws this error.

Here is a potential solution that worked for me:

  1. Include the following line: '\\.css$': '<rootDir>/emptyModule.js', in your jest.config.js file
  2. Create a file named emptyModule.js in the root directory of your application

Here is my full jest.config.js file just for extra reference:

// Add any custom config to be passed to Jest
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    // Handle module aliases (this will be automatically configured for you soon)
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '\\.css$': '<rootDir>/emptyModule.js',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)

Enter fullscreen mode Exit fullscreen mode

Hopefully, this solves your issue. If not, keep looking for solutions, you'll come across one that works!

Conclusion:

Thanks for reading this blog post!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on Twitter and GitHub, connect with me on LinkedIn and subscribe to my YouTube channel.

Top comments (0)