Not able to access the element inside the DOM using cypress - cypress

I am testing a website i.e console.internetcomputerservices.com, please refer the below code:
/// <reference types="cypress" />
describe("Basic tests", () => {
before(() => {
cy.visit("https://console.internetcomputerservices.com", {
onBeforeLoad(win) {
win.localStorage.setItem(
"token",
"my-token"
);
},
});
});
it.only("should be able to run test 1", async () => {
cy.viewport(1280, 720)
//Clicks on Creat DApp
cy.contains('Create DApp').click()
//Clicks on Static website
cy.contains('Static Website').click()
//clicks on "Connect with github"
cy.contains('Connect with github').click()
//The origin is changed to github.com inside which following operation takes place
cy.origin('https://github.com', ()=>{
cy.get('input[name="login"]').type('my-email')
cy.get('input[name="password"]').type('my-password')
cy.get('[type="submit"]').click()
cy.get('[href="/settings/installations/29576211"]').click()
cy.contains('Only select repositories').click()
cy.contains('All repositories').click()
cy.get('.js-integrations-install-form-submit.btn-primary.btn.float-left.mr-2').click()
})
//Comes out of github.com back to console.internetcomputerservices.com
//(Expected) cypress will identify the placeholder and type "intro-2"
// but this doesn't happen, cypress doesn't identify any element inside the DOM
cy.get('input[placeholder="Search…"]').type('intro-2')
});
});
When we return back to our home website, i expect that the cypress identifies the placeholder and type in "intro-2", to check that was it particular to placeholder, i realised that cypress is not able to identify any element on DOM.
If you refer the Search bar, i want to access one with placeholder='Search...'
I apologies for poor choice of words, i am beginner in this and not familiar with jargon, I hope you understand my question.

Related

Is there a way to "force" a visit?

