Quería escribir los valores de una matriz en un archivo JSON usando writeFile .
console.log(category); cy.writeFile('cypress/fixtures/actionsName.json', category);
He generado los valores de la matriz de categorías . Vea abajo
Mi contenido esperado del archivo sería algo como esto
Sin embargo, al escribir el contenido del archivo JSON usando writeFile , solo imprime la matriz de nivel superior, sin incluir su contenido.
No estoy seguro de lo que me estoy perdiendo, realmente agradecería si alguien puede echar un vistazo. ¡Gracias por adelantado!
ACTUALIZACIÓN: según la solicitud, a continuación se muestra el código utilizado para completar la matriz de categorías. Avíseme si algo necesita ser actualizado/optimizado.
getActionName(){ let category = new Array(); let actions = new Array(); //Get all action name and store to json cy.get('.linkbox').each(($category) => { //Get category name const text = $category.find('.heading').text(); cy.log("Category: " + text); category.push(text); //Get each action name and push to the related category cy.wrap($category).find('ul li h2').each(($action) => { const text = $action.text(); cy.log("Action: " + text); actions.push(text); }).then(() => { category[text] = actions; actions = []; }) }).then(() =>{ console.log(category); //!Only writes the top level array cy.writeFile('cypress/fixtures/actionsName.json', category); }) }
Es un poco difícil decirlo con certeza a partir de la captura de pantalla, pero creo que la matriz tiene propiedades no estándar adjuntas (una matriz es un objeto).
Intenta convertir,
const keys = ['Alert', 'Dynamic Elements', 'Frames and Windows', etc] const output = keys.reduce((acc, item) => { acc[item] = category[item] return acc }, {}) cy.writeFile('cypress/fixtures/actionsName.json', output)
Acabo de mirar su código publicado: el problema es el esperado, está adjuntando las listas a la matriz como propiedades. Lo anterior debería funcionar, o puede limpiar la forma en que recopila las listas.
getActionName(){ //let category = new Array(); // change this to an object let category = {}; let actions = new Array(); //Get all action name and store to json cy.get('.linkbox').each(($category) => { //Get category name const text = $category.find('.heading').text(); cy.log("Category: " + text); //category.push(text); // don't need this //Get each action name and push to the related category cy.wrap($category).find('ul li h2').each(($action) => { const text = $action.text(); cy.log("Action: " + text); actions.push(text); }).then(() => { category[text] = actions; actions = []; }) }).then(() =>{ console.log(category); //!Only writes the top level array cy.writeFile('cypress/fixtures/actionsName.json', category); }) }