Skip to content

Commit b78708f

Browse files
authored
Visual diff: check for rootSelector before making request API (#561)
Closes #521
1 parent 1abfe48 commit b78708f

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/docdiff.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,13 @@ export class DocDiffElement extends LitElement {
147147
}
148148

149149
compare() {
150-
let promiseData;
150+
// First check the root selector is in the current body
151+
if (document.querySelector(this.rootSelector) === null) {
152+
console.error("Element not found in current document.");
153+
return;
154+
}
151155

156+
let promiseData;
152157
if (this.cachedRemoteResponse !== null) {
153158
promiseData = Promise.resolve(this.cachedRemoteResponse);
154159
} else {
@@ -186,8 +191,8 @@ export class DocDiffElement extends LitElement {
186191
);
187192
const newBody = document.querySelector(this.rootSelector);
188193

189-
if (oldBody == null || newBody == null) {
190-
throw new Error("Element not found in both documents.");
194+
if (oldBody === null) {
195+
throw new Error("Element not found in base document.");
191196
}
192197

193198
// Depending on the context, visualDomDiff function is found under a different path.

tests/docdiff.test.html

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,25 @@
6868
const content = document.querySelector("main");
6969
await expect(content).dom.to.equalSnapshot();
7070
});
71+
72+
it("check root selector is in current document before making request", async () => {
73+
config.addons.options.root_selector = "#non-existent-id";
74+
75+
const matchMockedUrl = new RegExp(`.+`, "g");
76+
server.respondWith("GET", matchMockedUrl, [200, {}, "{}"]);
77+
78+
const addon = new docdiff.DocDiffAddon(config);
79+
const element = document.querySelector("readthedocs-docdiff");
80+
81+
const event = new CustomEvent(
82+
EVENT_READTHEDOCS_DOCDIFF_ADDED_REMOVED_SHOW,
83+
);
84+
document.dispatchEvent(event);
85+
86+
await elementUpdated(element);
87+
// The request shouldn't be done because the root selector is not found in the current document.
88+
expect(server.requests).to.have.length(0);
89+
});
7190
});
7291
});
7392
</script>

0 commit comments

Comments
 (0)