我可以从mocha单元测试中删除文件吗?

时间:2013-12-04 23:24:50

标签: javascript node.js file-io mocha

尝试一些node.js文件系统检查(以确认环境是否正常运行) 当我在Mocha的外部编写fs.unlink或fs.unlinkSync 时,它会按预期删除文件:

var fs = require('fs');

var newFile = new Date().getTime() +".txt";

fs.writeFile(newFile, "hello!", function (err) {
    if (err) console.log(err);
    // console.log("Created file: "+newFile);
    fs.readdir(__dirname, function(err, list) {
        // console.log(list)
        console.log(list.indexOf(newFile) > -1)
        fs.unlinkSync(newFile);
        console.log('successfully deleted '+newFile);
        // console.log("Deleted: "+newFile)
        fs.readdir(__dirname, function(err, list) {
            if (err) throw err;
            console.log(list.indexOf(newFile) === -1);
        });
    });
});

但是当我尝试完全来自里面的相同代码进行摩卡测试时,删除文件......

var chai   = require('chai');
var assert = chai.assert; 
var fs     = require('fs');

describe('Node.js Environment Checks', function(){
  describe('Basic IO', function(){
    it('CREATE (temporary) file tests create/write access to FS', function(){
        // setup
        var newFile = new Date().getTime() +".txt";

        fs.writeFile(newFile, "hello!", function (err) {
            if (err) console.log(err);
            // console.log("Created file: "+newFile);
            fs.readdir(__dirname, function(err, list) {
                // console.log(list)
                assert.isTrue(list.indexOf(newFile) > -1)
                fs.unlinkSync(newFile);
                console.log('successfully deleted '+newFile);
                // console.log("Deleted: "+newFile)
                fs.readdir(__dirname, function(err, list) {
                    if (err) throw err;
                    assert.isTrue(list.indexOf(newFile) === -1);
                });
            });
        });
    })
  })
}) // end node env checks

我错过了什么......?

注意:我在GitHub上创建了一个问题: https://github.com/visionmedia/mocha/issues/1058
(如果我在那里得到答复,我将在这里反映出来)

1 个答案:

答案 0 :(得分:0)

使用异步测试形式。更改it来电,以便回调获得done参数:

it('CREATE (temporary) file tests create/write access to FS', function(done){

并在最里面的异步回调中调用它:

            fs.readdir(__dirname, function(err, list) {
                if (err) throw err;
                assert.isTrue(list.indexOf(newFile) === -1);
                done();
            });