next.js: router client file is transpiled incorrectly

Verify canary release

  • I verified that the issue exists in Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 21.4.0: Mon Feb 21 20:34:37 PST 2022; root:xnu-8020.101.4~2/RELEASE_X86_64
Binaries:
  Node: 16.11.1
  npm: 8.0.0
  Yarn: 1.22.17
  pnpm: N/A
Relevant packages:
  next: 12.1.5
  react: 17.0.2
  react-dom: 17.0.2

What browser are you using? (if relevant)

n/a

How are you deploying your application? (if relevant)

n/a

Describe the Bug

The dist/client/router.js file had this code added in version 12.1.5

if (typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) {
  Object.assign(exports.default, exports);
  module.exports = exports.default;
}

This essentially erases all named exports from the CJS exports object, and instead hangs them all on the default export. This breaks Jest code that’s mocking the useRouter hook.

import * as routerModule from 'next/router';

// ...

jest.spyOn(routerModule, 'useRouter').mockReturnValue(({
  pathname: '/foo/bar',
  push: pushMockFn,
} as unknown) as useRouter.NextRouter);

now breaks, since routerModule.useRouter is null, requiring instead

import routerModule from 'next/router';

This fixes the test, but is wrong. useRouter is not a property on the default export (or shouldn’t be) but is rather a named export in that module.

Expected Behavior

CJS exports should match ESM.

To Reproduce

See above

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 17 (8 by maintainers)

Commits related to this issue

Most upvoted comments

@arackaf unfortunately for now I have had to roll back to 12.0.7. The memory leak was what led me here, and it all seems related to the router. I couldn’t get any of the latest versions to build properly, so I’m skipping the hack to get my tests to pass until the larger issues get resolved.