WordPress / gutenberg

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.
https://wordpress.org/gutenberg/
Other
10.52k stars 4.21k forks source link

Not possible to mock packages that use private APIs #57426

Open chrisvanpatten opened 10 months ago

chrisvanpatten commented 10 months ago

Description

Packages with top-level locked private APIs are not easily mockable in Jest tests by third parties.

I will fully admit even after looking through the private API code I'm not 100% sure why this is, but I've been able to reproduce it consistently, particularly with tests which depend on the @wordpress/block-editor package. It seems like something in jest.requireActual is possibly accessing these APIs in an incompatible way.

Step-by-step reproduction instructions

  1. Write a Jest test depending on a mock of a package with top level private dependencies, such as @wordpress/block-editor
    
    jest.mock( '@wordpress/block-editor', () => ( {
    ...jest.requireActual( '@wordpress/block-editor' ),
    RichText: ( { value, onChange, placeholder } ) => (
        <input
            data-testid="rich-text"
            value={ value }
            onChange={ ( e ) => onChange( e.target.value ) }
            placeholder={ placeholder }
        />
    ),
    InnerBlocks: () => <div data-testid="inner-blocks">Mocked InnerBlocks</div>,
    useBlockProps: jest.fn( () => ( {} ) ),
    } ) );

describe( 'myTestSuite', () => { test( 'myTest', () => { render( );

    expect( screen.getByTestId( 'rich-text' ) ).toBeInTheDocument();
    expect( screen.getByTestId( 'inner-blocks' ) ).toBeInTheDocument();
} );

} );

2. Observe the following error in execution:

● Test suite failed to run

Cannot unlock an object that was not locked before.

  3 |
  4 | jest.mock( '@wordpress/block-editor', () => ( {
> 5 |       ...jest.requireActual( '@wordpress/block-editor' ),
    |               ^
  6 |       RichText: ( { value, onChange, placeholder } ) => (
  7 |               <input
  8 |                       data-testid="rich-text"


### Screenshots, screen recording, code snippet

_No response_

### Environment info

_No response_

### Please confirm that you have searched existing issues in the repo.

Yes

### Please confirm that you have tested with all plugins deactivated except Gutenberg.

Yes
jdamner commented 8 months ago

+1

VelichkoAlexander commented 8 months ago

I encountered the same issue while also mocking @wordpress/block-editor. Gutenberg version: 16.0.0.