我尝试在测试前创建一些目录树并在测试结束后将其删除:
require('should');
var fs = require('fs');
var rmdir = require('rmdir');
describe('FsWatcher', function() {
before(function(done) {
console.log("before");
fs.mkdir('tmp');
fs.mkdir('tmp/css');
fs.mkdir('tmp/js');
fs.mkdir('tmp/lib');
fs.open('tmp/index.htm', 'w');
// (...)
console.log("after_before");
done();
});
describe('single file', function() {
it('should succed', function(done) {
(1).should.equal(1);
done();
});
});
after(function() {
console.log("after");
rmdir('tmp', function() {
console.log("rmdir!");
});
console.log("after_end");
});
});
console.log
的顺序是正确的:
mocha `find tests -name '*.js'`
before
after_before
․after
after_end
✔ 1 test complete (6 ms)
但它不会调用 rmdir()。相同的 rmdir 在 before()
结束时起作用:
describe('FsWatcher', function() {
before(function(done) {
console.log("before");
fs.mkdir('tmp');
fs.mkdir('tmp/css');
fs.mkdir('tmp/js');
fs.mkdir('tmp/lib');
fs.open('tmp/index.htm', 'w');
// (...)
console.log("after_before");
rmdir('tmp', function(){
console.log("rmdir!");
});
done();
});
});
控制台:
mocha `find tests -name '*.js'`
before
after_before
rmdir!
after
after_end
为什么它在 after()
中不起作用?
最佳答案
测试完成得太快了。您需要使用 after 的异步版本。
after(function(done) {
console.log("after");
rmdir('tmp', function() {
console.log("rmdir!");
done();
});
console.log("after_end");
});
应该输出:
after
after_end
rmdir!
当您从 before()
调用它时它似乎起作用的原因是因为还有很多其他事情正在发生,所以 rmdir 将被调用,但稍后当节点返回事件时环形。
关于javascript - Mocha 不会在 after() 函数中调用 rmdir,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080068/