Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lesson 4: Topic 5 #3

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cypress.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ const { defineConfig } = require("cypress");

module.exports = defineConfig({
e2e: {
chromeWebSecurity: false,
supportFile: 'cypress/support/commands.js',
specPattern: 'cypress/integration/**/*.spec.js',
setupNodeEvents(on, config) {
// implement node event listeners here
},
Expand Down
12 changes: 12 additions & 0 deletions cypress/fixtures/adBlockerUrls.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"blockAds": "https://pagead2.googlesyndication.com/**",
"blockGpt": "https://www.googletagservices.com/tag/js/gpt.js",
"blockGtm": "https://www.googletagmanager.com/gtm.js?id=GTM-MX8DD4S",
"blockAdPlus": "https://cdn.ad.plus/player/adplus.js",
"blockBacktrace": "https://events.backtrace.io/**",
"blockGif": "**/*.gif",
"blockUserMatch": "**/usermatch.gif**",
"blockMerge": "**/merge**",
"blockScripts": "**/*.js"
}

36 changes: 36 additions & 0 deletions cypress/fixtures/credentials.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"users": {
"standardUser": {
"username": "standard_user",
"password": "secret_sauce"
},
"lockedOutUser": {
"username": "locked_out_user",
"password": "secret_sauce"
},
"problemUser": {
"username": "problem_user",
"password": "secret_sauce"
},
"performanceGlitchUser": {
"username": "performance_glitch_user",
"password": "secret_sauce"
},
"invalidUser": {
"username": "invalid_user",
"password": "secret_sauce"
},
"noPassword": {
"username": "standard_user",
"password": ""
},
"invalidPassword": {
"username": "standard_user",
"password": "invalid_password"
},
"noUsername": {
"username": "",
"password": "secret_sauce"
}
}
}
41 changes: 41 additions & 0 deletions cypress/integration/alerts.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
describe('Alerts Handling on DEMOQA', () => {
beforeEach(() => {
cy.visitWithAdBlocker('https://demoqa.com/alerts');
cy.clock();
});

it('tests the [Alert] button which shows an alert box', () => {
cy.on('window:alert', (text) => expect(text).to.contain('You clicked a button'));
cy.get('#alertButton').click();
});

it('ensures the [Timer Alert] button triggers after exactly 5 seconds', () => {
cy.on('window:alert', (text) => expect(text).to.equal('This alert appeared after 5 seconds'));
cy.get('#timerAlertButton').click();
cy.tick(5000); // Simulate passing of 5 seconds
});

it('accepts a confirm alert and verifies actions taken on confirmation', () => {
cy.on('window:confirm', (str) => {
expect(str).to.eq('Do you confirm action?');
return true;
});
cy.get('#confirmButton').click();
cy.get('#confirmResult').should('contain', 'You selected Ok');
});

it('cancels a confirm alert and verifies actions taken on cancellation', () => {
cy.on('window:confirm', (str) => {
expect(str).to.eq('Do you confirm action?');
return false;
});
cy.get('#confirmButton').click();
cy.get('#confirmResult').should('contain', 'You selected Cancel');
});

it('accepts a prompt alert and verifies actions taken on confirmation', () => {
cy.window().then((win) => cy.stub(win, 'prompt').returns('Cypress Tester'));
cy.get('#promtButton').click();
cy.get('#promptResult').should('contain', 'You entered Cypress Tester');
});
});
21 changes: 21 additions & 0 deletions cypress/integration/frames.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
describe('Frames Handling on DEMOQA', () => {
beforeEach(() => {
cy.visitWithAdBlocker('https://demoqa.com/frames');
});

const verifyFrameContentAndSize = (frameId, expectedWidth, expectedHeight, expectedText) => {
it(`verifies content and dimensions within ${frameId}`, () => {
cy.get(frameId)
.should('have.attr', 'width', expectedWidth)
.and('have.attr', 'height', expectedHeight);

cy.frameLoaded(frameId);
cy.iframe(frameId).within(() => {
cy.get('h1#sampleHeading').should('have.text', expectedText);
});
});
};

verifyFrameContentAndSize('#frame1', '500px', '350px', 'This is a sample page');
verifyFrameContentAndSize('#frame2', '100px', '100px', 'This is a sample page');
});
42 changes: 42 additions & 0 deletions cypress/integration/sauce_demo.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// saucedemo_tests.cy.js
describe('Sauce Demo Tests', () => {
beforeEach(() => {
// Visits the Sauce Demo website before each test
cy.visitWithAdBlocker('https://www.saucedemo.com');
});

it('TC_1: Successfully logs in as a standard user', () => {
cy.loginWithFixture('standardUser');
cy.get('.inventory_list').should('be.visible');
});

it('TC_2: Fails to log in with invalid credentials', () => {
cy.loginWithFixture('invalidPassword');
cy.log('Attempted login with in with invalid password');
cy.get('.error-message-container').then((elem) => {
console.log('Error message element:', elem);
}).should('be.visible');
});

it('TC_3: Navigates through product pages', () => {
cy.loginWithFixture('standardUser');
cy.get('.inventory_item_name').first().click();
cy.get('.inventory_details').should('be.visible');
cy.go('back');
cy.get('.inventory_list').should('be.visible');
});

it('TC_4: Adds an item to the cart', () => {
cy.loginWithFixture('standardUser');
cy.get('.btn_inventory').first().click();
cy.get('.shopping_cart_link').click();
cy.get('.cart_list').should('be.visible');
});

it('TC_5: Adds all items and completes checkout', () => {
cy.loginWithFixture('standardUser');
cy.addAllItemsToCart();
cy.completeCheckout('John', 'Dow', '12345');
cy.get('.complete-header').should('be.visible');
});
});
103 changes: 78 additions & 25 deletions cypress/support/commands.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,78 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
import 'cypress-iframe';

// Helper function to log and throw errors
function logAndThrow(message) {
cy.log(message);
throw new Error(message);
}

// Custom command to visit a URL with ad blockers enabled
Cypress.Commands.add('visitWithAdBlocker', (url) => {
cy.fixture('adBlockerUrls').then(urls => {
try {
Object.entries(urls).forEach(([key, value]) => {
cy.intercept(value, {
statusCode: key === 'blockScripts' ? undefined : 200,
body: key === 'blockScripts' ? undefined : '',
onResponse: key === 'blockScripts' ? (req) => {
if (req.url.includes('google') || req.url.includes('adsbygoogle')) {
req.destroy();
}
} : undefined,
log: false
}).as(key);
});
cy.visit(url).then(() => cy.log('Visited with ad blockers set up successfully.'));
} catch (error) {
logAndThrow(`Ad Blocker setup error: ${error.message}`);
}
});
});

// Custom command for logging into a site
Cypress.Commands.add('login', (username, password) => {
cy.get('[data-test="username"]').type(username, { log: false }).should('have.value', username);
cy.get('[data-test="password"]').type(password, { log: false }).should('have.value', password);
cy.get('#login-button').click();
});

// Custom command to login with a user type from a fixture
Cypress.Commands.add('loginWithFixture', (userType) => {
cy.fixture('credentials').then(credentials => {
const user = credentials.users[userType];
if (!user) logAndThrow('User type not found in fixture');
cy.login(user.username, user.password);
});
});

// Custom command to add an item to the cart by name
Cypress.Commands.add('addItemToCartByName', (itemName) => {
cy.contains('.inventory_item_name', itemName).parents('.inventory_item').within(() => {
cy.get('.btn_inventory').click().should('have.class', 'btn_inventory');
});
});

// Custom command to add all items to the cart
Cypress.Commands.add('addAllItemsToCart', () => {
cy.get('.inventory_item').each(element => {
cy.wrap(element).find('.btn_inventory').click();
});
});

// Custom command to complete the checkout process
Cypress.Commands.add('completeCheckout', (firstName, lastName, zipCode) => {
cy.get('.shopping_cart_link').click();
cy.get('.checkout_button').click();
cy.get('#first-name').type(firstName);
cy.get('#last-name').type(lastName);
cy.get('#postal-code').type(zipCode);
cy.get('.btn_primary.cart_button').click();
cy.get('.btn_action.cart_button').click(); // This clicks the final 'Finish' button on the checkout page
});

// Overwriting the 'visit' command to always disable the cache
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
const noCacheStr = `_noCache=${Math.random()}`;
url = url.includes('?') ? `${url}&${noCacheStr}` : `${url}?${noCacheStr}`;
return originalFn(url, options);
});
21 changes: 1 addition & 20 deletions cypress/support/e2e.js
Original file line number Diff line number Diff line change
@@ -1,20 +1 @@
// ***********************************************************
// This example support/e2e.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')
import './commands'
20 changes: 20 additions & 0 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions node_modules/@types/cypress/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions node_modules/@types/cypress/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions node_modules/@types/cypress/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/cypress-iframe/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading