Cypress在钩子之间共享变量/别名?
自定义命令也非常简单:Cypress在钩子之间共享变量/别名?,cypress,Cypress,自定义命令也非常简单: So I have a pretty `before` and `beforeEach` function that runs before all tests. It looks something like this: describe("JWT Authentication", function() { before(function() { // custom command runs once to get token for JWT auth
So I have a pretty `before` and `beforeEach` function that runs before all tests. It looks something like this:
describe("JWT Authentication", function() {
before(function() {
// custom command runs once to get token for JWT auth
// alias token as 'user' for further use
cy.get_auth_token().as('user')
})
beforeEach(function() {
// before each page load, set the JWT to the aliased 'user' token
cy.visit("/", {
onBeforeLoad(win) {
// set the user object in local storage
win.localStorage.setItem("token", this.user.token);
}
})
})
it("a single test...", function() {
//do stuff
});
自定义命令本身工作并按预期检索令牌。但是,当涉及到每个之前的时,它不知道这个.user.token是什么。特别是不知道用户是什么
一个选项当然是在每个之前调用每个中的命令,这就是JWT Cypress配方/示例规范所做的。然而,这感觉太过分了,因为在我的例子中,我不需要每次测试都获取令牌。对于这组测试,我只需要抓住它一次
因此,如何使用Cypress自定义命令将令牌共享到beforeach钩子。我运行了一些测试,所有的位似乎都正常工作
下面没有给出答案,但可能有助于调试
在before()和beforeach()之间传递令牌
假设我们在before()
中有一个用户,它是否到达onBeforeLoad()
回调
描述(“JWT身份验证”,函数(){
在(函数()之前){
const mockUser={token:'xyz'};
cy.wrap(mockUser).as('user');
})
beforeach(函数(){
访问(”http://example.com", {
加载前加载(win){
console.log(this.user.title);//打印'xyz'
}
})
})
它(“单个测试…”,函数(){
//做事
})
});
自定义命令是否正常工作
我找不到用于身份验证检查的通用模拟,但是任何获取对象的cy.request()
都应该是等效的
我正在点击typicode.com,寻找标题属性
描述(“JWT身份验证”,函数(){
add(“get\u auth\u token”,()=>{
cy.request(“GET”https://jsonplaceholder.typicode.com/todos/1')
.其(“主体”)
。然后(body=>{
console.log('body',body);//打印{userId:1,id:1,标题:“deletus aut autem”,完成:false}
返回体;
});
})
在(函数()之前){
cy.get_auth_token()
.then(user=>console.log('user',user))//打印{userId:1,id:1,标题:“deletus aut autem”,完成:false}
.as('用户')
})
beforeach(函数(){
访问(”http://example.com", {
加载前加载(win){
console.log(this.user.title);//打印'deletus aut autem'
}
})
})
它(“单个测试…”,函数(){
//做事
})
});
自定义命令
这个较短的版本似乎也有效
Cypress.Commands.add(“get\u auth\u token”,()=>{
cy.request(“GET”https://jsonplaceholder.typicode.com/todos/1')
.其(“机构”);
})
我不能在每次之前和之后都这样做。这对我来说太好了afterEach()
在问题中没有提到,但对于演示如何调试非常有用。
Cypress.Commands.add("get_auth_token", () => {
cy.request("POST", Cypress.env("auth_url"), {
username: Cypress.env("auth_username"),
password: Cypress.env("auth_password")
})
.its("body")
.then(res => {
return res;
});
})