自動化測試,讓你上班擁有一杯咖啡的時間 | Day 19 — 如何寫入檔案和讀取檔案

史卯郁
Oct 3, 2021

--

此系列文章會同步發文到13th鐵人賽,有興趣的讀者可以前往觀看喔。

  1. writeFile() 語法
cy.writeFile(filePath, contents)
cy.writeFile(filePath, contents, encoding)
cy.writeFile(filePath, contents, options)
cy.writeFile(filePath, contents, encoding, options)

2. 可以寫成 txt 檔或是 json 檔,檔案會放在 cypress/fixtures 底下

cy.writeFile('path/to/message.txt', 'Hello Cypress') cy.writeFile('path/to/data.json', { name: 'Jennifer', email: 'jennifer@example.com' })

3. 在檔案的最後附加文字可以用 { flag: 'a+' }

cy.writeFile('path/to/message.txt', 'Hello World', { flag: 'a+' })

4. readFile() 語法

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

5. 動手寫程式

describe('測試寫檔案', function() {
it('應該可以在test1檔案寫東西', function() {
cy.writeFile('cypress/fixtures/test1.txt', 'Hello Cypress!\\n')
})
it('應該可以在test1檔案上附加文字', function() {
cy.writeFile('cypress/fixtures/test1.txt', 'Hello Cypress!!', {flag: 'a+',})
})
it('應該可以在test2檔案寫東西', function() {
cy.writeFile('cypress/fixtures/test2.json', { name: 'Jennifer', email: 'jennifer@example.com' })
})
})
describe('測試讀檔案', function() {
it('應該可以在test1檔案讀檔案', function() {
cy.readFile('cypress/fixtures/test1.txt').should('eq','Hello Cypress!\\nHello Cypress!!')
})
it('應該可以在test2檔案讀檔案', function() { cy.readFile('cypress/fixtures/test2.json').its('name').should('eq', 'Jennifer')
})
})

5. 看結果

參考資料

--

--

No responses yet