如何在 Cypress 中使用 writeFile 将数组的值正确写入 JSON 文件?

How to properly write the values of an array into a JSON file using writeFile in Cypress?

我想使用 writeFile 将数组的值写入 JSON 文件。

console.log(category);

cy.writeFile('cypress/fixtures/actionsName.json', category);

我已经输出了 类别 数组的值。见下文

我期望的文件内容是这样的

但是,在使用 writeFile 写入 JSON 文件的内容时,它只打印顶级数组,不包括其内容。

我不确定我遗漏了什么,如果有人能看一下,我将不胜感激。提前致谢!

更新: 根据要求,下面是用于填充类别数组的代码。让我知道是否需要 updated/optimized.

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);
    }) 
}

从屏幕截图中很难确定,但我认为该数组附加了非标准属性(数组是一个对象)。

尝试转换,

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)

刚刚查看了您发布的代码 - 问题正如预期的那样,您将列表作为属性附加到数组。以上应该有效,或者您可以清理收集列表的方式。

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);
    }) 
}