Fakenick
Fakenick

Reputation: 103

Overriding window as function call context

I am writing test cases in cypress, and every line I write refers to the cy object. A sample of my test code looks something like this:

it('does stuff', () => {
    cy.visit(startUrl);
    cy.get(".new-item-button").click();
    cy.url().should('include', url2);
    cy.get(".home-link").click();
    cy.url().should('include', startUrl);
    cy.url().should('not.include', url2);
}

Seeing all cy references makes me sad. Is there anyway to make function calls in my test function use a different call context? Just taking cy away would make javascript look for global functions, but is there anyway that I make javascript look for them in the cy object, so that I could write like this?

it('does stuff', () => {
    visit(startUrl);
    get(".new-item-button").click();
    url().should('include', url2);
    get(".home-link").click();
    url().should('include', startUrl);
    url().should('not.include', url2
}

that would make me feel happier. Thank you.

Upvotes: 0

Views: 189

Answers (2)

kuceb
kuceb

Reputation: 18079

Since calling a parent command starts a new command, you can actually do this:

it('does stuff', () => { 
cy.visit(startUrl)
.get(".new-item-button").click()
.url().should('include', url2)
.get(".home-link").click()
.url().should('include', startUrl)
.url().should('not.include', url2)
 }

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075337

You can, if you're not using strict mode, but you probably shouldn't. JavaScript's with statement is effectively deprecated because it makes code very unclear (details in this article by Douglas Crockford).

Here's how you'd do it with with:

// NOT RECOMMENDED, and doesn't work in strict mode
with (cy) {
    visit(startUrl);
    // ...
}

cy. is already quite short, I'd strongly recommend just keeping using it. It's simple, and it's clear to others coming to the code.

Upvotes: 1

Related Questions