Skip to content

Commit

Permalink
Add: Generic end 2 end test to the block transforms.
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgefilipecosta committed Nov 27, 2018
1 parent f97617f commit b7c0a55
Show file tree
Hide file tree
Showing 8 changed files with 302 additions and 39 deletions.
39 changes: 39 additions & 0 deletions test/e2e/specs/__snapshots__/block-transforms.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`test transforms individual transforms work as expected Code block should transform to Preformatted block. fixture: core__code 1`] = `
"<!-- wp:preformatted -->
<pre class=\\"wp-block-preformatted\\">export default function MyButton() {
return <Button>Click Me!</Button>;
}</pre>
<!-- /wp:preformatted -->"
`;
exports[`test transforms individual transforms work as expected Paragraph block should transform to Heading block. fixture: core__paragraph__align-right 1`] = `
"<!-- wp:heading -->
<h2>... like this one, which is separate from the above and right aligned.</h2>
<!-- /wp:heading -->"
`;
exports[`test transforms individual transforms work as expected Paragraph block should transform to List block. fixture: core__paragraph__align-right 1`] = `
"<!-- wp:list -->
<ul><li>... like this one, which is separate from the above and right aligned.</li></ul>
<!-- /wp:list -->"
`;
exports[`test transforms individual transforms work as expected Paragraph block should transform to Preformatted block. fixture: core__paragraph__align-right 1`] = `
"<!-- wp:preformatted -->
<pre class=\\"wp-block-preformatted\\">... like this one, which is separate from the above and right aligned.</pre>
<!-- /wp:preformatted -->"
`;
exports[`test transforms individual transforms work as expected Paragraph block should transform to Quote block. fixture: core__paragraph__align-right 1`] = `
"<!-- wp:quote -->
<blockquote class=\\"wp-block-quote\\"><p>... like this one, which is separate from the above and right aligned.</p></blockquote>
<!-- /wp:quote -->"
`;
exports[`test transforms individual transforms work as expected Paragraph block should transform to Verse block. fixture: core__paragraph__align-right 1`] = `
"<!-- wp:verse -->
<pre class=\\"wp-block-verse\\">... like this one, which is separate from the above and right aligned.</pre>
<!-- /wp:verse -->"
`;
164 changes: 164 additions & 0 deletions test/e2e/specs/block-transforms.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/**
* External dependencies
*/
import path from 'path';
import {
intersection,
mapValues,
pickBy,
some,
} from 'lodash';

/**
* Internal dependencies
*/
import {
getAllBlocks,
getAvailableBlockTransforms,
getBlockTitle,
getEditedPostContent,
hasBlockSwitcher,
newPost,
setPostContent,
selectBlockByClientId,
transformBlock,
} from '../support/utils';
import {
getFileBaseNames,
readFixtureFile,
} from '../../support/utils';
import { EXPECTED_TRANSFORMS } from './fixtures/block-transforms';

/*
* Returns true if the fileBase refers to a fixture of a block
* that should not be handled e.g: because of being deprecated,
* or because of being a block that tests an error state.
*/
const isAnExpectedUnhandledBlock = ( fixturesDir, fileBase ) => {
if ( fileBase.includes( 'deprecated' ) ) {
return true;
}
const parsedBlockObject = JSON.parse(
readFixtureFile( fixturesDir, fileBase + '.parsed.json' )
)[ 0 ];
return some(
[
null,
'core/block',
'core/column',
'core/freeform',
'core/text-columns',
'core/subhead',
'core/text',
'unregistered/example',
],
( blockName ) => parsedBlockObject.blockName === blockName
);
};

const setPostContentAndSelectBlock = async ( content ) => {
await setPostContent( content );
const blocks = await getAllBlocks();
const clientId = blocks[ 0 ].clientId;
await page.click( '.editor-post-title .editor-post-title__block' );
await selectBlockByClientId( clientId );
};

const getTransformStructureFromFile = async ( fixturesDir, fileBase ) => {
if ( isAnExpectedUnhandledBlock( fixturesDir, fileBase ) ) {
return null;
}
const content = readFixtureFile( fixturesDir, fileBase + '.html' );
await setPostContentAndSelectBlock( content );
const block = ( await getAllBlocks() )[ 0 ];
const availableTransforms = await getAvailableBlockTransforms();
const originalBlock = await getBlockTitle( block.name );

return {
availableTransforms,
originalBlock,
content,
};
};

const getTransformResult = async ( blockContent, transformName ) => {
await setPostContentAndSelectBlock( blockContent );
expect( await hasBlockSwitcher() ).toBe( true );
await transformBlock( transformName );
return getEditedPostContent();
};