I'm using the cy.visit() command but the website i'm visiting (which i don't own) doesn't always fire the load event, although the content itself that i need for testing does appear on the website.
Despite the content appearing, since the load event is not fired sometimes (for some reason which i can't fix since i don't have ownership over this website), the cy.visit() command fails.
Is there a way to "force" it somehow, similar to how we can pass { force: true} for the cy.click() command?
Add the below to your cypress commands file
Cypress.Commands.add('forceVisit', url => {
cy.window().then(win => {
return win.open(url, '_self');
});
});
And in your tests, you can call
cy.forceVisit("www.google.com")
It's hard to simulate the problem, but I think I managed by setting pageLoadTimeout really low (30ms).
You can catch the onLoad fail in an event handler and checking for the page load error message.
I recommend doing it in a beforeEach().
beforeEach(() => {
Cypress.config("pageLoadTimeout", 30) // set this to whatever time length
// you feel is appropriate to start testing
// You'll need to experiment to get this right
// and in CI it will be a lot longer
cy.once('fail', (err) => { // "once" to just catch a single error
const message = err.parsedStack[0].message
if (message.match(/Timed out after waiting `\d+ms` for your remote page to load/)) {
return false
}
throw err // any other error, fail it
})
cy.visit('www.example.com');
})
it('checks the heading of the page', () => {
cy.get('h1').should('have.text', 'Example Domain') // ✅
})
As you can already assume, that is highly discouraged. It also really depends on how it fails and with which errors, but, without any code to reproduce, you may want to try this if you haven't already:
cy.visit('/', {failOnStatusCode: false});
Reference: https://docs.cypress.io/api/commands/visit#Arguments

Cypress: > Cannot call cy.get() outside a running test

i am getting this error when i run a test file. The test file uses methods declared in a page object file, please let me know how this can be fixed.
Error message
Page Object code
cy.get('.more-less-container').then(dropdown => {
if (dropdown.find('.name').contains('More')) {
cy.get('more-less-container').click();
} else {
console.log('folders are in expanded state');
}
});
class Folders {
Archive() {
dropdown();
cy.get('.category-content')
.find('[title="Archive"]')
.click()
.get('.folder-details')
.should('contain.text', 'Archive');
}
Trash() {
dropdown();
cy.get('.category-content')
.find('[title="Trash"]')
.click()
.get('.folder-details')
.should('contain.text', 'Trash');
}
Test code
/// <reference types="cypress" />
import { openFolder } from '../support/page-objects/sidebar/drafts';
describe('Verify mobile app download link redirections', () => {
before(() => {
cy.login();
});
});
it('Needs to open the drafts folder', () => {
openFolder.Drafts();
cy.get('.modal-close').click();
});
Not sure what i'm missing out here.
As I can see the cy.get(...) command (line 1) in your "Page Object code" file is not part of a class, and as such will be executed as soon as cypress is opened (ran), because that's how this support file is supposed to work, it's loaded and executed immediately (which means before any test are actually started). So the solution would be to move that command as part of the Folders class as a utility function, which later on you would explicitly call during your tests.

Cypress how to handle new tab without "target" and "href" attribute?

Note:
Cypress is a great tool for automating. I am new in Cypress world. I really like the way how we can take actions and make assertions on the same line of code.
However, I met a hard problem, that I am not able to process. I am sure that this is handled in some way, but after 2 days of researching (about 6 hours), I'm running out of energy.
Description:
I am trying (learning to use Cypress) to automate this example. I am not able to automate (button) "New Tab" functionality. I don't want to think about how can I solve this 'quest' and how can I automate the other two (buttons) "New WIndow" and "New WIndow Message" functionalities. Here is a screenshot of the HTML document:
My code:
I try to solve this by using the first answer from this topic.
/// <reference types="cypress" />
describe('Example shows how to work with browser windows.', () => {
it('Example shows how to work witn button that opens new tab without "target: _blank" and "href" attributes.', () => {
cy.visit('https://demoqa.com/browser-windows')
cy.window().then(win => {
cy.stub(win, 'open').as('open')
})
cy.xpath('//*[#id="tabButton"]').click()
cy.get('#open').should('have.been.calledOnceWithExactly', '/sample')
})
})
I am not sure what I miss.
Your example is not following the link's code you have provided. I have refactored your code, tested & it's working:
/// <reference types="cypress" />
describe('Example shows how to work with browser windows.', () => {
it('Example shows how to work witn button that opens new tab without "target: _blank" and "href" attributes.', () => {
cy.visit('https://demoqa.com/browser-windows', {
onBeforeLoad(win) {
cy.stub(win, 'open')
}
});
cy.get('#tabButton').click();
cy.window().its('open').should('be.called');
cy.get('#windowButton').click();
cy.window().its('open').should('be.called');
cy.get('#msgWindowButtonWrapper').click();
cy.window().its('open').should('be.called');
});
});
Results:

Cypress - testing a contact form with google recaptcha

How can I test a contact form with google recaptcha ?
I want to test if "We will respond you soon." message appear.
I created my own Cypress command in order to test Google reCAPTCHA
Cypress.Commands.add('solveGoogleReCAPTCHA', () => {
// Wait until the iframe (Google reCAPTCHA) is totally loaded
cy.wait(500);
cy.get('#g-recaptcha *> iframe')
.then($iframe => {
const $body = $iframe.contents().find('body');
cy.wrap($body)
.find('.recaptcha-checkbox-border')
.should('be.visible')
.click();
});
});
I combined this command with the instructions given by Google:
https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do
So, I had to do minor changes to my source code:
export const RECAPTCHA_SITE_KEY: string = window.Cypress
? '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
After some attempts, I came up with this:
Cypress.Commands.add('confirmCaptcha', function () {
cy.get('iframe')
.first()
.then((recaptchaIframe) => {
const body = recaptchaIframe.contents()
cy.wrap(body).find('.recaptcha-checkbox-border').should('be.visible').click()
})
})
Also make sure you have this in your cypress.json file, otherwise iFrames cannot be accessed:
"chromeWebSecurity": false
This works for me, which has no need for a cy.wait(500) or other fixed amount of time, because it uses the cypress implicit wait in its for the iframe contents to load.
cy.get('iframe')
.first()
.its('0.contentDocument.body')
.should('not.be.undefined')
.and('not.be.empty')
.then(cy.wrap)
.find('#recaptcha-anchor')
.should('be.visible')
.click();
This can be added as a custom command as well. It is based off of this blog post: https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/
Cypress has good suggestions on their best practice page: https://docs.cypress.io/guides/references/best-practices.html#Visiting-external-sites
Basically it comes down to this: if it is not your own application, just stub it. Trust the 3th party to test their own page.

How to make sure page loads completely in cypress

I am working in cypress.
Steps to repro
I just visit the login page by cy.visit()-spinner is loading
passed the credentials using type-spinner is still loading
click on submit.-spinner is still loading
its throwing error .. why because the login page XHR calls didnt get completed thats why still we can see spinner loading in top and i tried to click the submit button before it gets loaded,may be because of poor network-telling invalid credentials.
I believe you have to wait for the XHR request to get completed and validate the page load or perform other actions.
Here is a sample,
// Wait for the route aliased as 'getAccount' to respond
cy.server()
cy.route('/accounts/*').as('getAccount')
cy.visit('/accounts/123')
cy.wait('#getAccount').then((xhr) => {
cy.get('#loading-bar').should('not.be.visible')
})
Here is a similar solution which I have previously given - Cypress:Is there any way to check invisibility of an element
You check if the button is present and then click on the button.If
describe('check if button present', function () {
it('check for button using CSS Selector', function () {
cy.visit(url)
let found = false
let count=0
while (!found) {
const nonExistent = Cypress.$('.btn-selector')
if (!nonExistent.length) {
found = false
count=count+1
cy.wait(1000)
if(count==60)
{
found = true
cy.log('Element not found after 60 seconds..Exit from loop!!!')
}
}
else
{
found = true
cy.get('.btn-selector').click()
}
}
})
})

Resources