在我的賽普拉斯測驗中,我試圖從 CSV 檔案中讀取資料并遍歷每一行。
以下是我的fixtures/logins.csv檔案內容:

我想遍歷每一行資料以登錄到應用程式。
這是我最新的代碼,它當前只是將 CSV 檔案資料記錄為字串:
const csvUploaded = 'cypress/fixtures/logins.csv'
it('CSV test', () => {
cy.readFile(csvUploaded, 'utf-8').then((txt) => {
cy.log(txt)
cy.log(typeof txt)
});
});
txt目前是以下字串:
username,password john,pword1 james,myPassword frank,newPassword
uj5u.com熱心網友回復:
使用該格式的資料,您必須
txt用換行符分割單個字串- 將每一行拆分為
| - 洗掉空值 - 修剪周圍空格的字串
cy.fixture('logins.csv')
.then(txt => txt.split('\n').map(row => row.trim())) // string to array of rows
.then(rows => {
const data = rows.slice(1) // remove headers
.map(row => row.split('|') // split each row
.filter(Boolean) // ignore start and end "|"
.map(col => col.trim()) // remove whitespace
)
.filter(row => row.length) // remove empty rows
return data
})
.should('deep.eq', [
['john', 'pword1'],
['james', 'myPassword'],
['frank', 'newPassword']
])
.each(row => {
console.log(row)
})
降價表
從技術上講,該檔案不是 CSV,它是一個降價表(或者可以這樣對待)。
這個包Parse Markdown Table可以幫助你決議它
it('parses a markdown table from fixture', async () => {
const { createMarkdownArrayTable } = await import('parse-markdown-table')
cy.fixture('logins.csv').then(txt => {
createMarkdownArrayTable(txt).then(async table => {
console.info('headers', table.headers)
for await (const row of table.rows) {
console.info('row', row)
}
})
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523240.html
標籤:CSV柏
下一篇:嵌套JSON到CSV(多級)