describe( 'test transforms', () => {
const fixturesDir = path.join(
__dirname, '..', '..', 'integration', 'full-content', 'fixtures'
);

// Todo: Remove the intersect as soon as all fixtures are corrected,
// and its direct usage on the editor does not trigger errors.
// Currently some fixtures trigger errors (mainly media related)
// because when loaded in the editor,
// some requests are triggered that have a 404 response.
const fileBasenames = intersection(
getFileBaseNames( fixturesDir ),
[
'core__code',
'core__paragraph__align-right',
]
);

const transformStructure = {};
beforeAll( async () => {
await newPost();

for ( const fileBase of fileBasenames ) {
const structure = await getTransformStructureFromFile(
fixturesDir,
fileBase
);
if ( ! structure ) {
continue;
}
transformStructure[ fileBase ] = structure;
await setPostContent( '' );
await page.click( '.editor-post-title .editor-post-title__block' );
}
} );

it( 'should contain the expected transforms', async () => {
expect(
mapValues(
pickBy(
transformStructure,
( { availableTransforms } ) => availableTransforms,
),
( { availableTransforms, originalBlock } ) => {
return { originalBlock, availableTransforms };
}
)
).toEqual( EXPECTED_TRANSFORMS );
} );

describe( 'individual transforms work as expected', () => {
beforeAll( async () => {
await newPost();
} );

beforeEach( async () => {
await setPostContent( '' );
await page.click( '.editor-post-title .editor-post-title__block' );
} );

for ( const [ fixture, { originalBlock, availableTransforms } ] of Object.entries( EXPECTED_TRANSFORMS ) ) {
for ( const transform of availableTransforms ) {
it( `${ originalBlock } block should transform to ${ transform } block. fixture: ${ fixture }`,
async () => {
const { content } = transformStructure[ fixture ];
expect(
await getTransformResult( content, transform )
).toMatchSnapshot();
}
);
}
}
} );
} );
18 changes: 18 additions & 0 deletions test/e2e/specs/fixtures/block-transforms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export const EXPECTED_TRANSFORMS = {
core__code: {
originalBlock: 'Code',
availableTransforms: [
'Preformatted',
],
},
'core__paragraph__align-right': {
originalBlock: 'Paragraph',
availableTransforms: [
'Heading',
'List',
'Quote',
'Preformatted',
'Verse',
],
},
};
11 changes: 11 additions & 0 deletions test/e2e/support/utils/get-block-title.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Returns a string containing the block title associated with the provided block name.
* @param {string} blockName Block name.
*
* @return {Promise} Promise resolving with a string containing the block title.
*/
export async function getBlockTitle( blockName ) {
return page.evaluate( ( _blockName ) => {
return wp.data.select( 'core/blocks' ).getBlockType( _blockName ).title;
}, blockName );
}
2 changes: 2 additions & 0 deletions test/e2e/support/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export { ensureSidebarOpened } from './ensure-sidebar-opened';
export { findSidebarPanelWithTitle } from './find-sidebar-panel-with-title';
export { getAllBlocks } from './get-all-blocks';
export { getAvailableBlockTransforms } from './get-available-block-transforms';
export { getBlockTitle } from './get-block-title';
export { getEditedPostContent } from './get-edited-post-content';
export { getUrl } from './get-url';
export { hasBlockSwitcher } from './has-block-switcher';
Expand All @@ -38,5 +39,6 @@ export { switchToAdminUser } from './switch-to-admin-user';
export { switchToEditor } from './switch-to-editor';
export { switchToTestUser } from './switch-to-test-user';
export { toggleOption } from './toggle-option';
export { transformBlock } from './transform-block';
export { visitAdmin } from './visit-admin';
export { waitForPageDimensions } from './wait-for-page-dimensions';
11 changes: 11 additions & 0 deletions test/e2e/support/utils/transform-block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Transforms the current selected block in the block whose title is blockTitle.
*
* @param {string} blockTitle Title of the destination block of the transformation.
*/
export const transformBlock = async ( blockTitle ) => {
await page.click( '.editor-block-toolbar .editor-block-switcher' );
await page.click(
`.editor-block-types-list .editor-block-types-list__list-item button[aria-label="${ blockTitle }"]`
);
};
58 changes: 19 additions & 39 deletions test/integration/full-content/full-content.spec.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/**
* External dependencies
*/
import fs from 'fs';
import path from 'path';
import { uniq, startsWith, get } from 'lodash';
import { startsWith, get } from 'lodash';
import { format } from 'util';

