在Cypress中创建指定大小的文件

huangapple go评论52阅读模式
英文:

Creating a file of Certain size in Cypress

问题

我想在 Cypress 测试中创建一个特定大小(26MB)的文件。

我不想在 fixtures 中包含一个真实的文件,因为这会使我的存储库杂乱不堪。

我不能使用环境文件,因为这将在本地和 CI 上运行。它需要是平台无关的。

有没有办法在测试中做到这一点,而不使用系统脚本?

我们能否使用 cy.task 方法做些什么?

英文:

I want to create a file of certain size (26MB) in the cypress test.

I don't want to include a real file in the fixtures as it would clutter my repository.

I can't use an environment file as this would be run locally and on CI. It needs to be platform independent.

Is there a way I can do this in the test without the usage of system scripts?

Is there anything we can do with cy.task method?

答案1

得分: 2

没有永久文件的很好理由。

但是你可以在 before() 钩子中写入文件。

before(() => {
  cy.writeFile('cypress/downloads/file26mb.dat',  Buffer.alloc(26*1024*1024, '0'))
})

你可以在 after() 钩子中通过任务删除它。

const { defineConfig } = require('cypress')
const fs = require('fs')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        deleteFile(path) {
          fs.unlinkSync(path)
          return null
        },
      })
    },
  },
})
after(() => {
  cy.task('deleteFile', 'cypress/downloads/file26mb.dat')
})

使用下载文件夹意味着如果由于某种原因(崩溃)文件没有清理,Cypress 会自动清理。

英文:

There's not a great argument for not having a permanent file.

But you can write the file in a before() hook.

before(() => {
  cy.writeFile('cypress/downloads/file26mb.dat',  Buffer.alloc(26*1024*1024, '0'))
})

You can delete it in an after() hook via a task

const { defineConfig } = require('cypress')
const fs = require('fs')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        deleteFile(path) {
          fs.unlinkSync(path)
          return null
        },
      })
    },
  },
})
after(() => {
  cy.task('deleteFile, 'cypress/downloads/file26mb.dat')
})

Using the downloads folder means if the file is not cleaned up for some reason (a crash), Cypress cleans it up anyway.

huangapple
  • 本文由 发表于 2023年5月17日 12:02:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定