NodeJs测试用于侧面forEach方法的代码

时间:2017-02-10 09:22:02

标签: javascript node.js mocha sinon

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

方法:

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();
    });
});

测试方法:我想测试一下attachment.push被调用2次但是怎么样?我还想断言附件是什么。

Map<String, Set<Integer>> map = new HashMap<>();
// fill map here
String result = map.entrySet().stream()
        .map(x -> x.getKey() + ": " + x.getValue().stream()
                .map(Object::toString)
                .collect(Collectors.joining(", ")))
        .collect(Collectors.joining("; "));

1 个答案:

答案 0 :(得分:1)

当你调用sinon.stub(files);时,你会刺伤文件数组的所有方法。这意味着forEach实际上不会被执行,您将不会生成任何文件。 这就是为什么我猜你无法检查文件的数量。

第二件事是,没有必要测试类似的事情,如果.push被调用两次&#39;或者&#39; if .forEach&#39;被称为。如果你稍微改变实现(例如你开始使用lodash _.each而不是Array.prototype.forEach),你的测试将停止工作。

您应该测试行为,而不是内部实现。

&#13;
&#13;
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();
	});
});
&#13;
&#13;
&#13;

我用过'断言'&#39;模块只是为了简单。我建议&#39; chai&#39;作为一个更强大的断言库。