使用Mocha和Assert测试Node.js 模块(下)

我们在 TODO 模块中想要的功能之一是 CSV 导出功能。这会将我们存储的所有 TODO 连同完成的状态打印到一个文件中。这要求我们使用该fs模块——一个用于处理文件系统的内置 Node.js 模块。

  写入文件是一种异步操作。在 Node.js 中有很多方法可以写入文件。我们可以使用回调、Promises 或async/await关键字。在本节中,我们将看看我们如何为这些不同的方法编写测试

  回调

  回调函数是用作异步函数的参数的函数。当异步操作完成时调用它。

  让我们在我们的Todos类中添加一个名为saveToFile(). 这个函数将通过遍历我们所有的 TODO 项并将该字符串写入文件来构建一个字符串。

  打开你的index.js文件:

nano index.js

  在此文件中,添加以下代码:

const fs = require('fs');

class Todos {

    constructor() {

        this.todos = [];

    }

    list() {

        return [...this.todos];

    }

   

    add(title) {

        let todo = {

            title: title,

            completed: false,

        }

        this.todos.push(todo);

    }

    complete(title) {

        if (this.todos.length === 0) {

            throw new Error("You have no TODOs stored. Why don't you add one first?");

        }

        let todoFound = false

        this.todos.forEach((todo) => {

            if (todo.title === title) {

                todo.completed = true;

                todoFound = true;

                return;

            }

        });

        if (!todoFound) {

            throw new Error(`No TODO was found with the title: "${title}"`);

        }

    }

    saveToFile(callback) {

        let fileContents = 'Title,Completed\n';

        this.todos.forEach((todo) => {

            fileContents += `${todo.title},${todo.completed}\n`

        });

        fs.writeFile('todos.csv', fileContents, callback);

    }

}

module.exports = Todos;

  我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值