【问题标题】:How to test Node module with no end points using mocha and chai如何使用 mocha 和 chai 测试没有端点的 Node 模块
【发布时间】:2015-11-10 06:48:18
【问题描述】:
让我首先声明我是一个节点并测试新手。我编写了一个节点模块,用于更新某个目录(和所有子目录)中所有指定文件类型的所有版权标头。它按预期工作,但我想编写一些测试来验证功能,以防将来发生任何变化或在其他地方使用。
对测试、node 和 mocha/chai 不熟悉,我不知道想出一种有意义的测试方法。没有前端,也没有端点。我只传入一个文件扩展名列表、一个包含的子目录列表和一个排除的子目录列表,它就会运行。 (这些列表在模块中用作正则表达式)。文件已就地更新。
谁能告诉我如何开始使用它?我不依赖于 Mocha 和 Chai,如果有更好的方法,我会全力以赴。如果这超出了 stackoverflow 的范围,我深表歉意。
【问题讨论】:
标签:
regex
node.js
testing
mocha.js
chai
【解决方案1】:
假设您的模块上有一个方法,该方法返回更新文件的列表,而这又需要一些其他模块遍历文件目录以确定所述文件,您的测试可能看起来像这样。您可以使用sinon 进行存根。 :
var assert = require('assert');
var sinon = require('sinon');
var sandbox = sinon.sandbox.create();
var copywriter = require('../copywriter');
var fileWalker = require('../fileWalker');
describe('copywriter', function() {
beforeEach(function() {
sandbox.stub(fileWalker, 'filesToUpdate').yields(null, ['a.txt', 'b.txt']);
});
afterEach(function() {
sandbox.restore();
});
// the done is passed into this test as a callback for asynchronous tests
// you would not need this for synchronous tests
it('updates the copyright headers', function(done) {
copywriter('../some-file-path', function(err, data){
assert.ifError(err);
sinon.assert.calledWith(fileWalker.filesToUpdate, '../some-file-path');
assert.deepEqual(data.updated, ['a.txt', 'b.txt']);
done();
});
});
});