简体   繁体   English

如何在赛普拉斯中使用模块“fs”?

[英]How to use a module 'fs' in Cypress?

I want to import JSON data from my local repository.我想从我的本地存储库中导入 JSON 数据。

var fs = require('fs');
var data = fs.readFileSync('./profile.json', 'utf8');
console.log(data);

...

However Cypress occurs this error:然而赛普拉斯发生了这个错误:

在此处输入图像描述

Here is my package.json from my cypress project.这是我的柏树项目中的 package.json。

{
  "name": "cypress_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "npx cypress run",
    "clean-reports": "rm -rf cypress/reports",
    "merge-report": "npx mochawesome-merge --reportDir cypress/reports/separate-reports cypress/reports/full_report.json",
    "generate-report": "npx mochawesome-report-generator --reportDir cypress/reports cypress/reports/full_report.json",
    "after:tests": "npm run merge-report; npm run generate-report",
    "cypress": "npm run clean-reports; npm run test; npm run after:tests"
  },
  "keywords": [],
  "type": "module",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@cypress/webpack-preprocessor": "^5.4.1",
    "cypress": "^4.11.0",
    "fs": "0.0.1-security",
    "mocha": "5.2.0",
    "mochawesome": "4.1.0",
    "mochawesome-merge": "2.0.1",
    "mochawesome-report-generator": "4.0.1",
    "papaparse": "^5.2.0",
    "selenium-webdriver": "^4.0.0-alpha.7",
    "xlsx": "^0.16.4"
  },
  "devDependencies": {
    "@babel/core": "^7.11.0",
    "@babel/preset-env": "^7.11.0",
    "babel-loader": "^8.1.0",
    "webpack": "^4.44.1"
  }
}

I don't want to use cy.fixture because I need to use data from json in my 'it test discription'.我不想使用 cy.fixture,因为我需要在我的“it 测试描述”中使用来自 json 的数据。 For example, I want to make tests like this.例如,我想做这样的测试。

it (datas.data, ()=>{
   ...
})

You should be able to load your profile.json with the require statement.您应该能够使用 require 语句加载您的profile.json

const data = require('profile.json');

To use fs, or various other Node modules, you must put it in a plugin.要使用 fs 或其他各种 Node 模块,您必须将其放入插件中。 From https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests#Plugins-file :https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests#Plugins-file

While the Cypress tests execute in the browser, the plugins file runs in the background Node process, giving your tests the ability to access the file system and the rest of the operating system by calling the cy.task() command当 Cypress 测试在浏览器中执行时,插件文件在后台 Node 进程中运行,使您的测试能够通过调用cy.task()命令访问文件系统和操作系统的 rest

This is alluded to in the comments above, but I missed it there so I want to make it clear.上面的评论中提到了这一点,但我在那里错过了它,所以我想澄清一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM