cy.url() and/or cy.location('href') does not return a string

柔情痞子 提交于 2020-04-15 06:47:10

问题


I have an editor page. When I add any content and click the "Save" button my URL will change, adding a random id in the URL. I want to check if my ID's are changing every time when I click the "Save button".

I save the URL result in variable and want to check it, I do it like this:

const currentURL = cy.url();
cy.get('.editor-toolbar-actions-save').click();
cy.url().should('not.eq', currentURL);

But my currentURL variable's type is not string:

expected http://localhost:8080/editor/37b44d4d-48b7-4d19-b3de-56b38fc9f951 to not equal { Object (chainerId, firstCall) }

How I can use my variable?


回答1:


tl;dr

Cypress commands are async, you have to use then to work with their yields.

const currentURL = null
cy.url().then(url => {
  currentURL = url;
});
cy.get('.editor-toolbar-actions-save').click();
cy.url().should('not.eq', currentURL);

Explanation

A similar question was asked on GitHub, and the official document on aliases explains this phenomenon in great detail:

You cannot assign or work with the return values of any Cypress command. Commands are enqueued and run asynchronously.

The solution is shown too:

To access what each Cypress command yields you use .then().

cy.get('button').then(($btn) => {
  // $btn is the object that the previous
  // command yielded us
})

It is also a good idea to check out the core concepts docs's section on asynchronicity.




回答2:


These commands return a chainable type, not primitive values like strings, so assigning them to variables will require further action to 'extract' the string.

In order to get the url string, you need to do

cy.url().then(urlString => //do whatever)


来源:https://stackoverflow.com/questions/56790303/cy-url-and-or-cy-locationhref-does-not-return-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!