如何检查 html 文档中每个脚本标签的 src 属性

How can I check the src attribute of every script tag in an html document

我想使用 Cypress 检查 HTML 文档中的每个 <script> 标记,以确保 src 属性与字符串“^js”相匹配。

<script src="js/somejsfile.js">

匹配

<script src="somejsfile.js">

不匹配。

我试过了

 cy.document()
        .get('head script')
        .each(($match) => {
            cy.wrap($match)
            .invoke('attr', 'src')
            .then((src) => {
                expect(src).to.match(/^js/)
            })
        })

但 src 始终未定义。

页面访问期间有一些修改(如您在其他地方提到的),所以诀窍是 cy.request() 页面。

不幸的是 cy.request() 页面没有附加到赛普拉斯想要 运行 命令反对的 DOM,所以你不能用赛普拉斯命令查询,但原生查询仍然存在工作(并且足够了,因为没有任何异步操作)。

cy.request(my-url)
  .its('body')          // NB the response body, not the body of your page
  .then(content => {

    const parser = new DOMParser();
    const doc = parser.parseFromString(content, 'text/html')

    const scripts = doc.querySelectorAll('head script')    // native query
    const srcs = [...scripts].map(script => script.getAttribute('src'))

    expect(srcs.every(src => src.endsWith('js'))).to.eq(true)
    srcs.forEach(src => expect(src).to.match(/^js/))
  })