Well, I think I found out a kind of solution. I guess the problem was something about asynchronous issue. The "expect function" seemed to called before finishing read files.
So I changed my code and get the result I expected. By the way timer function seems that it doesn't work properly. Please review my changed code and give some advice if I did something wrong.
const findPattern = require('./findPatterns');
const expect = require('chai').expect;
const sinon = require('sinon');
describe('findPattern', function() {
const sampleFiles = ['./sample/sample1.txt', './sample/sample2.txt', './sample/sample3.txt'];
const regEx = /[0-9]+/g;
const readFun = (file) => console.log('Read from ' + file);
const o = {
f: readFun
};
const spy = sinon.spy(o, "f");
beforeEach(function(done) {
findPattern(sampleFiles, regEx, done)
.on('error', (err) => console.log('error: ' + err))
.on('read', spy)
.on('found', (file, match) => console.log('Matched ' + match + ' in file' + file));
});
it('findPattern', function() {
expect(spy.called).to.be.true;
});
});
const EventEmitter = require('events');
const fs = require('fs');
function readFile(file, regex, emitter, callback) {
fs.readFile(file, "utf-8", (err, content) => {
if (err) {
return emitter.emit('error', err);
}
emitter.emit('read', file);
const matches = content.match(regex);
if (matches) {
matches.forEach(i => {
emitter.emit('found', file, i);
});
}
callback();
});
}
function findPattern(files, regex, done) {
const emitter = new EventEmitter();
let completed = 0;
function finish() {
if (++completed == files.length) {
return done();
}
}
files.forEach(function(file) {
readFile(file, regex, emitter, finish);
});
return emitter;
}
module.exports = findPattern;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…