Debian Codegraph @

closure-library/closure/goog/testing/dom.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Testing utilities for DOM related tests.
17 *
18 * @author [email protected] (Robby Walker)
19 */
20
21 goog.setTestOnly('goog.testing.dom');
22 goog.provide('goog.testing.dom');
23
24 goog.require('goog.array');
25 goog.require('goog.asserts');
26 goog.require('goog.dom');
27 goog.require('goog.dom.InputType');
28 goog.require('goog.dom.NodeIterator');
29 goog.require('goog.dom.NodeType');
30 goog.require('goog.dom.TagIterator');
31 goog.require('goog.dom.TagName');
32 goog.require('goog.dom.classlist');
33 goog.require('goog.iter');
34 goog.require('goog.object');
35 goog.require('goog.string');
36 goog.require('goog.style');
37 goog.require('goog.testing.asserts');
38 goog.require('goog.userAgent');
39
40 goog.forwardDeclare('goog.dom.AbstractRange');
41
42
43 /**
44 * @return {!Node} A DIV node with a unique ID identifying the
45 * {@code END_TAG_MARKER_}.
46 * @private
47 */
48 goog.testing.dom.createEndTagMarker_ = function() {
49 var marker = goog.dom.createElement(goog.dom.TagName.DIV);
50 marker.id = goog.getUid(marker);
51 return marker;
52 };
53
54
55 /**
56 * A unique object to use as an end tag marker.
57 * @private {!Node}
58 * @const
59 */
60 goog.testing.dom.END_TAG_MARKER_ = goog.testing.dom.createEndTagMarker_();
61
62
63 /**
64 * Tests if the given iterator over nodes matches the given Array of node
65 * descriptors. Throws an error if any match fails.
66 * @param {goog.iter.Iterator} it An iterator over nodes.
67 * @param {Array<Node|number|string>} array Array of node descriptors to match
68 * against. Node descriptors can be any of the following:
69 * Node: Test if the two nodes are equal.
70 * number: Test node.nodeType == number.
71 * string starting with '#': Match the node's id with the text
72 * after "#".
73 * other string: Match the text node's contents.
74 */
75 goog.testing.dom.assertNodesMatch = function(it, array) {
76 var i = 0;
77 goog.iter.forEach(it, function(node) {
78 if (array.length <= i) {
79 fail(
80 'Got more nodes than expected: ' +
81 goog.testing.dom.describeNode_(node));
82 }
83 var expected = array[i];
84
85 if (goog.dom.isNodeLike(expected)) {
86 assertEquals('Nodes should match at position ' + i, expected, node);
87 } else if (goog.isNumber(expected)) {
88 assertEquals(
89 'Node types should match at position ' + i, expected, node.nodeType);
90 } else if (expected.charAt(0) == '#') {
91 assertEquals(
92 'Expected element at position ' + i, goog.dom.NodeType.ELEMENT,
93 node.nodeType);
94 var expectedId = expected.substr(1);
95 assertEquals('IDs should match at position ' + i, expectedId, node.id);
96
97 } else {
98 assertEquals(
99 'Expected text node at position ' + i, goog.dom.NodeType.TEXT,
100 node.nodeType);
101 assertEquals(
102 'Node contents should match at position ' + i, expected,
103 node.nodeValue);
104 }
105
106 i++;
107 });
108
109 assertEquals('Used entire match array', array.length, i);
110 };
111
112
113 /**
114 * Exposes a node as a string.
115 * @param {Node} node A node.
116 * @return {string} A string representation of the node.
117 */
118 goog.testing.dom.exposeNode = function(node) {
119 return (node.tagName || node.nodeValue) + (node.id ? '#' + node.id : '') +
120 ':"' + (node.innerHTML || '') + '"';
121 };
122
123
124 /**
125 * Exposes the nodes of a range wrapper as a string.
126 * @param {goog.dom.AbstractRange} range A range.
127 * @return {string} A string representation of the range.
128 */
129 goog.testing.dom.exposeRange = function(range) {
130 // This is deliberately not implemented as
131 // goog.dom.AbstractRange.prototype.toString, because it is non-authoritative.
132 // Two equivalent ranges may have very different exposeRange values, and
133 // two different ranges may have equal exposeRange values.
134 // (The mapping of ranges to DOM nodes/offsets is a many-to-many mapping).
135 if (!range) {
136 return 'null';
137 }
138 return goog.testing.dom.exposeNode(range.getStartNode()) + ':' +
139 range.getStartOffset() + ' to ' +
140 goog.testing.dom.exposeNode(range.getEndNode()) + ':' +
141 range.getEndOffset();
142 };
143
144
145 /**
146 * Determines if the current user agent matches the specified string. Returns
147 * false if the string does specify at least one user agent but does not match
148 * the running agent.
149 * @param {string} userAgents Space delimited string of user agents.
150 * @return {boolean} Whether the user agent was matched. Also true if no user
151 * agent was listed in the expectation string.
152 * @private
153 */
154 goog.testing.dom.checkUserAgents_ = function(userAgents) {
155 if (goog.string.startsWith(userAgents, '!')) {
156 if (goog.string.contains(userAgents, ' ')) {
157 throw new Error('Only a single negative user agent may be specified');
158 }
159 return !goog.userAgent[userAgents.substr(1)];
160 }
161
162 var agents = userAgents.split(' ');
163 var hasUserAgent = false;
164 for (var i = 0, len = agents.length; i < len; i++) {
165 var cls = agents[i];
166 if (cls in goog.userAgent) {
167 hasUserAgent = true;
168 if (goog.userAgent[cls]) {
169 return true;
170 }
171 }
172 }
173 // If we got here, there was a user agent listed but we didn't match it.
174 return !hasUserAgent;
175 };
176
177
178 /**
179 * Map function that converts end tags to a specific object.
180 * @param {Node} node The node to map.
181 * @param {undefined} ignore Always undefined.
182 * @param {!goog.iter.Iterator<Node>} iterator The iterator.
183 * @return {Node} The resulting iteration item.
184 * @private
185 */
186 goog.testing.dom.endTagMap_ = function(node, ignore, iterator) {
187 return iterator.isEndTag() ? goog.testing.dom.END_TAG_MARKER_ : node;
188 };
189
190
191 /**
192 * Check if the given node is important. A node is important if it is a
193 * non-empty text node, a non-annotated element, or an element annotated to
194 * match on this user agent.
195 * @param {Node} node The node to test.
196 * @return {boolean} Whether this node should be included for iteration.
197 * @private
198 */
199 goog.testing.dom.nodeFilter_ = function(node) {
200 if (node.nodeType == goog.dom.NodeType.TEXT) {
201 // If a node is part of a string of text nodes and it has spaces in it,
202 // we allow it since it's going to affect the merging of nodes done below.
203 if (goog.string.isBreakingWhitespace(node.nodeValue) &&
204 (!node.previousSibling ||
205 node.previousSibling.nodeType != goog.dom.NodeType.TEXT) &&
206 (!node.nextSibling ||
207 node.nextSibling.nodeType != goog.dom.NodeType.TEXT)) {
208 return false;
209 }
210 // Allow optional text to be specified as [[BROWSER1 BROWSER2]]Text
211 var match = node.nodeValue.match(/^\[\[(.+)\]\]/);
212 if (match) {
213 return goog.testing.dom.checkUserAgents_(match[1]);
214 }
215 } else if (node.className && goog.isString(node.className)) {
216 return goog.testing.dom.checkUserAgents_(node.className);
217 }
218 return true;
219 };
220
221
222 /**
223 * Determines the text to match from the given node, removing browser
224 * specification strings.
225 * @param {Node} node The node expected to match.
226 * @return {string} The text, stripped of browser specification strings.
227 * @private
228 */
229 goog.testing.dom.getExpectedText_ = function(node) {
230 // Strip off the browser specifications.
231 return node.nodeValue.match(/^(\[\[.+\]\])?([\s\S]*)/)[2];
232 };
233
234
235 /**
236 * Describes the given node.
237 * @param {Node} node The node to describe.
238 * @return {string} A description of the node.
239 * @private
240 */
241 goog.testing.dom.describeNode_ = function(node) {
242 if (node.nodeType == goog.dom.NodeType.TEXT) {
243 return '[Text: ' + node.nodeValue + ']';
244 } else {
245 return '<' + node.tagName + (node.id ? ' #' + node.id : '') + ' .../>';
246 }
247 };
248
249
250 /**
251 * Assert that the html in {@code actual} is substantially similar to
252 * htmlPattern. This method tests for the same set of styles, for the same
253 * order of nodes, and the presence of attributes. Breaking whitespace nodes
254 * are ignored. Elements can be
255 * annotated with classnames corresponding to keys in goog.userAgent and will be
256 * expected to show up in that user agent and expected not to show up in
257 * others.
258 * @param {string} htmlPattern The pattern to match.
259 * @param {!Node} actual The element to check: its contents are matched
260 * against the HTML pattern.
261 * @param {boolean=} opt_strictAttributes If false, attributes that appear in
262 * htmlPattern must be in actual, but actual can have attributes not
263 * present in htmlPattern. If true, htmlPattern and actual must have the
264 * same set of attributes. Default is false.
265 */
266 goog.testing.dom.assertHtmlContentsMatch = function(
267 htmlPattern, actual, opt_strictAttributes) {
268 var div = goog.dom.createDom(goog.dom.TagName.DIV);
269 div.innerHTML = htmlPattern;
270
271 var errorSuffix =
272 '\nExpected\n' + div.innerHTML + '\nActual\n' + actual.innerHTML;
273
274 var actualIt = goog.iter.filter(
275 goog.iter.map(
276 new goog.dom.TagIterator(actual), goog.testing.dom.endTagMap_),
277 goog.testing.dom.nodeFilter_);
278
279 var expectedIt = goog.iter.filter(
280 new goog.dom.NodeIterator(div), goog.testing.dom.nodeFilter_);
281
282 var actualNode;
283 var preIterated = false;
284 var advanceActualNode = function() {
285 // If the iterator has already been advanced, don't advance it again.
286 if (!preIterated) {
287 actualNode = goog.iter.nextOrValue(actualIt, null);
288 }
289 preIterated = false;
290
291 // Advance the iterator so long as it is return end tags.
292 while (actualNode == goog.testing.dom.END_TAG_MARKER_) {
293 actualNode = goog.iter.nextOrValue(actualIt, null);
294 }
295 };
296
297 // HACK(brenneman): IE has unique ideas about whitespace handling when setting
298 // innerHTML. This results in elision of leading whitespace in the expected
299 // nodes where doing so doesn't affect visible rendering. As a workaround, we
300 // remove the leading whitespace in the actual nodes where necessary.
301 //
302 // The collapsible variable tracks whether we should collapse the whitespace
303 // in the next Text node we encounter.
304 var IE_TEXT_COLLAPSE =
305 goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9');
306
307 var collapsible = true;
308
309 var number = 0;
310 goog.iter.forEach(expectedIt, function(expectedNode) {
311 advanceActualNode();
312 assertNotNull(
313 'Finished actual HTML before finishing expected HTML at ' +
314 'node number ' + number + ': ' +
315 goog.testing.dom.describeNode_(expectedNode) + errorSuffix,
316 actualNode);
317
318 // Do no processing for expectedNode == div.
319 if (expectedNode == div) {
320 return;
321 }
322
323 assertEquals(
324 'Should have the same node type, got ' +
325 goog.testing.dom.describeNode_(actualNode) + ' but expected ' +
326 goog.testing.dom.describeNode_(expectedNode) + '.' + errorSuffix,
327 expectedNode.nodeType, actualNode.nodeType);
328
329 if (expectedNode.nodeType == goog.dom.NodeType.ELEMENT) {
330 var expectedElem = goog.asserts.assertElement(expectedNode);
331 var actualElem = goog.asserts.assertElement(actualNode);
332
333 assertEquals(
334 'Tag names should match' + errorSuffix, expectedElem.tagName,
335 actualElem.tagName);
336 assertObjectEquals(
337 'Should have same styles' + errorSuffix,
338 goog.style.parseStyleAttribute(expectedElem.style.cssText),
339 goog.style.parseStyleAttribute(actualElem.style.cssText));
340 goog.testing.dom.assertAttributesEqual_(
341 errorSuffix, expectedElem, actualElem, !!opt_strictAttributes);
342
343 if (IE_TEXT_COLLAPSE &&
344 goog.style.getCascadedStyle(actualElem, 'display') != 'inline') {
345 // Text may be collapsed after any non-inline element.
346 collapsible = true;
347 }
348 } else {
349 // Concatenate text nodes until we reach a non text node.
350 var actualText = actualNode.nodeValue;
351 preIterated = true;
352 while ((actualNode = goog.iter.nextOrValue(actualIt, null)) &&
353 actualNode.nodeType == goog.dom.NodeType.TEXT) {
354 actualText += actualNode.nodeValue;
355 }
356
357 if (IE_TEXT_COLLAPSE) {
358 // Collapse the leading whitespace, unless the string consists entirely
359 // of whitespace.
360 if (collapsible && !goog.string.isEmptyOrWhitespace(actualText)) {
361 actualText = goog.string.trimLeft(actualText);
362 }
363 // Prepare to collapse whitespace in the next Text node if this one does
364 // not end in a whitespace character.
365 collapsible = /\s$/.test(actualText);
366 }
367
368 var expectedText = goog.testing.dom.getExpectedText_(expectedNode);
369 if ((actualText && !goog.string.isBreakingWhitespace(actualText)) ||
370 (expectedText && !goog.string.isBreakingWhitespace(expectedText))) {
371 var normalizedActual = actualText.replace(/\s+/g, ' ');
372 var normalizedExpected = expectedText.replace(/\s+/g, ' ');
373
374 assertEquals(
375 'Text should match' + errorSuffix, normalizedExpected,
376 normalizedActual);
377 }
378 }
379
380 number++;
381 });
382
383 advanceActualNode();
384 assertNull(
385 'Finished expected HTML before finishing actual HTML' + errorSuffix,
386 goog.iter.nextOrValue(actualIt, null));
387 };
388
389
390 /**
391 * Assert that the html in {@code actual} is substantially similar to
392 * htmlPattern. This method tests for the same set of styles, and for the same
393 * order of nodes. Breaking whitespace nodes are ignored. Elements can be
394 * annotated with classnames corresponding to keys in goog.userAgent and will be
395 * expected to show up in that user agent and expected not to show up in
396 * others.
397 * @param {string} htmlPattern The pattern to match.
398 * @param {string} actual The html to check.
399 * @param {boolean=} opt_strictAttributes If false, attributes that appear in
400 * htmlPattern must be in actual, but actual can have attributes not
401 * present in htmlPattern. If true, htmlPattern and actual must have the
402 * same set of attributes. Default is false.
403 */
404 goog.testing.dom.assertHtmlMatches = function(
405 htmlPattern, actual, opt_strictAttributes) {
406 var div = goog.dom.createDom(goog.dom.TagName.DIV);
407 div.innerHTML = actual;
408
409 goog.testing.dom.assertHtmlContentsMatch(
410 htmlPattern, div, opt_strictAttributes);
411 };
412
413
414 /**
415 * Finds the first text node descendant of root with the given content. Note
416 * that this operates on a text node level, so if text nodes get split this
417 * may not match the user visible text. Using normalize() may help here.
418 * @param {string|RegExp} textOrRegexp The text to find, or a regular
419 * expression to find a match of.
420 * @param {Element} root The element to search in.
421 * @return {?Node} The first text node that matches, or null if none is found.
422 */
423 goog.testing.dom.findTextNode = function(textOrRegexp, root) {
424 var it = new goog.dom.NodeIterator(root);
425 var ret = goog.iter.nextOrValue(goog.iter.filter(it, function(node) {
426 if (node.nodeType == goog.dom.NodeType.TEXT) {
427 if (goog.isString(textOrRegexp)) {
428 return node.nodeValue == textOrRegexp;
429 } else {
430 return !!node.nodeValue.match(textOrRegexp);
431 }
432 } else {
433 return false;
434 }
435 }), null);
436 return ret;
437 };
438
439
440 /**
441 * Assert the end points of a range.
442 *
443 * Notice that "Are two ranges visually identical?" and "Do two ranges have
444 * the same endpoint?" are independent questions. Two visually identical ranges
445 * may have different endpoints. And two ranges with the same endpoints may
446 * be visually different.
447 *
448 * @param {Node} start The expected start node.
449 * @param {number} startOffset The expected start offset.
450 * @param {Node} end The expected end node.
451 * @param {number} endOffset The expected end offset.
452 * @param {goog.dom.AbstractRange} range The actual range.
453 */
454 goog.testing.dom.assertRangeEquals = function(
455 start, startOffset, end, endOffset, range) {
456 assertEquals('Unexpected start node', start, range.getStartNode());
457 assertEquals('Unexpected end node', end, range.getEndNode());
458 assertEquals('Unexpected start offset', startOffset, range.getStartOffset());
459 assertEquals('Unexpected end offset', endOffset, range.getEndOffset());
460 };
461
462
463 /**
464 * Gets the value of a DOM attribute in deterministic way.
465 * @param {!Node} node A node.
466 * @param {string} name Attribute name.
467 * @return {*} Attribute value.
468 * @private
469 */
470 goog.testing.dom.getAttributeValue_ = function(node, name) {
471 // These hacks avoid nondetermistic results in the following cases:
472 // IE7: goog.dom.createElement(goog.dom.TagName.INPUT).height returns
473 // a random number.
474 // FF3: getAttribute('disabled') returns different value for <div disabled="">
475 // and <div disabled="disabled">
476 // WebKit: Two radio buttons with the same name can't be checked at the same
477 // time, even if only one of them is in the document.
478 if (goog.userAgent.WEBKIT && node.tagName == goog.dom.TagName.INPUT &&
479 node['type'] == goog.dom.InputType.RADIO && name == 'checked') {
480 return false;
481 }
482 return goog.isDef(node[name]) &&
483 typeof node.getAttribute(name) != typeof node[name] ?
484 node[name] :
485 node.getAttribute(name);
486 };
487
488
489 /**
490 * Assert that the attributes of two Nodes are the same (ignoring any
491 * instances of the style attribute).
492 * @param {string} errorSuffix String to add to end of error messages.
493 * @param {!Element} expectedElem The element whose attributes we are expecting.
494 * @param {!Element} actualElem The element with the actual attributes.
495 * @param {boolean} strictAttributes If false, attributes that appear in
496 * expectedNode must also be in actualNode, but actualNode can have
497 * attributes not present in expectedNode. If true, expectedNode and
498 * actualNode must have the same set of attributes.
499 * @private
500 */
501 goog.testing.dom.assertAttributesEqual_ = function(
502 errorSuffix, expectedElem, actualElem, strictAttributes) {
503 if (strictAttributes) {
504 goog.testing.dom.compareClassAttribute_(expectedElem, actualElem);
505 }
506
507 var expectedAttributes = expectedElem.attributes;
508 var actualAttributes = actualElem.attributes;
509
510 for (var i = 0, len = expectedAttributes.length; i < len; i++) {
511 var expectedName = expectedAttributes[i].name;
512 var expectedValue =
513 goog.testing.dom.getAttributeValue_(expectedElem, expectedName);
514
515 var actualAttribute = actualAttributes[expectedName];
516 var actualValue =
517 goog.testing.dom.getAttributeValue_(actualElem, expectedName);
518
519 // IE enumerates attribute names in the expected node that are not present,
520 // causing an undefined actualAttribute.
521 if (!expectedValue && !actualValue) {
522 continue;
523 }
524
525 if (expectedName == 'id' && goog.userAgent.IE) {
526 goog.testing.dom.compareIdAttributeForIe_(
527 /** @type {string} */ (expectedValue), actualAttribute,
528 strictAttributes, errorSuffix);
529 continue;
530 }
531
532 if (goog.testing.dom.ignoreAttribute_(expectedName)) {
533 continue;
534 }
535
536 assertNotUndefined(
537 'Expected to find attribute with name ' + expectedName +
538 ', in element ' + goog.testing.dom.describeNode_(actualElem) +
539 errorSuffix,
540 actualAttribute);
541 assertEquals(
542 'Expected attribute ' + expectedName + ' has a different value ' +
543 errorSuffix,
544 String(expectedValue), String(
545 goog.testing.dom.getAttributeValue_(
546 actualElem, actualAttribute.name)));
547 }
548
549 if (strictAttributes) {
550 for (i = 0; i < actualAttributes.length; i++) {
551 var actualName = actualAttributes[i].name;
552 var actualAttribute = actualAttributes.getNamedItem(actualName);
553
554 if (!actualAttribute || goog.testing.dom.ignoreAttribute_(actualName)) {
555 continue;
556 }
557
558 assertNotUndefined(
559 'Unexpected attribute with name ' + actualName + ' in element ' +
560 goog.testing.dom.describeNode_(actualElem) + errorSuffix,
561 expectedAttributes[actualName]);
562 }
563 }
564 };
565
566
567 /**
568 * Assert the class attribute of actualElem is the same as the one in
569 * expectedElem, ignoring classes that are useragents.
570 * @param {!Element} expectedElem The DOM element whose class we expect.
571 * @param {!Element} actualElem The DOM element with the actual class.
572 * @private
573 */
574 goog.testing.dom.compareClassAttribute_ = function(expectedElem, actualElem) {
575 var classes = goog.dom.classlist.get(expectedElem);
576
577 var expectedClasses = [];
578 for (var i = 0, len = classes.length; i < len; i++) {
579 if (!(classes[i] in goog.userAgent)) {
580 expectedClasses.push(classes[i]);
581 }
582 }
583 expectedClasses.sort();
584
585 var actualClasses = goog.array.toArray(goog.dom.classlist.get(actualElem));
586 actualClasses.sort();
587
588 assertArrayEquals(
589 'Expected class was: ' + expectedClasses.join(' ') +
590 ', but actual class was: ' + actualElem.className + ' in node ' +
591 goog.testing.dom.describeNode_(actualElem),
592 expectedClasses, actualClasses);
593 };
594
595
596 /**
597 * Set of attributes IE adds to elements randomly.
598 * @type {Object}
599 * @private
600 */
601 goog.testing.dom.BAD_IE_ATTRIBUTES_ = goog.object.createSet(
602 'methods', 'CHECKED', 'dataFld', 'dataFormatAs', 'dataSrc');
603
604
605 /**
606 * Whether to ignore the attribute.
607 * @param {string} name Name of the attribute.
608 * @return {boolean} True if the attribute should be ignored.
609 * @private
610 */
611 goog.testing.dom.ignoreAttribute_ = function(name) {
612 if (name == 'style' || name == 'class') {
613 return true;
614 }
615 return goog.userAgent.IE && goog.testing.dom.BAD_IE_ATTRIBUTES_[name];
616 };
617
618
619 /**
620 * Compare id attributes for IE. In IE, if an element lacks an id attribute
621 * in the original HTML, the element object will still have such an attribute,
622 * but its value will be the empty string.
623 * @param {string} expectedValue The expected value of the id attribute.
624 * @param {Attr} actualAttribute The actual id attribute.
625 * @param {boolean} strictAttributes Whether strict attribute checking should be
626 * done.
627 * @param {string} errorSuffix String to append to error messages.
628 * @private
629 */
630 goog.testing.dom.compareIdAttributeForIe_ = function(
631 expectedValue, actualAttribute, strictAttributes, errorSuffix) {
632 if (expectedValue === '') {
633 if (strictAttributes) {
634 assertTrue(
635 'Unexpected attribute with name id in element ' + errorSuffix,
636 actualAttribute.value == '');
637 }
638 } else {
639 assertNotUndefined(
640 'Expected to find attribute with name id, in element ' + errorSuffix,
641 actualAttribute);
642 assertNotEquals(
643 'Expected to find attribute with name id, in element ' + errorSuffix,
644 '', actualAttribute.value);
645 assertEquals(
646 'Expected attribute has a different value ' + errorSuffix,
647 expectedValue, actualAttribute.value);
648 }
649 };