Cypress interview questions
16 questions with answers. 151 open jobs in India ask for Cypress.
Should I use both Cypress and Jest together?
short answer: It's very common to use Jest and Cypress in the same codebase.
Unit, Integration, or E2E tests
With component Libraries like Vue and React, the line between integration and unit tests can get a bit fuzzy. We can even use the same tools(Jest & Cypress)for both cases, which makes things even more confusing. I recommend that you aim to test "user stories" or, in other words, make sure that users can always perform key actions. For example:
- Can the user fill and submit a form?
- Can the user add products to the cart?
- Does the hamburger menu respond to clicks?
Some of these tests will involve one component, others will involve two and some will require the entire application. I prefer writing smaller tests(unit and integration) using Jest and testing library because of the quick feedback loop. I get to develop and run my tests at, almost, the same time.
Eventually, you'll run into cases that involve so many moving parts(components) that using Jest is not an option. This is where Cypress shines, it's great for testing your end-to-end workflows.
From Stack Overflow: asked by norr, answered by randyjp (CC BY-SA 4.0)
Why is Cypress saying my element is detached after just running a get command?
This could be bad advice, but can you try the following?
cy.findAllByRole('rowheader').eq(2).click({force: true})From Stack Overflow: asked by Gwynn, answered by Ε Г И І И О (CC BY-SA 4.0)
Is there any way to run parallel cypress tests on local machine, for example 5 streams
Technically, it's possible. Cypress does not recommend it since running multiple cypress instances on the same machine consumes lots of resources (CPU over all) and it slows down the entire machine performances with useless results.
Anyway if you have limited resources and you cannot use the official dashboard or you don't have more than one CI server available, you can run your test on a single machine launching cypress run multiple times dividing your test suite in multiple folders.
I've created a npm library called
cypress-parallel(https://github.com/tnicola/cypress-parallel) that (after the first run), balances and splits the test suite in multiple subsets, based on the tests run history and for each subset it launches a Cypress command. It also collect the results from all the specs file, logging them at the end of the execution. In terms of performances, it seems that with 2 processes you can improve your overall tests execution time time up to 40%.From Stack Overflow: asked by Lev Boichenko, answered by Nicola Tommasi (CC BY-SA 4.0)
Should e2e tests persist data in real databases?
I'm currently working at a large well-known company on our test tools and frameworks team. So while I'm no expert, it is something that's part of my job. I'm going to be talking specifically about web testing. Testing is somewhat different for native apps like iOS and Android and I'm not super familiar with those aspects.
The terminology between e2e (end to end) and integration tests is somewhat interchangeable, while unit tests have a more specific definition.
Generally e2e/integration tests should be runnable in dev and production environments. Depending on your setup, your dev environment is probably using some semi-frequently updated snapshot of your production db. In other cases, your local environment may be hitting the actual production db. There are pros/cons to both approaches, but it largely depends on the scale of your company or project. For example, if you're at a large company with dedicated teams you can see many changes a day hitting production databases vs a small team where a weekly snapshot of the prod db is probably good enough for testing locally. i At the base level, all integration tests should be treated as real. When dealing with web apps there are lots of other factors we have to take into account like different web browsers, network activity / availability, etc. So mocking out data for api calls would allow for super fast testing, but then adds another level of complexity with making sure the mocks stay up to date with the real-world database.
Running integration tests locally should more or less be doing the same thing against your dev server that they will be doing against staging and production. With the exception of having the app detecting whether its running in a dev, staging, or production environment to switch out URL's and various credentials, the app should be expected to behave exactly the same way.
In regards to your question about authentication, the answer is yes. Lets look at 2 examples that show different considerations.
Suppose your project is very small. You create some real accounts on production and your db gets snapshotted weekly for use in your local dev environment. You just run your integration tests with one or more of those users as needed. Since the local tests are only hitting your local db, you don't need to worry about the data being generated since it won't affect production. Other engineers on your team can use the same user(s) and not worry about it. If one engineer makes some changes to the db schema, ORM, etc then everyone just gets a new copy of the db snapshot and continues working.
Now for the other extreme. Suppose your project is very big. Millions of users and hundreds of employees all collectively making changes to the codebase and db every day. There are all kinds of ways that infrastructures are setup to handle various engineering tasks. There's too much data and the db changes too often to make using local snapshots feasible. At this scale, you're probably doing continuous integration and running your tests on every commit. You want to do that so that incoming changes don't make it to production and cause major problems. You're probably running your local dev environments against either a constantly updated staging database, or perhaps even against your production db itself. (Try planning for the staging db as it avoids a lot of other problems.)
Now, having just a small set of dedicated test users starts to be a problem. Tests are running all the time, both automated and by dozens of engineers all working on their own bits of work. Since the staging db is probably shared, you easily start getting weird conflicts as the same test user is doing all kinds of things and starts causing tests to fail. A good solution I've seen for this is a kind of test account checkout server. You create say 100 or 1000 (or more) test user accounts. When your integration tests run, they literally check out a test user account from the server. When the tests are done, the integration tests clean up whatever changes they made on that user and tell the checkout server that the user is free again. Then it randomly gets checked out by someone/something else and the cycle continues.
So the take aways that related directly to your question:
Read the rest at the sourceFrom Stack Overflow: asked by Daniel Cortes, answered by Geuis (CC BY-SA 4.0)
Using Cypress, how to test if element does not exist?
Well this seems to work, so it tells me I have some more to learn about .should()
cy.get('.check-box-sub-text').should('not.exist');From Stack Overflow: asked by Maccurt, answered by Maccurt (CC BY-SA 3.0)
How can I run just one test with Cypress?
to run only one file
cypress run --spec path/to/file.spec.jsor using glob patterns:
cypress run --spec 'path/to/files/*.spec.js'Note: you need to wrap your glob patterns in single quotes to avoid shell expansion!
to run only one test in a file
You can use a
.onlyas described in the Cypress docsit.only('only run this one', () => { // similarly use it.skip(...) to skip a test }) it('not this one', () => { })Also, you can do the same with
describeandcontextblocksedit:
there's also a nice
VSCodeextension to make adding/removing.only's easier with keyboard shortcuts. It's called Test Utils (install withext install chrisbreiding.test-utils). It works with js, coffee, and typescript:From Stack Overflow: asked by kuceb, answered by kuceb (CC BY-SA 4.0)
In Cypress how to count a selection of items and get the length?
Found a solution, This works to check a count of items:
cy.get('.datatable').find('tr').should('have.length', 4)This does not work with the
Cypress.$()method of notation.Reference: https://docs.cypress.io/guides/references/assertions.html#Length
From Stack Overflow: asked by Katharine Osborne, answered by Katharine Osborne (CC BY-SA 3.0)
Cypress causing type errors in jest assertions
Anyone facing this problem in the github issue "New Cypress 10 global TypeScript type conflicts with Jest expect" has a workaround
Fix issue by exluding
./cypress.config.tsin yourtsconfig.json"exclude": [ "./cypress.config.ts", //other exclusions that may help https://github.com/cypress-io/cypress/issues/22059#issuecomment-1428298264 "node_modules", "cypress", "**/*.cy.tsx" ]From cypress developer:
We didn't change our globals very much for v10. For all the cases I reproduced, it was fixed by adding ./cypress.config.ts to the tsconfig.exclude property. Since the cypress.config.ts is being included in the type checking, it is loading the cypress types which is polluting your jest tests.
From Stack Overflow: asked by Jonathan Tuzman, answered by Marcus Fonseca (CC BY-SA 4.0)
How to select nth item inside select element in cypress?
Update
As pointed out by @dpstree in the comments, this doesn't answer the original question. Please see more recent answers for a complete solution.
Original
By using eq
cy.get('tbody>tr').eq(0) // Yield first 'tr' in 'tbody' cy.get('ul>li').eq(4) // Yield fifth 'li' in 'ul'From Stack Overflow: asked by JD., answered by Arnaud P (CC BY-SA 4.0)
Pipe Cypress console.log and command log to output
As of Cypress 3.0.0, you can use
cy.task()to access node directly and output to the node console. From the docs:// in test cy.task('log', 'This will be output to the terminal')// in plugins file on('task', { log (message) { console.log(message) return null } })See here for more info.
I don't know of a way to mirror the Cypress logs to the console directly, but this is at least a workable alternative.
From Stack Overflow: asked by Jake He, answered by Joshua Wade (CC BY-SA 4.0)
How to access the value of baseURL in Cypress?
You can use the
Cypress.config()command.To get
baseUrlvalue useCypress.config().baseUrlorCypress.config('baseUrl').From Stack Overflow: asked by David Boydell, answered by Diogo Rocha (CC BY-SA 4.0)
Cypress - how to find by text content?
This code will yield the DOM element with
YOUR_BUTTON_CLASSwhich contains text 'Customer'. Is that what you're looking for?cy.get('.YOUR_BUTTON_CLASS').contains('Customer');Here the documentation for
.containscypress command.From Stack Overflow: asked by Phil, answered by DurkoMatko (CC BY-SA 4.0)
How can I execute code before all tests suite with Cypress?
Short answer: You can write your login command in a
beforehook within thesupportFile(the file that is loaded automatically before your other spec files). Thisbeforehook will run before any of the code in your other test files.Recommendations: That being said, this approach leaves little flexibility for variation in your individual test files that you may want in the future like:
- What if you want to seed the database differently for one test?
- What if you want to log in as a different user with different permissions?
- What if you need to do something in
onBeforeLoadonce?
I would recommend just having the login command in a
beforehook in each individual spec file.I would also further recommend having your login command in a
beforeEachhook to avoid sharing any state in between tests.From Stack Overflow: asked by Florian F, answered by Jennifer Shehane (CC BY-SA 3.0)
How to get the value from an input field into a const and log it?
Using
invoke('val')instead ofinvoke('text')worked for my case.Reminder of the html tag
<input type="text" class="form-control" name="email">Cypress code
cy.get('input[name="email"]') .invoke('val') .then(sometext => cy.log(sometext));From Stack Overflow: asked by soccerway, answered by soccerway (CC BY-SA 4.0)
Cypress get href attribute
The code below should do what you're trying to achieve. There is also an entire recipe with suggestions on how to test links that open in new tabs.
it('Advertise link should refer to Contact page', () => { cy.get('div.footer-nav > ul > li:nth-child(2) > a') .should('have.attr', 'href').and('include', 'contact') .then((href) => { cy.visit(href) }) })I would also suggest reading through the Cypress document on the best ways to assign and work with variables: https://on.cypress.io/variables-and-aliases
From Stack Overflow: asked by Max, answered by Jennifer Shehane (CC BY-SA 4.0)
In Cypress, set a token in localStorage before test
Here's an example of adding a command
cy.login()that you can use in any Cypress test, or put in abeforeEachhook.Cypress.Commands.add('login', () => { cy.request({ method: 'POST', url: 'http://localhost:3000/api/users/login', body: { user: { email: 'jake@jake.jake', password: 'jakejake', } } }) .then((resp) => { window.localStorage.setItem('jwt', resp.body.user.token) }) })Then in your test:
beforeEach(() => { cy.login() })From Stack Overflow: asked by kuceb, answered by kuceb (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA16 questions