简体   繁体   中英

Load json file content in Node js/Mochausing require module passing file name dynamically

I am using mocha/node js/cypress tool to write my test scripts and able to load the data of a json file using the following statement:

var data = require('../../fixtures/TestData/JsonData/ABC_DEF.json');

If I have to pass the file name - ABC_DEF.json dynamically in the script as follows, it doesn't work.

var filename = 'ABC_DEF.json'
var data = require('../../fixtures/TestData/JsonData/'+filename);

Error I see in the Cypress console is:

Uncaught Error: Cannot find module '../../fixtures/TestData/JsonData/ABC_DEF.json'

Any inputs are highly appreciated.

Note: Objective is to read the file content whose file name is a dynamic variable and use it's value to construct the test name - it() dynamically. So file has to be read inside describe block as it has precedence over before() and it() blocks. Hence, cy commands cannot be used as they don't run outside tests and fs cannot be used as they run only in node context, again which is possible through only cy.task

The require command is used to load Node.js modules, and not to read data from file. You can read a file as an object with require , but that's not standard practice.

If you want to read data from file, consider using the fs module:

var fs = require('fs');
var data = fs.readFileSync('../../fixtures/TestData/JsonData/ABC_DEF.json', 'utf8');
console.log(data);

Edit : If you're using Cypress:

cy.readFile('../../fixtures/TestData/JsonData/ABC_DEF.json').then((data) => {
    console.log(data);
});

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

I would add an encoding to the readFileSync , like this:

var fs = require('fs');
var data = fs.readFileSync('../../fixtures/TestData/JsonData/ABC_DEF.json', {encoding: 'utf-8'});
console.log(data);

If you want a string rather than a Buffer . If you want that to be an Object , you can use JSON.parse(data) to get it into an object.

I just did this in the command line, and I have a test.json file:

> fs.readFileSync('test.json');
<Buffer 7b 0d 0a 09 22 74 65 73 74 22 3a 20 31 0d 0a 7d>
> fs.readFileSync('test.json', {encoding: 'utf-8'})
'{\r\n\t"test": 1\r\n}'
> JSON.parse(fs.readFileSync('test.json', {encoding: 'utf-8'}))
{ test: 1 }

Unable to read a file by it's dynamic name and use the content to construct the test name - it() dynamically in the same spec file. Workaround: Has split the code to 2 different spec files. First File with a it() to use cy commands to read a file by it's name and save it's file contents on disk. Second file to read the saved file content and use it's value to construct the test name - it()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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