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
- 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();
} );
} );
- 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