摩卡在testing中保存文件状态

我有一个unit testing,正在testingconfiguration文件的更新…当然,我运行testing后,我的文件现在改变了。 我想我可以使用“之前”来caching文件,并在“之后”恢复。

mod = require('../modtotest'); describe('Device Configuration', function(){ var confPath = '../config/config.json'; var config; before(function(){ //cache object config = require(confPath); }) describe('Update Config', function(){ it('Should update config', function(done){ mod.updateConfig(); //do assertions }) }); after(function(){ //restore fs.writeFileSync(confPath, JSON.stringify(config, null, 4)); }) }) 

但是,每当我尝试这样做,它说该文件不存在。 看起来,当我运行Mocha( -> app $mocha -R spec )时,它会在我执行它的地方执行全局安装目录吗?

有一个简单的方法来实现我想要的? 或者我可能只是把它全部弄错了?

如果你从命令行运行mocha,它的当前工作目录就是你启动它时所在的目录。 因此,如果您位于项目的顶层目录中,则其当前工作目录将成为项目的顶层目录,然后所有相对path将相对于项目的顶层目录进行解释。

如果您想读取与您的testing定义文件相关的文件,您可以使用__dirname并将其与您想要解释的pathjoin到您的文件中。 这里是我的一个testing套件中的实际代码:

 var fs = require("fs"); var path = require("path"); [...] var spectest_dir = path.join(__dirname, "spectest"); var test_dirs = fs.readdirSync(spectest_dir); 

上面的代码在一个名为test/spectest.js的文件中,相对于我的项目的顶层目录。 这段代码打开一个与文件所在位置有关的spectest目录:也就是打开名为test/spectest/的目录,然后处理它在那里find的文件,创build一个testing列表。

这就是说,你这样做的方式,你可能会遭受数据丢失,如果发生错误之前,你设法恢复你的文件是什么。 所以我会build议以不同的方式构build你的testing:

  1. 将您的configuration存储在一个不会被修改的模板文件中。 这可以被称为config_test_template.json

  2. beforeEachcallback中,将此模板复制到testing期间被修改的位置。 使用beforeEach可确保在每次callback之前重置testing中使用的文件, itcallback属于与beforeEach调用相同的describe

  3. 在callbackafter ,删除为testing而创build的文件。

像这样的东西:

 var fs = require("fs"); var path = require("path"); var mod = require('modtotest'); describe('Device Configuration', function(){ var template_path = path.join(__dirname, 'config_test_template.json'); var conf_path = path.join(__dirname, 'config.json'); var config; describe('Update Config', function(){ beforeEach(function () { fs.createReadStream(template_path).pipe(fs.createWriteStream(conf_path)); }); after(function () { fs.unlinkSync(conf_path); }); it('Should update config', function(done){ mod.updateConfig(); //do assertions }) // more tests could go here }); }); 

注意事项:我没有运行上面的代码,所以要小心input错误。 这个问题值得关注,以便在Node.js中复制文件。

如果这样做,最糟糕的情况是如果发生故障,还会有额外的文件。 没有数据丢失。