Skip to content

Commit

Permalink
Handle unspecified nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
JLRishe committed Dec 16, 2023
1 parent 3ce4730 commit 35dabde
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
24 changes: 16 additions & 8 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1304,23 +1304,31 @@ describe('xpath', () => {
describe('error handling', () => {
it('should reject unspecified expression', () => {
for (let expr of [null, undefined, '']) {
assert.throws(() => {
xpath.parse(expr);
}, {
message: 'XPath expression unspecified'
assert.throws(() => xpath.parse(expr), {
message: 'XPath expression unspecified',
});
}
});

it('should reject non-nodes', () => {
for (let node of ['<n />', 0, 45, true, false, [], {}]) {
assert.throws(() => {
xpath.parse('/*').select({ node });
}, {
message: 'Context node does not appear to be a valid DOM node.'
assert.throws(() => xpath.parse('/*').select({ node }), {
message: 'Context node does not appear to be a valid DOM node.',
});
}
});

it('should handle unspecified nodes', () => {
assert.throws(
() => xpath.parse('my:field').select(), {
message: 'Context node not found when evaluating XPath step: child::my:field',
});

assert.throws(
() => xpath.parse('/*').select(), {
message: 'Context node not found when determining document root.',
});
})
});

describe('Node type tests', () => {
Expand Down
13 changes: 11 additions & 2 deletions xpath.js
Original file line number Diff line number Diff line change
Expand Up @@ -1855,14 +1855,20 @@ var xpath = (typeof exports === 'undefined') ? {} : exports;
PathExpr.getRoot = function (xpc, nodes) {
var firstNode = nodes[0];

if (firstNode.nodeType === NodeTypes.DOCUMENT_NODE) {
// xpc.virtualRoot could possibly provide a root even if firstNode is null,
// so using a guard here instead of throwing.
if (firstNode && firstNode.nodeType === NodeTypes.DOCUMENT_NODE) {
return firstNode;
}

if (xpc.virtualRoot) {
return xpc.virtualRoot;
}

if (!firstNode) {
throw new Error('Context node not found when determining document root.');
}

var ownerDoc = firstNode.ownerDocument;

if (ownerDoc) {
Expand Down Expand Up @@ -1892,7 +1898,10 @@ var xpath = (typeof exports === 'undefined') ? {} : exports;
};

PathExpr.applyStep = function (step, xpc, node) {
var self = this;
if (!node) {
throw new Error('Context node not found when evaluating XPath step: ' + step);
}

var newNodes = [];
xpc.contextNode = node;

Expand Down

0 comments on commit 35dabde

Please sign in to comment.