Skip to content

Commit

Permalink
Make esm default interpolation work with jest mock
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed May 13, 2022
1 parent 092346d commit 973f120
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/next/taskfile-swc.js
Expand Up @@ -118,7 +118,25 @@ module.exports = function (task) {
if (interopClientDefaultExport) {
output.code += `
if (typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) {
Object.assign(exports.default, exports);
for (var exp in exports) {
if (Object.prototype.hasOwnProperty.call(exports, exp)) {
Object.defineProperty(exports.default, exp, {
enumerable: true,
configurable: true,
get: (function (exp) {
return function() {
return exports[exp];
}
})(exp),
set: (function (exp) {
return function(newValue) {
exports[exp] = newValue;
}
})(exp)
});
}
}
Object.defineProperty(exports.default, '__esModule', { value: true });
module.exports = exports.default;
}
`
Expand Down
14 changes: 14 additions & 0 deletions test/unit/esm-interpolate/esm-interpolate.test.tsx
@@ -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>`)
})
8 changes: 8 additions & 0 deletions test/unit/esm-interpolate/fixture.tsx
@@ -0,0 +1,8 @@
import React from 'react'
import { useRouter } from 'next/router'

export const Foo = () => {
const router = useRouter()

return <div>{router.pathname}</div>
}

0 comments on commit 973f120

Please sign in to comment.