Skip to content

Commit

Permalink
Display better warning messages
Browse files Browse the repository at this point in the history
  • Loading branch information
zaguiini committed Nov 22, 2023
1 parent 514a1dd commit bf10159
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 19 deletions.
63 changes: 45 additions & 18 deletions packages/block-editor/src/utils/test/transform-styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,53 @@
import transformStyles from '../transform-styles';

describe( 'transformStyles', () => {
it( 'should not throw error in case of invalid css', () => {
const run = () =>
transformStyles(
[
{
css: 'h1 { color: red; }', // valid CSS
},
{
css: 'h1 { color: red;', // invalid CSS
},
],
'.my-namespace'
);

expect( run ).not.toThrow();
describe( 'error handling', () => {
beforeEach( () => {
// Intentionally suppress the expected console errors and warnings to reduce
// noise in the test output.
jest.spyOn( console, 'warn' ).mockImplementation( jest.fn() );
} );

const [ validCSS, invalidCSS ] = run();
it( 'should not throw error in case of invalid css', () => {
const run = () =>
transformStyles(
[
{
css: 'h1 { color: red;', // invalid CSS
},
],
'.my-namespace'
);

expect( run ).not.toThrow();
expect( console ).toHaveWarned();
} );

expect( validCSS ).toBe( '.my-namespace h1 { color: red; }' );
expect( invalidCSS ).toBe( null );
it( 'should warn invalid css in the console', () => {
const run = () =>
transformStyles(
[
{
css: 'h1 { color: red; }', // valid CSS
},
{
css: 'h1 { color: red;', // invalid CSS
},
],
'.my-namespace'
);

const [ validCSS, invalidCSS ] = run();

expect( validCSS ).toBe( '.my-namespace h1 { color: red; }' );
expect( invalidCSS ).toBe( null );

expect( console ).toHaveWarnedWith(
'wp.blockEditor.transformStyles Failed to transform CSS.',
'<css input>:1:1: Unclosed block\n> 1 | h1 { color: red;\n | ^'
// ^^^^ In PostCSS, a tab is equal four spaces
);
} );
} );

describe( 'selector wrap', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/block-editor/src/utils/transform-styles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ const transformStyles = ( styles, wrapperSelector = '' ) => {
].filter( Boolean )
).process( css, {} ).css; // use sync PostCSS API
} catch ( error ) {
if ( ! ( error instanceof CssSyntaxError ) ) {
if ( error instanceof CssSyntaxError ) {
// eslint-disable-next-line no-console
console.warn(
'wp.blockEditor.transformStyles Failed to transform CSS.',
error.message + '\n' + error.showSourceCode( false )
);
} else {
// eslint-disable-next-line no-console
console.warn(
'wp.blockEditor.transformStyles Failed to transform CSS.',
Expand Down

0 comments on commit bf10159

Please sign in to comment.