Allow jest to run with use server directive (#56148)

Disable server components and server actions SWC transform when it's running jest. You can only do basic DOM testing like what we described in #54891 instead the server action itself.

Closes #53065 
Closes NEXT-1473
This commit is contained in:
Jiachi Liu 2023-09-28 16:15:51 +02:00 committed by GitHub
parent 8f0f8236ab
commit 48093b87a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 10 deletions

View file

@ -178,16 +178,16 @@ function getBaseSWCOptions({
development
),
}),
serverComponents: hasServerComponents
? { isServer: !!isServerLayer }
: undefined,
serverActions: hasServerComponents
? {
// TODO-APP: When Server Actions is stable, we need to remove this flag.
enabled: !!isServerActionsEnabled,
isServer: !!isServerLayer,
}
: undefined,
serverComponents:
hasServerComponents && !jest ? { isServer: !!isServerLayer } : undefined,
serverActions:
hasServerComponents && !jest
? {
// TODO-APP: When Server Actions is stable, we need to remove this flag.
enabled: !!isServerActionsEnabled,
isServer: !!isServerLayer,
}
: undefined,
bundleTarget,
}
}

View file

@ -0,0 +1,5 @@
'use server'
export async function action(data) {
console.log(data)
}

View file

@ -0,0 +1,9 @@
import { action } from './action'
export default function Page() {
return (
<button data-testid="log" onClick={action}>
log
</button>
)
}

View file

@ -0,0 +1,10 @@
/**
* @jest-environment jsdom
*/
import { render, screen } from '@testing-library/react'
import Page from './page'
it('works with client-only code', () => {
render(<Page />)
expect(screen.getByTestId('log')).toHaveTextContent('log')
})