|
| 1 | +/** |
| 2 | + * WordPress dependencies |
| 3 | + */ |
| 4 | +import { addFilter, removeFilter } from '@wordpress/hooks'; |
| 5 | +import { useSelect } from '@wordpress/data'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Internal dependencies |
| 9 | + */ |
| 10 | +import useSetting from '..'; |
| 11 | +import * as BlockEditContext from '../../block-edit/context'; |
| 12 | + |
| 13 | +// Mock useSelect() functions used by useSetting() |
| 14 | +jest.mock( '@wordpress/data/src/components/use-select' ); |
| 15 | + |
| 16 | +let selectMock = {}; |
| 17 | +const setupSelectMock = () => { |
| 18 | + selectMock = { |
| 19 | + getSettings: () => ( {} ), |
| 20 | + getBlockParents: () => [], |
| 21 | + getBlockName: () => '', |
| 22 | + }; |
| 23 | +}; |
| 24 | + |
| 25 | +useSelect.mockImplementation( ( callback ) => callback( () => selectMock ) ); |
| 26 | + |
| 27 | +const mockSettings = ( settings ) => { |
| 28 | + selectMock.getSettings = () => ( { |
| 29 | + __experimentalFeatures: settings, |
| 30 | + } ); |
| 31 | +}; |
| 32 | + |
| 33 | +const mockCurrentBlockContext = ( |
| 34 | + blockContext = { name: '', isSelected: false } |
| 35 | +) => { |
| 36 | + jest.spyOn( BlockEditContext, 'useBlockEditContext' ).mockReturnValue( |
| 37 | + blockContext |
| 38 | + ); |
| 39 | +}; |
| 40 | + |
| 41 | +describe( 'useSetting', () => { |
| 42 | + beforeEach( () => { |
| 43 | + setupSelectMock(); |
| 44 | + mockCurrentBlockContext(); |
| 45 | + } ); |
| 46 | + |
| 47 | + it( 'uses block setting', () => { |
| 48 | + mockSettings( { |
| 49 | + blocks: { |
| 50 | + 'core/test-block': { |
| 51 | + layout: { |
| 52 | + contentSize: '840px', |
| 53 | + }, |
| 54 | + }, |
| 55 | + }, |
| 56 | + } ); |
| 57 | + |
| 58 | + mockCurrentBlockContext( { |
| 59 | + name: 'core/test-block', |
| 60 | + } ); |
| 61 | + |
| 62 | + expect( useSetting( 'layout.contentSize' ) ).toBe( '840px' ); |
| 63 | + } ); |
| 64 | + |
| 65 | + it( 'uses blockEditor.useSetting.before hook override', () => { |
| 66 | + mockSettings( { |
| 67 | + blocks: { |
| 68 | + 'core/test-block': { |
| 69 | + layout: { |
| 70 | + contentSize: '840px', |
| 71 | + }, |
| 72 | + }, |
| 73 | + }, |
| 74 | + } ); |
| 75 | + |
| 76 | + mockCurrentBlockContext( { |
| 77 | + name: 'core/test-block', |
| 78 | + } ); |
| 79 | + |
| 80 | + addFilter( |
| 81 | + 'blockEditor.useSetting.before', |
| 82 | + 'test/useSetting.before', |
| 83 | + ( result, path, clientId, blockName ) => { |
| 84 | + if ( blockName === 'core/test-block' ) { |
| 85 | + return '960px'; |
| 86 | + } |
| 87 | + |
| 88 | + return result; |
| 89 | + } |
| 90 | + ); |
| 91 | + |
| 92 | + expect( useSetting( 'layout.contentSize' ) ).toBe( '960px' ); |
| 93 | + |
| 94 | + removeFilter( |
| 95 | + 'blockEditor.useSetting.before', |
| 96 | + 'test/useSetting.before' |
| 97 | + ); |
| 98 | + } ); |
| 99 | +} ); |
0 commit comments