【问题标题】:Cypress - extract value from XML responseCypress - 从 XML 响应中提取值
【发布时间】:2021-12-30 16:23:54
【问题描述】:

在使用赛普拉斯发出 API 请求时,我在从 XML 响应中检索值时遇到问题。 API 返回 200,我可以在浏览器控制台中看到响应正文,正如预期的那样。

在网上大量研究后,我尝试了以下方法,但是返回的“价格”值未定义。

非常感谢您的指导。

/// <reference types="cypress" />

it('Submit test', () => {
    cy
      .readFile('../fixtures/test1.xml')
      .then(fetchXML)
      .then(responseFromXML  => {
          expect(responseFromXML.status).to.eq(200)

      const parser = new DOMParser();
      const xmlDOM = parser.parseFromString(responseFromXML,"text/xml");
      const value = xmlDOM.getElementsByTagName("Price")[0];
      console.log("Extracted value is "+value)
      })
  
    function fetchXML(xml_body) {
      return cy.request({
        url: Cypress.env('test_endpoint'),
        method: 'POST',
        body: xml_body,
        headers: {
          'Content-Type': 'application/xml',
        },
      })
  }
})

请参阅下面的示例 XML 响应。我怀疑问题出在线路上

const value = xmlDOM.getElementsByTagName("Price")[0];

XML 响应:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP:Body>
        <tns:CreateV2ResponseParameter xmlns:tns="http://ws.xxx.com/wsdl" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <tns:PriceList>
                <tns:PriceDetails>
                    <tns:Price>211</tns:Price>
                </tns:PriceDetails>
            </tns:PriceList>
        </tns:CreateV2ResponseParameter>
    </SOAP:Body>
</SOAP:Envelope>

【问题讨论】:

    标签: javascript xml cypress


    【解决方案1】:

    您在这里向解析器传递了错误的值:

    parser.parseFromString(responseFromXML,"text/xml");
    

    应该是responseFromXML.body:

    parser.parseFromString(responseFromXML.body,"text/xml");
    

    【讨论】:

    • 感谢您的建议。我确实尝试了建议的解决方案,但价格仍然未定义。我怀疑问题出在 line const value = xmlDOM.getElementsByTagName("Price")[0];我在上面添加了一个示例 XML 响应。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2016-01-03
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    相关资源
    最近更新 更多