NodeJstesting用例的代码,用于每个数组的方法

这里的文件是一个数组像var files = ['/tmp/1.pdf','/tmp/2.pdf'];

方法:

var createAttachmentsForMail = function (files) { var attachmets = []; files.forEach(function (value) { attachmets.push( { "Content-type": mime.lookup(value), "FileName": path.basename(value), "content": new Buffer(fs.readFileSync(value)).toString('base64') } ); }); return attachmets; }; 

testing方法: 我想testingattachment.push被调用2次,但是怎么样? 我也想断言附件是什么回报。

 describe("Create attachments", function() { it('from pdf path', function() { var files = [ '/tmp/1.pdf', '/tmp/2.pdf' ]; sinon.stub(fs, "readFileSync"); sinon.stub(files); mailSender.createAttachmentsForMail(files); sinon.assert.calledOnce(files.forEach); fs.readFileSync.restore(); files.forEach.restore(); }); }); 

当你打电话给sinon.stub(files); 你刺了文件数组的所有方法。 这意味着forEach不会被执行,也不会产生任何文件。 这就是为什么我猜你不能检查文件的数量。

第二件事就是不需要testing“如果两次调用.push”或者“如果.forEach”被调用。 因为如果你稍微改变实现(例如,你开始使用lodash _.each而不是Array.prototype.forEach),你的testing将停止工作。

你应该testing行为,而不是内部实现。

 var assert = require('assert'); describe('#createAttachmentsForMail', () => { it('should form proper file names/content types etc', function() { var files = [ '/tmp/1.pdf', '/tmp/2.pdf' ]; //Also let's make readFileSync always return mocked data sinon.stub(fs, "readFileSync", () => 'mocked content'); var attachments = createAttachmentsForMail(files); //Test that we received 2 attachments. assert.equal(attachments.length, 2); for (var attachment of attachments) { //Check if we received a proper content type assert.equal(attachment['Content-type'], 'application/pdf'); //Do other needed checks ... } fs.readFileSync.restore(); }); });