如何让 mocha 让我的程序写文件? [英] How to make mocha let my program write files?

查看:54
本文介绍了如何让 mocha 让我的程序写文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常奇怪的行为(从我的角度来看):

I have a very strange behaviour (from my point of view):

当我使用 mocha 进行单元测试时,我无法写入任何文件(我可以创建文件,但没有写入任何文件).

I cannot write any file when I make my unit tests using mocha (I can create the files but nothing is written to them).

举个例子,我有这段代码:

As an example I have this piece of code:

    console.log('The beginning');
    var fs = require('fs');

    var writableStream = fs.createWriteStream("./testOuputFile.txt");

    function callback(s){
        console.log('callback', s);
    }

    writableStream.on("error", function(err) {
        console.log("ERROR");
        done(err);
    });
    writableStream.on("close", function(ex) {
        console.log("CLOSED");
        done();
    });
    writableStream.on("finish", function(ex) {
        console.log("ENDED");
        done();
    });
    writableStream.on("open", function(fd) {
        console.log("OPENED:"+fd);
    });
    if(typeof callback === "undefined"){
        callback = function(s){console.log(s);};
    }
    var cbCalled = false;
    function done(err) {
        if (!cbCalled) {
            callback(err);
            cbCalled = true;
        }
    }
    writableStream.write('Something');
    writableStream.end();

    fs.writeFile('message.txt', 'Hello Node', function (err) {
        if (err) throw err;
        console.log('It\'s saved!');
    });

    console.log('The end');

将此代码复制到名为 run.js 的文件中并运行 'node run.js' 将输出:

Copying this code into a file named run.js and run 'node run.js' will output:

    The beginning
    The end
    OPENED:11
    ENDED
    callback undefined
    CLOSED
    It's saved!

我得到了两个包含一些文本的不错的文件:testOutputFile.txt 和 message.txt

I obtain two nice files containing some text: testOutputFile.txt and message.txt

对名为 test/test.js 的文件执行相同操作并运行 'mocha' 将输出:

Doing the same into a file named test/test.js and run 'mocha' will output:

    The beginning
    The end



        0 tests complete (0 ms)

我得到两个空文件(零字节):testOutputFile.txt 和 message.txt

And I obtain two empty files (zero bytes): testOutputFile.txt and message.txt

正常吗?

是否需要在 mocha 中进行调整才能使这项工作正常进行?

Is there something to tune in mocha to make this work ?

推荐答案

几乎可以肯定的是,您忘记将 done 回调包含在您的 describe/it 函数参数列表中,因此 mocha 认为您的测试是同步的,并且无法知道您的 IO 何时完成,因此一旦您的函数返回,mocha 就会结束该过程.但正如@BenjaminGruenbaum 指出的那样,您省略了代码中有趣的部分,因此请发布完整代码,我们将予以确认.

Almost certainly you forgot to include the done callback in your describe/it function argument list so mocha thinks your test is synchronous and it doesn't have any way to know when your IO is done, so as soon as your function returns, mocha ends the process. But as @BenjaminGruenbaum points out, you omitted the interesting part of the code, so post the full code and we'll confirm.

这篇关于如何让 mocha 让我的程序写文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