SOAP XML query in Cypress test

Viewed 52

I have an XML response I need to parse the userId.

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetUser>
      <m:UserId>123</m:UserId>
    </m:GetUser>
  </soap:Body>
</soap:Envelope>

How do I get data from this in a structured way?

This does not work. Is there a command or addon that can handle XML?

cy.wrap(xml).find('m:UserId')
2 Answers

Presuming it comes from a request response, convert the xml string to a document and query using document.querySelector().

const xml = `<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Body>
    <m:GetUser xmlns:m="https://www.sample.com/users">
      <m:UserId>123</m:UserId>
    </m:GetUser>
  </soap:Body>
</soap:Envelope>`

const parser = new DOMParser();
const doc = parser.parseFromString(xml, "application/xml");
const id = doc.querySelector("UserId").textContent 

expect(id).to.eq('123')

I note the namespace is missing above. Without it the field you seek would not be found. Was that a typo?

Yoy can do something like this:

const xml = `<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetUser>
      <m:UserId>123</m:UserId>
    </m:GetUser>
  </soap:Body>
</soap:Envelope>`

cy.wrap(Cypress.$(xml))
  .then((xml) => xml.filter('soap:Body').find('m:UserId').text())
  .should('eq', '123')
Related