Parcourir la source

Introduce assertEqualMarkup() test util.

Maciej Gołaszewski il y a 6 ans
Parent
commit
e3898218b6

+ 1 - 0
packages/ckeditor5-utils/package.json

@@ -17,6 +17,7 @@
     "@ckeditor/ckeditor5-editor-classic": "^12.1.4",
     "@ckeditor/ckeditor5-core": "^12.3.0",
     "@ckeditor/ckeditor5-engine": "^14.0.0",
+    "assertion-error": "^1.1.0",
     "eslint": "^5.5.0",
     "eslint-config-ckeditor5": "^2.0.0",
     "husky": "^1.3.1",

+ 44 - 0
packages/ckeditor5-utils/tests/_utils/utils.js

@@ -5,6 +5,10 @@
 
 /* global console:false */
 
+import { AssertionError } from 'chai';
+// eslint-disable-next-line camelcase
+import { html_beautify } from 'js-beautify/js/lib/beautify-html';
+
 import EmitterMixin from '../../src/emittermixin';
 import CKEditorError from '../../src/ckeditorerror';
 import areConnectedThroughProperties from '../../src/areconnectedthroughproperties';
@@ -141,3 +145,43 @@ export function assertCKEditorError( err, message, editorThatShouldBeFindableFro
 		expect( err.data ).to.deep.equal( data );
 	}
 }
+
+/**
+ * An assertion util test whether two given strings containing markup language are equal.
+ * Unlike `expect().to.equal()` form Chai assertion library, this util formats the markup before showing a diff.
+ *
+ * This util can be used to test HTML strings and string containing serialized model.
+ *
+ *		// Will throw error for chaijs
+ *		assertEqualMarkup(
+ *			'<paragraph><$text foo="bar">baz</$text></paragraph>',
+ *			'<paragraph><$text foo="bar">baaz</$text></paragraph>',
+ *		);
+ *
+ * @param {String} actual An actual string.
+ * @param {String} expected An expected string.
+ * @param {message} [expected="Expected two markup strings to be equal"] Optional error message.
+ */
+export function assertEqualMarkup( actual, expected, message = 'Expected two markup strings to be equal' ) {
+	if ( actual != expected ) {
+		throw new AssertionError( message, {
+			actual: formatMarkup( actual ),
+			expected: formatMarkup( expected ),
+			showDiff: true
+		} );
+	}
+}
+
+const TEXT_TAG_PLACEHOLDER = 'span data-cke="true"';
+const TEXT_TAG_PLACEHOLDER_REGEXP = new RegExp( TEXT_TAG_PLACEHOLDER, 'g' );
+
+function formatMarkup( string ) {
+	const htmlSafeString = string.replace( /\$text/g, TEXT_TAG_PLACEHOLDER );
+
+	const beautifiedMarkup = html_beautify( htmlSafeString, {
+		indent_size: 2,
+		space_in_empty_paren: true
+	} );
+
+	return beautifiedMarkup.replace( TEXT_TAG_PLACEHOLDER_REGEXP, '$text' );
+}