/**
Expand All @@ -18,37 +17,18 @@ import {
import { parse as grammarParse } from '@wordpress/block-serialization-default-parser';
import { registerCoreBlocks } from '@wordpress/block-library';

const fixturesDir = path.join( __dirname, 'fixtures' );
/**
* Internal dependencies
*/
import {
getFileBaseNames,
readFixtureFile,
writeFixtureFile,
} from '../../support/utils';

// We expect 4 different types of files for each fixture:
// - fixture.html : original content
// - fixture.parsed.json : parser output
// - fixture.json : blocks structure
// - fixture.serialized.html : re-serialized content
// Get the "base" name for each fixture first.
const fileBasenames = uniq(
fs.readdirSync( fixturesDir )
.filter( ( f ) => /(\.html|\.json)$/.test( f ) )
.map( ( f ) => f.replace( /\..+$/, '' ) )
);

function readFixtureFile( filename ) {
try {
return fs.readFileSync(
path.join( fixturesDir, filename ),
'utf8'
);
} catch ( err ) {
return null;
}
}
const fixturesDir = path.join( __dirname, 'fixtures' );

function writeFixtureFile( filename, content ) {
fs.writeFileSync(
path.join( fixturesDir, filename ),
content
);
}
const fileBasenames = getFileBaseNames( fixturesDir );

function normalizeParsedBlocks( blocks ) {
return blocks.map( ( block, index ) => {
Expand Down Expand Up @@ -77,15 +57,15 @@ describe( 'full post content fixture', () => {

fileBasenames.forEach( ( f ) => {
it( f, () => {
const content = readFixtureFile( f + '.html' );
const content = readFixtureFile( fixturesDir, f + '.html' );
if ( content === null ) {
throw new Error(
'Missing fixture file: ' + f + '.html'
);
}

const parserOutputActual = grammarParse( content );
let parserOutputExpectedString = readFixtureFile( f + '.parsed.json' );
let parserOutputExpectedString = readFixtureFile( fixturesDir, f + '.parsed.json' );

if ( ! parserOutputExpectedString ) {
if ( process.env.GENERATE_MISSING_FIXTURES ) {
Expand All @@ -94,7 +74,7 @@ describe( 'full post content fixture', () => {
null,
4
) + '\n';
writeFixtureFile( f + '.parsed.json', parserOutputExpectedString );
writeFixtureFile( fixturesDir, f + '.parsed.json', parserOutputExpectedString );
} else {
throw new Error(
'Missing fixture file: ' + f + '.parsed.json'
Expand Down Expand Up @@ -129,7 +109,7 @@ describe( 'full post content fixture', () => {
}

const blocksActualNormalized = normalizeParsedBlocks( blocksActual );
let blocksExpectedString = readFixtureFile( f + '.json' );
let blocksExpectedString = readFixtureFile( fixturesDir, f + '.json' );

if ( ! blocksExpectedString ) {
if ( process.env.GENERATE_MISSING_FIXTURES ) {
Expand All @@ -138,7 +118,7 @@ describe( 'full post content fixture', () => {
null,
4
) + '\n';
writeFixtureFile( f + '.json', blocksExpectedString );
writeFixtureFile( fixturesDir, f + '.json', blocksExpectedString );
} else {
throw new Error(
'Missing fixture file: ' + f + '.json'
Expand All @@ -162,12 +142,12 @@ describe( 'full post content fixture', () => {
// `serialize` doesn't have a trailing newline, but the fixture
// files should.
const serializedActual = serialize( blocksActual ) + '\n';
let serializedExpected = readFixtureFile( f + '.serialized.html' );
let serializedExpected = readFixtureFile( fixturesDir, f + '.serialized.html' );

if ( ! serializedExpected ) {
if ( process.env.GENERATE_MISSING_FIXTURES ) {
serializedExpected = serializedActual;
writeFixtureFile( f + '.serialized.html', serializedExpected );
writeFixtureFile( fixturesDir, f + '.serialized.html', serializedExpected );
} else {
throw new Error(
'Missing fixture file: ' + f + '.serialized.html'
Expand Down Expand Up @@ -209,7 +189,7 @@ describe( 'full post content fixture', () => {
// The parser output for this test. For missing files,
// JSON.parse( null ) === null.
const parserOutput = JSON.parse(
readFixtureFile( basename + '.json' )
readFixtureFile( fixturesDir, basename + '.json' )
);
// The name of the first block that this fixture file
// contains (if any).
Expand Down
Loading

0 comments on commit b7c0a55

Please sign in to comment.