簡體   English   中英

如何從 cypress 項目中讀取 JSON 文件?

[英]How to read JSON file from cypress project?

我已經開始使用 cypress automation,我正在努力處理 JSON 個文件。

任何人都知道我如何讀取 JSON 文件,比方說,位於../example/vehicle.json?

我知道柏樹是 JavaScript,但在柏樹項目中導入 JQuery 時我也遇到了麻煩。

我從未與賽普拉斯合作過,在查看文檔時,我認為這可以幫助您

cy.fixture(filePath)
cy.fixture(filePath, encoding)
cy.fixture(filePath, options)
cy.fixture(filePath, encoding, options)

請查看https://docs.cypress.io/api/commands/fixture.html#Syntax

Juste 以防萬一這可以幫助任何人,有一個很好的方法可以使用以下行來做到這一點:

cy.readFile('path/to/file.json/txt/yaml')

https://docs.cypress.io/api/commands/readfile.html

據我所知,這將是訪問存儲在 json 文件中的數據的“賽普拉斯”方式。

參考: https : //docs.cypress.io/api/commands/fixture.html#Accessing-Fixture-Data

cy.fixture('user').then((user)  => {
    var name = user.name
    var pass = user.password
})

其中“用戶”是/fixtures/user.json

{
    "name": "username",
    "password": "password1234"
}

嘿 Cypress geek 我成功使用它

cy.fixture(profile.json).then((user) => {
        // Delay each keypress by 0.1 sec
        cy.get('#username').type(user.email, { delay: 100 }).should('have.value', user.email)
        cy.get('#password').type(user.password)
      })

在 fixtures 文件夾中創建一個UserData.json文件並定義您的值,如下所示:

{
  "Name": "Ghulam Nabi",
  "Password":"Admin123"
}

現在,在您的測試文件中

cy.fixture(‘UserData.json’).then((user) => { 

        cy.get(‘#txtUsername’).type(user.Name)
        cy.get(‘#txtPassword’).type(user.Password)

      });

這只是一個例子。 你可以通過這個方法做很多事情。

禮貌: https://softans.com/get-user-data-from-json-file-in-cypress/

您可能會發現這對您的問題和組織您的項目很有用。 假設您在這里有輸入文件:

fixtures    
│
└───website
│      orders.json
│      ...
│
└───mobile
       subCancel.json
       ...

您可以創建一個支持方法,該方法返回給定 json 文件所在文件夾的名稱:

getFolderForJson(jsonName) {
   let value;
   switch (jsonName) {
     case 'subCancel':
       value = 'mobile';
       break;
     case ... //add your custom cases
    }
   return value;
}

將 json 讀取邏輯放在一個命令中,以便在您的測試中重復使用:

Cypress.Commands.add('readJson', (jsonName) => {
  cy.fixture(jsonName).then(json => {
    return JSON.parse(JSON.stringify(json)
    );
  });
});

然后在測試操作/斷言中使用 json 文件屬性:

let folder = new BasePage().getFolderForJson(jsonName);
cy.readJson(folder + '/' + jsonName + '.json').then((data) => {
   cy.get('selector').type(data.shippingAddress); //use your own json files/properties
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM