Skip to content

Commit

Permalink
Improve static resource loading recipe (#363)
Browse files Browse the repository at this point in the history
* add example waiting for an image

* update text

* fix returned value

* add using natural height to detect image load
  • Loading branch information
bahmutov authored and jennifer-shehane committed Nov 5, 2019
1 parent 5aea10a commit 4a35c06
Show file tree
Hide file tree
Showing 8 changed files with 150 additions and 51 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Recipe | Description
[Form Interactions](./examples/testing-dom__form-interactions) | Test form elements like input type `range`
[Drag and Drop](./examples/testing-dom__drag-drop) | Use `.trigger()` to test drag and drop
[Shadow DOM](./examples/testing-dom__shadow-dom) | You need to use any of available custom commands
[Waiting for static resource](./examples/testing-dom__wait-for-resource) | Shows how to wait for CSS or any other static resource to load
[Waiting for static resource](./examples/testing-dom__wait-for-resource) | Shows how to wait for CSS, image, or any other static resource to load
[CSV load and table test](./examples/testing-dom__csv-table) | Loads CSV file and compares objects against cells in a table

## Logging in recipes
Expand Down
41 changes: 40 additions & 1 deletion examples/testing-dom__wait-for-resource/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ cy.window().then(win => {
})
```

From the tests, we can call the above code wrapped in a custom command.
From the tests, we can call the above code wrapped in a custom command `cy.waitForResource`.

```js
// cypress/integration/spec.js
Expand All @@ -55,3 +55,42 @@ The custom command `cy.waitForResource` is written directly in the spec file. An
## 3rd party module

The [cypress/integration/spec.js](cypress/integration/spec.js) also includes a test that uses [cypress-wait-until](https://github.com/NoriSte/cypress-wait-until) 3rd party module with custom command `cy.waitUntil` to retry finding the performance entry with expected name.

## Delayed image

The spec file also shows how to ensure that an image has fully loaded.

```js
describe('loading images', () => {
it('waits for the image to load', () => {
cy.visit('/')

// we can wait for the <img> element to appear
// but the image has not been loaded yet.
cy.get('[alt="delayed image"]').should('be.visible')

// Let's wait for the actual image to load
cy.waitForResource('cypress-logo.png')
})
})
```

![Test in action](images/wait-for-image.gif)

Alternatively, we can use `IMG.naturalWidth` or `IMG.naturalHeight` properties which are set when the image loads.

```js
// we can wait for the <img> element to appear
// but the image has not been loaded yet.
cy.get('[alt="delayed image"]')
.should('be.visible')
.and(($img) => {
// "naturalWidth" and "naturalHeight" are set when the image loads
expect(
$img[0].naturalWidth,
'image has natural width'
).to.be.greaterThan(0)
})
```

![Using natural width to detect when image loads](images/natural-width.gif)
2 changes: 1 addition & 1 deletion examples/testing-dom__wait-for-resource/cypress.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"baseUrl": "http://localhost:4500",
"viewportHeight": 200,
"viewportHeight": 600,
"viewportWidth": 300
}
134 changes: 87 additions & 47 deletions examples/testing-dom__wait-for-resource/cypress/integration/spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,69 +40,109 @@ Cypress.Commands.add('waitForResource', (name, options = {}) => {
foundResource = win.performance
.getEntriesByType('resource')
.find((item) => item.name.endsWith(name))

if (!foundResource) {
// resource not found, will try again
return
}

clearInterval(interval)
// let's resolve with the found performance object
// to allow tests to inspect it
resolve(foundResource)
// because cy.log changes the subject, let's resolve the returned promise
// with log + returned actual result
resolve(
cy.log('✅ success').then(() => {
// let's resolve with the found performance object
// to allow tests to inspect it
return foundResource
})
)
}, 100)
})
}
)
})

