Make esm default interpolation work with jest mock (#36877)

fixes https://github.com/vercel/next.js/issues/36794
This commit is contained in:
LongYinan 2022-05-14 00:39:38 +08:00 committed by GitHub
parent 2ed5b3d5f0
commit 9e568dae24
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 0 deletions

View file

@ -118,6 +118,7 @@ module.exports = function (task) {
if (interopClientDefaultExport) {
output.code += `
if (typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}

View file

@ -0,0 +1,14 @@
import React from 'react'
import { renderToString } from 'react-dom/server'
import * as nextRouter from 'next/router'
import { Foo } from './fixture'
// @ts-expect-error
jest.spyOn(nextRouter, 'useRouter').mockReturnValue({
pathname: 'Hello',
})
test('mock the interpolated modules should work', () => {
expect(renderToString(<Foo />)).toBe(`<div>Hello</div>`)
})

View file

@ -0,0 +1,8 @@
import React from 'react'
import { useRouter } from 'next/router'
export const Foo = () => {
const router = useRouter()
return <div>{router.pathname}</div>
}