@@ -4,10 +4,13 @@ import {
44 csrfServerAction ,
55} from '@molecules/NHSNotifyFormWrapper/NHSNotifyFormWrapper' ;
66import { render } from '@testing-library/react' ;
7- import { verifyCsrfTokenFull } from '@utils/csrf-utils' ;
7+ import { redirect } from 'next/navigation' ;
8+ import { verifyFormCsrfToken } from '@utils/csrf-utils' ;
9+
10+ jest . mock ( 'next/navigation' ) ;
811
912jest . mock ( '@utils/csrf-utils' , ( ) => ( {
10- verifyCsrfTokenFull : jest . fn ( ) ,
13+ verifyFormCsrfToken : jest . fn ( ) ,
1114} ) ) ;
1215
1316test ( 'Renders back button' , ( ) => {
@@ -27,8 +30,9 @@ describe('csrfServerAction', () => {
2730 expect ( action ) . toEqual ( '/action' ) ;
2831 } ) ;
2932
30- test ( 'server action' , async ( ) => {
31- const mockAction = jest . fn ( ( ) => 'response' ) ;
33+ test ( 'server action with valid csrf check' , async ( ) => {
34+ jest . mocked ( verifyFormCsrfToken ) . mockResolvedValueOnce ( true ) ;
35+ const mockAction = jest . fn ( ) ;
3236 const action = csrfServerAction ( mockAction ) ;
3337
3438 if ( typeof action === 'string' ) {
@@ -38,7 +42,25 @@ describe('csrfServerAction', () => {
3842 const mockFormData = mockDeep < FormData > ( ) ;
3943 await action ( mockFormData ) ;
4044
41- expect ( verifyCsrfTokenFull ) . toHaveBeenCalledWith ( mockFormData ) ;
45+ expect ( verifyFormCsrfToken ) . toHaveBeenCalledWith ( mockFormData ) ;
4246 expect ( mockAction ) . toHaveBeenCalledWith ( mockFormData ) ;
4347 } ) ;
48+
49+ test ( 'server action with failed csrf check' , async ( ) => {
50+ jest . mocked ( verifyFormCsrfToken ) . mockResolvedValueOnce ( false ) ;
51+
52+ const mockAction = jest . fn ( ) ;
53+ const action = csrfServerAction ( mockAction ) ;
54+
55+ if ( typeof action === 'string' ) {
56+ throw new TypeError ( 'Expected server action' ) ;
57+ }
58+
59+ const mockFormData = mockDeep < FormData > ( ) ;
60+ await action ( mockFormData ) ;
61+
62+ expect ( verifyFormCsrfToken ) . toHaveBeenCalledWith ( mockFormData ) ;
63+ expect ( redirect ) . toHaveBeenCalledWith ( '/auth/signout' ) ;
64+ expect ( mockAction ) . not . toHaveBeenCalled ( ) ;
65+ } ) ;
4466} ) ;
0 commit comments