@@ -1662,4 +1662,80 @@ describe('React Integration Tests', () => {
16621662 global . localStorage = originalLocalStorage ;
16631663 } ) ;
16641664 } ) ;
1665+
1666+ describe ( 'POST body cache key update' , ( ) => {
1667+ it ( 'should regenerate cache key and use updated body when POST body changes and refetch is called' , async ( ) => {
1668+ const testUrl = '/api/post-body-cache-key' ;
1669+ const initialBody = { value : 'first' } ;
1670+ const updatedBody = { value : 'second' } ;
1671+ let currentBody = initialBody ;
1672+
1673+ // Mock fetch to echo back the request body
1674+ global . fetch = jest . fn ( ) . mockImplementation ( ( _url , config ) => {
1675+ const parsedBody =
1676+ config && config . body ? JSON . parse ( config . body ) : undefined ;
1677+ return Promise . resolve ( {
1678+ ok : true ,
1679+ status : 200 ,
1680+ data : parsedBody ,
1681+ body : parsedBody ,
1682+ json : ( ) => Promise . resolve ( parsedBody ) ,
1683+ } ) ;
1684+ } ) ;
1685+
1686+ // React state simulation
1687+ let setBody : ( b : typeof initialBody ) => void = ( ) => { } ;
1688+ function BodyComponent ( ) {
1689+ const [ body , _setBody ] = React . useState ( currentBody ) ;
1690+ setBody = _setBody ;
1691+ const { data, refetch, isLoading } = useFetcher ( testUrl , {
1692+ method : 'POST' ,
1693+ body,
1694+ } ) ;
1695+ return (
1696+ < div >
1697+ < div data-testid = "data" >
1698+ { data ? JSON . stringify ( data ) : 'No Data' }
1699+ </ div >
1700+ < div data-testid = "loading" >
1701+ { isLoading ? 'Loading...' : 'Not Loading' }
1702+ </ div >
1703+ < button data-testid = "refetch-btn" onClick = { ( ) => refetch ( true ) } >
1704+ Refetch
1705+ </ button >
1706+ </ div >
1707+ ) ;
1708+ }
1709+
1710+ render ( < BodyComponent /> ) ;
1711+
1712+ // Wait for initial fetch
1713+ await waitFor ( ( ) => {
1714+ expect ( screen . getByTestId ( 'data' ) ) . toHaveTextContent ( 'No Data' ) ;
1715+ } ) ;
1716+
1717+ // Act: update the body asynchronously
1718+ act ( ( ) => {
1719+ currentBody = updatedBody ;
1720+ setBody ( updatedBody ) ;
1721+ } ) ;
1722+
1723+ // Refetch with new body
1724+ fireEvent . click ( screen . getByTestId ( 'refetch-btn' ) ) ;
1725+
1726+ // Assert: data should match updated body
1727+ await waitFor ( ( ) => {
1728+ expect ( screen . getByTestId ( 'data' ) ) . toHaveTextContent ( 'second' ) ;
1729+ } ) ;
1730+
1731+ // Also check that fetch was called with the updated body
1732+ expect ( global . fetch ) . toHaveBeenLastCalledWith (
1733+ testUrl ,
1734+ expect . objectContaining ( {
1735+ method : 'POST' ,
1736+ body : JSON . stringify ( updatedBody ) ,
1737+ } ) ,
1738+ ) ;
1739+ } ) ;
1740+ } ) ;
16651741} ) ;
0 commit comments