我正在使用 cypress 来测试我们的 Angular 应用程序。在阅读了很多关于 cypress 的最佳实践之后,我现在想重构我们的自定义 cypress 登录命令。目前它使用 UI 登录。
我找到了有关如何使用应用程序代码 (https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/logging-in__using-app-code) 登录的示例,但我在使用 Angular 应用程序时遇到了麻烦。显然,我们正在使用 Angular 服务来处理登录。现在尝试从示例中复制代码并不能使用 Angular 服务:
// test.spec
import { AuthService } from 'src/app/core/http/auth.service'
describe('Landing Page Test', () => {
it('should log the user in running app code', () => {
// I cannot run it like this, coz service is a class
AuthService.login('username','password');
// I also cannot instantiate the AuthService because it has injected dependencies
// so this does not compile:
const authService = new AuthService();
});
});
// AuthService (shortend ...)
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private apiHttpService: ApiHttpService) {}
login(username, password) {
// do login stuff
}
}
有什么方法可以利用该服务并从那里运行登录?或者这对 Angular 来说是不可能的吗?
最佳答案
哦,我找到了答案,但它看起来很老套,您将以下内容添加到您的服务中:
constructor() {
if (window['Cypress']) window['AuthService'] = this
}
myFunctionName() {
console.log("Oh I hope I'll get called from Cypress!")
}
在 Cypress 中,您将能够做到这一点:
it.only('Dev', () => {
cy.window().then((w) => {
w.AuthService.myFunctionName()
})
})
关于angular - 使用 Angular 服务使用 cypress 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59750186/