Reputation: 333
The test objective is to confirm that an uploaded images 'src' attribute changes if a user uploads a new image, meaning the image has changed.
I've tried to use a couple approaches, outlined below.
First Approach
cy.get('.img').then($img => {
//store the src
const source = $('img').attr('src');
/**
* File drop 2mb jpg
*/
cy.fixture(Cypress.env("JPG_2MB_ASSET"), "base64").then(fileContent => {
cy.get(".dropzone").upload(
{
fileContent,
fileName: "sampleimage.jpg",
mimeType: "image/jpeg"
},
{ subjectType: "drag-n-drop" }
);
});
cy.wait(16000);
cy.get('img')
.attr('src')
.should($src2 => {
expect($src2).not.to.eq(source);
});
Second Approach
//store the src
const source = $img.attr('src')
/**
* File drop 2mb jpg
*/
cy.fixture(Cypress.env("JPG_2MB"), "base64").then(fileContent => {
cy.get(".dropzone").upload(
{
fileContent,
fileName: "sampleimage.jpg",
mimeType: "image/jpeg"
},
{ subjectType: "drag-n-drop" }
);
});
cy.wait(16000);
cy.get("img").attr('src').should(($src2) => {
expect($src2).not.to.eq(source)
Third Approach
cy.get("img")
.attr("src")
.then($src1 => {
/**
* File drop 2mb jpg
*/
cy.fixture(Cypress.env("JPG_2MB"), "base64").then(fileContent => {
cy.get(".dropzone").upload(
{
fileContent,
fileName: "sampleimage.jpg",
mimeType: "image/jpeg"
},
{ subjectType: "drag-n-drop" }
);
});
cy.wait(16000);
cy.get('img')
.attr('src')
.should($src2 => {
expect($src2).not.to.eq($src1);
});
The uploads work great, but the comparison of the src does not.
First & Second Approach
Expected- it stores the first image's src as the const source
, and it drops a 2mb jpg. It then compares the 2nd image's src to the first and confirm they are different.
Result- ReferenceError: $ is not defined
Third Approach
Expected- It stores the first src as $src1
, and then compares it to the second src, $src2
Result- cy.get(...).attr is not a function
Upvotes: 4
Views: 7426
Reputation: 333
After a plentitude of being angry at my keyboard, I have found the winning solution.
Using invoke
you can store the value of an attr like src
, as shown here:
https://docs.cypress.io/api/commands/invoke.html#Arguments-are-automatically-forwarded-to-the-function
So, after a few tweaks to the above attempts, I found this to work perfectly:
cy.get('.image-root img').invoke('attr', 'src').then((firstSrc) => {
const src1 = firstSrc
/**
* File drop 2mb jpg
*/
cy.fixture(Cypress.env("JPG_2MB"), "base64").then(fileContent => {
cy.get(".dropzone").upload(
{
fileContent,
fileName: "sampleimage.jpg",
mimeType: "image/jpeg"
},
{ subjectType: "drag-n-drop" }
);
});
cy.wait(16000);
cy.get('.image-root img').invoke('attr', 'src').then((nextSrc) => {
expect(nextSrc).to.not.equal(src1)
});
});
Upvotes: 8