utils.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* global console:false */
  6. import AssertionError from 'assertion-error';
  7. import { html_beautify as beautify } from 'js-beautify/js/lib/beautify-html';
  8. import EmitterMixin from '../../src/emittermixin';
  9. import CKEditorError from '../../src/ckeditorerror';
  10. import areConnectedThroughProperties from '../../src/areconnectedthroughproperties';
  11. /**
  12. * Creates an instance inheriting from {@link module:utils/emittermixin~EmitterMixin} with one additional method `observe()`.
  13. * It allows observing changes to attributes in objects being {@link module:utils/observablemixin~Observable observable}.
  14. *
  15. * The `observe()` method accepts:
  16. *
  17. * * `{String} observableName` – Identifier for the observable object. E.g. `"Editable"` when
  18. * you observe one of editor's editables. This name will be displayed on the console.
  19. * * `{utils.Observable observable} – The object to observe.
  20. * * `{Array.<String>} filterNames` – Array of property names to be observed.
  21. *
  22. * Typical usage:
  23. *
  24. * const observer = utils.createObserver();
  25. * observer.observe( 'Editable', editor.editables.current );
  26. *
  27. * // Stop listening (method from the EmitterMixin):
  28. * observer.stopListening();
  29. *
  30. * @returns {Emitter} The observer.
  31. */
  32. export function createObserver() {
  33. const observer = Object.create( EmitterMixin, {
  34. observe: {
  35. value: function observe( observableName, observable, filterNames ) {
  36. observer.listenTo( observable, 'change', ( evt, propertyName, value, oldValue ) => {
  37. if ( !filterNames || filterNames.includes( propertyName ) ) {
  38. console.log( `[Change in ${ observableName }] ${ propertyName } = '${ value }' (was '${ oldValue }')` );
  39. }
  40. } );
  41. return observer;
  42. }
  43. }
  44. } );
  45. return observer;
  46. }
  47. /**
  48. * Checks whether observable properties are properly bound to each other.
  49. *
  50. * Syntax given that observable `A` is bound to observables [`B`, `C`, ...]:
  51. *
  52. * assertBinding( A,
  53. * { initial `A` attributes },
  54. * [
  55. * [ B, { new `B` attributes } ],
  56. * [ C, { new `C` attributes } ],
  57. * ...
  58. * ],
  59. * { `A` attributes after [`B`, 'C', ...] changed }
  60. * );
  61. */
  62. export function assertBinding( observable, stateBefore, data, stateAfter ) {
  63. let key, boundObservable, attrs;
  64. for ( key in stateBefore ) {
  65. expect( observable[ key ] ).to.equal( stateBefore[ key ] );
  66. }
  67. // Change attributes of bound observables.
  68. for ( [ boundObservable, attrs ] of data ) {
  69. for ( key in attrs ) {
  70. if ( !Object.prototype.hasOwnProperty.call( boundObservable, key ) ) {
  71. boundObservable.set( key, attrs[ key ] );
  72. } else {
  73. boundObservable[ key ] = attrs[ key ];
  74. }
  75. }
  76. }
  77. for ( key in stateAfter ) {
  78. expect( observable[ key ] ).to.equal( stateAfter[ key ] );
  79. }
  80. }
  81. /**
  82. * An assertion util to test whether the given function throws error that has correct message,
  83. * data and whether the context of the error and the `editorThatShouldBeFindableFromContext`
  84. * have common props (So the watchdog will be able to find the correct editor instance and restart it).
  85. *
  86. * @param {Function} fn Tested function that should throw a `CKEditorError`.
  87. * @param {RegExp|String} message Expected message of the error.
  88. * @param {*} editorThatShouldBeFindableFromContext An editor instance that should be findable from the error context.
  89. * @param {Object} [data] Error data.
  90. */
  91. export function expectToThrowCKEditorError( fn, message, editorThatShouldBeFindableFromContext, data ) {
  92. let err = null;
  93. try {
  94. fn();
  95. } catch ( _err ) {
  96. err = _err;
  97. assertCKEditorError( err, message, editorThatShouldBeFindableFromContext, data );
  98. }
  99. expect( err ).to.not.equal( null, 'Function did not throw any error' );
  100. }
  101. /**
  102. * An assertion util to test whether a given error has correct message, data and whether the context of the
  103. * error and the `editorThatShouldBeFindableFromContext` have common props (So the watchdog will be able to
  104. * find the correct editor instance and restart it).
  105. *
  106. * @param {module:utils/ckeditorerror~CKEditorError} err The tested error.
  107. * @param {RegExp|String} message Expected message of the error.
  108. * @param {*} [editorThatShouldBeFindableFromContext] An editor instance that should be findable from the error context.
  109. * @param {Object} [data] Error data.
  110. */
  111. export function assertCKEditorError( err, message, editorThatShouldBeFindableFromContext, data ) {
  112. if ( typeof message === 'string' ) {
  113. message = new RegExp( message );
  114. }
  115. expect( message ).to.be.a( 'regexp', 'Error message should be a string or a regexp.' );
  116. expect( err ).to.be.instanceOf( CKEditorError );
  117. expect( err.message ).to.match( message, 'Error message does not match the provided one.' );
  118. // TODO: The `editorThatShouldBeFindableFromContext` is optional but should be required in the future.
  119. if ( editorThatShouldBeFindableFromContext === null ) {
  120. expect( err.context ).to.equal( null, 'Error context was expected to be `null`' );
  121. } else if ( editorThatShouldBeFindableFromContext !== undefined ) {
  122. expect( areConnectedThroughProperties( editorThatShouldBeFindableFromContext, err.context ) )
  123. .to.equal( true, 'Editor cannot be find from the error context' );
  124. }
  125. if ( data ) {
  126. expect( err.data ).to.deep.equal( data );
  127. }
  128. }
  129. /**
  130. * An assertion util test whether two given strings containing markup language are equal.
  131. * Unlike `expect().to.equal()` form Chai assertion library, this util formats the markup before showing a diff.
  132. *
  133. * This util can be used to test HTML strings and string containing serialized model.
  134. *
  135. * // Will throw an error that is handled as assertion error by Chai.
  136. * assertEqualMarkup(
  137. * '<paragraph><$text foo="bar">baz</$text></paragraph>',
  138. * '<paragraph><$text foo="bar">baaz</$text></paragraph>',
  139. * );
  140. *
  141. * @param {String} actual An actual string.
  142. * @param {String} expected An expected string.
  143. * @param {String} [message="Expected two markup strings to be equal"] Optional error message.
  144. */
  145. export function assertEqualMarkup( actual, expected, message = 'Expected markup strings to be equal' ) {
  146. if ( actual != expected ) {
  147. throw new AssertionError( message, {
  148. actual: formatMarkup( actual ),
  149. expected: formatMarkup( expected ),
  150. showDiff: true
  151. } );
  152. }
  153. }
  154. // Renames the $text occurrences as it is not properly formatted by the beautifier - it is tread as a block.
  155. const TEXT_TAG_PLACEHOLDER = 'span data-cke="true"';
  156. const TEXT_TAG_PLACEHOLDER_REGEXP = new RegExp( TEXT_TAG_PLACEHOLDER, 'g' );
  157. function formatMarkup( string ) {
  158. const htmlSafeString = string.replace( /\$text/g, TEXT_TAG_PLACEHOLDER );
  159. const beautifiedMarkup = beautify( htmlSafeString, {
  160. indent_size: 2,
  161. space_in_empty_paren: true
  162. } );
  163. return beautifiedMarkup.replace( TEXT_TAG_PLACEHOLDER_REGEXP, '$text' );
  164. }