I'm new with cypress and encounter a issue when doing the component test I have a component "Hero" which the props is as below
type HeroProps = {
heading: string;
description: string;
image: {
id: string;
url: string;
alt?: string;
};
};
which the image is from a content management system.
and here's my test
describe('Hero tests', () => {
const prop = {
heading: 'Heading for heading test',
description: 'Description for description test',
image: {
id: 'test id',
url: 'a url from CMS',
alt: 'test'
}
}
it('validate heading', () => {
cy.mount(<Hero {...prop} />);
cy.getByDataID(selectors.heading)
.should('have.text', 'Heading for heading test')
.and('be.visible');
});
});
the test will pass but when I check the result from UI, I saw that the image can not show and the console shows:
GET http://localhost:8080/assets/cms/xxxx/xxx.png 404 (Not Found)
did anyone know where I may do wrong? Thank you!
One way to handle this is to intercept the request and supply the image from fixtures.
That way seems easiest as you don't have to worry about where the image is coming from.
In the following test I use the naturalWidth
property of the <img>
element to assert that the image has actually loaded.
const prop = {
heading: 'Heading for heading test',
description: 'Description for description test',
image: {
id: 'test id',
url: '../../assets/cms/cypress.png',
alt: 'test'
}
}
cy.intercept(/cms/, { fixture: 'cypress.png' }).as('loadImage')
cy.mount(<Hero {...prop} />)
cy.wait('@loadImage')
cy.get('img')
.then($el => {
const element = $el[0]
const width = element.naturalWidth
return width
})
.should('be.gt', 0)
// OR
cy.get('img')
.its('0.naturalWidth')
.should('be.gt', 0)