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

Viewed 61

I want to check every <script> tag in an HTML document using Cypress to make sure the src attribute matches the string '^js'.

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

matches

<script src="somejsfile.js">

does not match.

I've tried

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

but src is always undefined.

1 Answers

There's some mods going on during page visit (as you noted elsewhere), so the trick is to cy.request() the page.

Unfortunately with cy.request() the page isn't attached to the DOM that Cypress wants to run commands against, so you can't query with Cypress commands but native queries still work (and are sufficient because there's nothing async going on).

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/))
  })
Related