πŸ’¦ FULL SET: WordPress/gutenberg/issues/ - High Quality

Skip to content

Not possible to mock packages that use private APIsΒ #57426

@chrisvanpatten

Description

@chrisvanpatten

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( <Edit /> );

		expect( screen.getByTestId( 'rich-text' ) ).toBeInTheDocument();
		expect( screen.getByTestId( 'inner-blocks' ) ).toBeInTheDocument();
	} );
} );
  1. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    [Package] Private APIs/packages/private-apis[Type] BugAn existing feature does not function as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions