【问题标题】:How do I increment automatically a variable when calling a Cypress method?调用赛普拉斯方法时如何自动增加变量?
【发布时间】:2021-05-03 10:15:38
【问题描述】:

createUserPatch 是用于创建新用户的 API 自定义命令。

可以看到我在里面创建了一个变量“A”。

该变量用于正文电子邮件部分[a]+'freddie.doe@example.com','type': 'work','primary': true}]

我想找到一种方法,在我调用命令 createUserPatch 时自动增加变量“A”。

Cypress.Commands.add('createUserPatch', (user) => {
    var A = 1;
    cy.request({
        method: 'POST',
        url:  '/scim/v2/users',
        qs: {
            key : Cypress.env('apiKey')                         
        }, 
        body :{
            schemas: user.schemas,
            userName: user.userName,
            emails: [{ 'value': [A]+'freddie.doe@example.com','type': 'work','primary': true}],
            name : 'Maurice'
        }   
    }).then(res => {
        return res.body;
    });        
});

我在下面的测试中使用了这个命令。

let user = {
    schemas:'["urn:ietf:params:scim:schemas:core:2.0:User"]',
    userName: 'John',
    userId: null,
    groupID: null 
};

describe('Deactivating a user ', () => {

    beforeEach(() => {        
        
        cy.createUserPatch(user).then((newUser) => {
            return user.userId = newUser.id;
        });
    });
....

每次我运行这个测试。 我希望增加电子邮件的价值。

第一次测试 -> 0freddie.doe@example.com

第二次测试 -> 1freddie.doe@example.com

第三次测试 -> 2freddie.doe@example.com

等等……

【问题讨论】:

  • 您是否尝试过不将其设为数组?
  • 我尝试在没有数组的情况下制作它,它确实工作了一次。但是如果我第二次运行它就不起作用了。
  • 添加一个数组不会修复它,var A = 1;在每次调用时重置,尝试将其放在定义之外,然后将 [A]+ 更改为 (A++)+
  • 我把它改成了 (A++)+ 并没有改变任何东西。我收到 409 错误,提示此电子邮件地址已被使用。
  • 您如何在测试中使用createUserPatch 。你也可以发一下吗?

标签: javascript cypress auto-increment


【解决方案1】:

Cypress 会在测试之间清除变量,但在其他问题中建议了一些保存数据的方法(例如将数据写入文件)。

由于您已经使用Cypress.env(name) 来访问环境变量,您可以使用Cypress.env(name, value) 来跟踪前缀。

Cypress.Commands.add('createUserPatch', (user) => {

  let prefix = Cypress.env('emailprefix') || 0;  // first time it may be undefined
                                                 // so "|| 0" initializes it
  Cypress.env('emailprefix', ++prefix);          // increment and save 

  cy.request({
    ...
    emails: [{ 'value': prefix+'freddie.doe@example.com','type': 'work','primary': true}],

注意,前缀值将在运行之间保留,这可能是也可能不是您想要的。

要在运行之间清除它,请添加 before() 以重置值

before(() => Cypress.env('emailprefix', 0) );

beforeEach(() => {
  cy.createUserPatch().then(console.log)
})

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2017-01-28
    • 2023-02-12
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多