首页 > 解决方案 > Cypress.io:如何使用 Fixtures?

问题描述

我实际上使用以下代码:

const userType = new Map([['Manager', '1'],['Developer', '2' ]]) 
for (const [key, value] of usertypes.entries()) 
{
    it('log in', () => 
    {
        cy.login(key,value)
        
        cy.xpath('path')
        .click()
         cy.xpath('path')                        
        .should('have.value' , key)         
    })
}

要在其他测试中使用用户,我想在名为 users 的夹具中定义用户类型。我怎样才能在这个测试中使用这个夹具?我的 Json 文件看起来像:

[[
     {"key": "Manager"},
     {"value": "1"}
],

[
    {"key": "Developer"},
    {"value": "2" }
]]

我尝试在 beforeElse 中使用 cy.fixture ,但我不需要在每个测试中都使用它,这是不对的。如何在测试中使用 users.json 的数据?

标签: testingautomated-testscypressfixtures

解决方案


查看您的测试,测试数据是在外部定义的it(),因此cy.fixture()无法在运行测试之外调用。在这种情况下,我会推荐你​​使用 import,所以:

  1. 与您的用户一起创建一个.js文件(假设在fixtures文件夹中)(不要忘记Map允许任何类型的键,因此不需要对象符号):
export const users =  [
    [
        "Manager", 1
    ],

    [
        "Developer", 2
    ]
]

  1. 导入变量并将其作为参数传递给您的地图构造函数:
import { users } from '../fixtures/your_file.js';

const userCred = new Map(users);
   for (const [name, password] of userCred.entries()) {
       it('log in', () => {
           cy.login(name, password)
       })
   }

推荐阅读