覆盖 window 作为函数调用上下文
Overriding window as function call context
我在用cypress写测试用例,写的每一行都引用了cy对象。我的测试代码示例如下所示:
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);
}
看到所有的cy引用我都很难过。无论如何让我的测试函数中的函数调用使用不同的调用上下文?只是拿走 cy 会让 javascript 寻找全局函数,但是无论如何我让 javascript 在 cy 对象中寻找它们,以便我可以这样写?
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
}
那会让我感觉更快乐。谢谢。
如果您不使用严格模式,您可以,但您可能不应该这样做。 JavaScript 的 with
语句实际上已被弃用,因为它使代码非常不清楚(Douglas Crockford 的 this article 中有详细信息)。
以下是使用 with
的方法:
// NOT RECOMMENDED, and doesn't work in strict mode
with (cy) {
visit(startUrl);
// ...
}
cy.
已经很短了,我强烈推荐继续使用它。很简单,来代码的人一目了然
由于调用父命令会启动一个新命令,您实际上可以这样做:
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)
}
我在用cypress写测试用例,写的每一行都引用了cy对象。我的测试代码示例如下所示:
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);
}
看到所有的cy引用我都很难过。无论如何让我的测试函数中的函数调用使用不同的调用上下文?只是拿走 cy 会让 javascript 寻找全局函数,但是无论如何我让 javascript 在 cy 对象中寻找它们,以便我可以这样写?
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
}
那会让我感觉更快乐。谢谢。
如果您不使用严格模式,您可以,但您可能不应该这样做。 JavaScript 的 with
语句实际上已被弃用,因为它使代码非常不清楚(Douglas Crockford 的 this article 中有详细信息)。
以下是使用 with
的方法:
// NOT RECOMMENDED, and doesn't work in strict mode
with (cy) {
visit(startUrl);
// ...
}
cy.
已经很短了,我强烈推荐继续使用它。很简单,来代码的人一目了然
由于调用父命令会启动一个新命令,您实际上可以这样做:
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)
}