I tried writing a unit test for one of our classes. It makes use of the DOMParser to access some XML attributes fetched from an endpoint.
The fetchXML part looks like this:
export async function fetchXML(url: string): Promise<Element> {
const req = await fetch(url, { headers: { "content-type": "application/xml" } })
const xml = await req.text()
return new DOMParser().parseFromString(xml, "application/xml").documentElement
}
(Edit: As Quentin pointed out: the get request contains "content-type" header and doesn't make sense. This code is untouched by me though and still works as expected, content-type is just ignored, and the returned response is of the correct format as far as I can tell. The problem somehow occurs during parsing)
Now I tried mocking the network request and return the exact same xml string in my test as I found in the application and expected the further process to be the same, but it seems like it is parsed differently(?) and the result is an empty Document object.
How can I reproduce/ensure that my mock is the same as in the real application? I can not even really tell what could be difference, other than the functionality of "parseFromString", which seems not to make much sense to me..
The tested class will search for querySelectors in the returned document and process their content further.
I also tried analyzing the parsed object in VS Code debugger but all attributes are kind of convoluted due to vues (?) proxy wrappers I think, making it relatively hard to compare. As far as I can tell are the objects not the same, but it's hard to ensure.
The application environment is a Vue3/Vite project and we use vitest. I am comparing the dev mode application with the corresponding test.
I pasted a minimal example here, which works, but if i run the exact same code in a test.spec.ts file it breaks with a TypeError: Cannot read properties of undefined (reading 'getAttribute')
https://codesandbox.io/s/domparser-example-y3v8eg
TL;DR:
I tried reproducing the output of new DOMParser().parseFromString(xml, "application/xml")
as used in my application in a test/spec file (as far as I can tell) identical input but different results. The result is supposed to contain querySelectors for "snapshot" but in test this is not the case and thus, the class throws and error (as expected if there would be no selectors).
The reason for my test to break was that the mocked XML response contained extensions that were not properly parsed (i just copy pasted a real response). I removed the extensions from the mock response' attributes and then the tests passed.