[英]Can I delete a file from inside a mocha unit test?
Trying a few node.js filesystem checks (to confirm if environment is functioning correctly) When I write my fs.unlink or fs.unlinkSync outside of Mocha it deletes the file as expected: 尝试一些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);
});
});
});
But when I try the exact same code from inside a mocha test it does not delete the file... 但是,当我从摩卡测试中尝试完全相同的代码不删档...
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
Am I missing something...? 我错过了什么吗?
note: I created an issue on GitHub: https://github.com/visionmedia/mocha/issues/1058 注意:我在GitHub上创建了一个问题: https : //github.com/visionmedia/mocha/issues/1058
(If I get a reply there first I will mirror it here) (如果我首先在那得到答复,我会在这里反映出来)
Use the asynchronous form of testing. 使用异步形式的测试。 Change your it
call so that the callback gets the done
parameter: 更改您的it
调用,以便回调获取done
参数:
it('CREATE (temporary) file tests create/write access to FS', function(done){
And call it in your innermost async callback: 并在最里面的异步回调中调用它:
fs.readdir(__dirname, function(err, list) {
if (err) throw err;
assert.isTrue(list.indexOf(newFile) === -1);
done();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.