Skip to content

Commit

Permalink
#145: Better error message when calling innerText or innerXml on …
Browse files Browse the repository at this point in the history
…nodes without children.
  • Loading branch information
renggli committed May 25, 2022
1 parent b21ca01 commit 193576e
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
4 changes: 4 additions & 0 deletions lib/src/xml/mixins/has_text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ mixin XmlHasText implements XmlChildrenBase {

/// Replaces the children of this node with text contents.
set innerText(String value) {
if (this is! XmlHasChildren) {
throw UnsupportedError(
'${(this as XmlNode).nodeType} cannot have child nodes.');
}
children.clear();
if (value.isNotEmpty) {
children.add(XmlText(value));
Expand Down
14 changes: 11 additions & 3 deletions lib/src/xml/mixins/has_xml.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import '../nodes/document_fragment.dart';
import '../nodes/node.dart';
import 'has_children.dart';
import 'has_parent.dart';
import 'has_writer.dart';
Expand All @@ -15,7 +16,14 @@ mixin XmlHasXml implements XmlChildrenBase, XmlParentBase, XmlHasWriter {
String get innerXml => children.map((node) => node.toXmlString()).join();

/// Replaces the markup representing the child nodes of this node.
set innerXml(String value) => children
..clear()
..add(XmlDocumentFragment.parse(value));
set innerXml(String value) {
if (this is! XmlHasChildren) {
throw UnsupportedError(
'${(this as XmlNode).nodeType} cannot have child nodes.');
}
children.clear();
if (value.isNotEmpty) {
children.add(XmlDocumentFragment.parse(value));
}
}
}
18 changes: 18 additions & 0 deletions test/mutate_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,15 @@ void main() {
},
'<element/>',
);
throwingTest(
'unsupported text node',
'<element>contents</element>',
(node) {
expect(node.firstChild, isA<XmlText>());
node.firstChild!.innerText = 'error';
},
throwsUnsupportedError,
);
});
group('innerXml', () {
mutatingTest(
Expand All @@ -277,6 +286,15 @@ void main() {
},
'<element/>',
);
throwingTest(
'unsupported text node',
'<element>contents</element>',
(node) {
expect(node.firstChild, isA<XmlText>());
node.firstChild!.innerXml = 'error';
},
throwsUnsupportedError,
);
});
group('outerXml', () {
mutatingTest(
Expand Down

0 comments on commit 193576e

Please sign in to comment.