it('applies app.css styles', () => {
cy.visit('/')
cy.waitForResource('base.css')
cy.waitForResource('app.css')
// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
})
describe('loading style', () => {
it('applies app.css styles', () => {
cy.visit('/')
cy.waitForResource('base.css')
cy.waitForResource('app.css')
// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
})

it('app.css is a tiny resource', () => {
cy.visit('/')
cy.waitForResource('app.css').should((resourceTiming) => {
// there are lots of timing properties in this object
expect(resourceTiming)
.property('entryType')
.to.equal('resource')
expect(resourceTiming, 'the CSS file is very small (in bytes)')
.property('transferSize')
.to.be.lt(300)
expect(resourceTiming, 'loads in less than 150ms')
.property('duration')
.to.be.lt(150)
it('app.css is a tiny resource', () => {
cy.visit('/')
cy.waitForResource('app.css').then((resourceTiming) => {
expect(resourceTiming, 'got resource timing').to.not.be.null

// there are lots of timing properties in this object
expect(resourceTiming)
.property('entryType')
.to.equal('resource')
expect(resourceTiming, 'the CSS file is very small (in bytes)')
.property('transferSize')
.to.be.lt(300)
expect(resourceTiming, 'loads in less than 150ms')
.property('duration')
.to.be.lt(150)
})
})
})

it('waits for multiple resources', () => {
cy.visit('/')
// the "cy.waitForResources" command was written in cypress/support/index.js file
cy.waitForResources('base.css', 'app.css')
// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
})
it('waits for multiple resources', () => {
cy.visit('/')
// the "cy.waitForResources" command was written in cypress/support/index.js file
cy.waitForResources('base.css', 'app.css')
// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
})

it('waits on resource using wait-until 3rd party plugin', () => {
cy.visit('/')

// 3rd party module "cypress-wait-until" is really useful
// for simple conditions like waiting for an item
// @see https://github.com/NoriSte/cypress-wait-until
cy.waitUntil(() =>
cy.window().then((win) =>
win.performance
.getEntriesByType('resource')
// note: ".some(...)" method returns boolean value
// which cypress-wait-until expects
.some((item) => item.name.endsWith('app.css'))
it('waits on resource using wait-until 3rd party plugin', () => {
cy.visit('/')

// 3rd party module "cypress-wait-until" is really useful
// for simple conditions like waiting for an item
// @see https://github.com/NoriSte/cypress-wait-until
cy.waitUntil(() =>
cy.window().then((win) =>
win.performance
.getEntriesByType('resource')
// note: ".some(...)" method returns boolean value
// which cypress-wait-until expects
.some((item) => item.name.endsWith('app.css'))
)
)
)

// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
// red color means the style from "app.css" has been loaded and applied
cy.get('h1', { timeout: 250 }).should('have.css', 'color', 'rgb(255, 0, 0)')
})
})

describe('loading images', () => {
it('waits for the image to load', () => {
cy.visit('/')

// we can wait for the <img> element to appear
// but the image has not been loaded yet.
cy.get('[alt="delayed image"]').should('be.visible')

// Let's wait for the actual image to load
cy.waitForResource('cypress-logo.png')
})

it('waits for the image to have actual dimensions', () => {
cy.visit('/')

// we can wait for the <img> element to appear
// but the image has not been loaded yet.
cy.get('[alt="delayed image"]')
.should('be.visible')
.and(($img) => {
// "naturalWidth" and "naturalHeight" are set when the image loads
expect(
$img[0].naturalWidth,
'image has natural width'
).to.be.greaterThan(0)
})
})
})
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 21 additions & 1 deletion examples/testing-dom__wait-for-resource/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,36 @@
</head>
<body>
<main>
<p>The title below will change its color after the app's style loads.</p>
<h1>Page title</h1>
<p>Below an image will appear after a short delay, first without an image, then the image will load after a delay.</p>
</main>
<script>
// example of a delayed CSS resource
setTimeout(() => {
// now load dynamic style to apply to H1 element
let link = document.createElement('link')
const link = document.createElement('link')
link.rel = 'stylesheet'
link.type = 'text/css'
link.href = 'app.css'
document.head.appendChild(link)
}, 1000)

// example of a delayed image element
// 1. it creates an IMG element after a delay
// 2. it loads the actual image after a delay
setTimeout(() => {
const image = document.createElement('img')
image.alt = 'delayed image'
image.width = '120'
image.height = '40'

// load the actual image after another short delay
setTimeout(() => {
image.src = 'cypress-logo.png'
}, 1000)

document.body.appendChild(image)
}, 1500)
</script>
</body>

0 comments on commit 4a35c06

Please sign in to comment.