我已经在Node中使用mocha,chai,typescript设置了测试:
import chai = require('chai');
import chaiAsPromised = require('chai-as-promised');
import ReadLine = require('readline');
import FS = require('fs');
before((done) => {
chai.should();
chai.use(chaiAsPromised);
done();
});
describe("Test", function() {
this.timeout(20000);
let testFile: string [] = [];
before((done) => {
let lineReader = ReadLine.createInterface({
input: FS.createReadStream("MyFile.txt")
});
lineReader.on('line', function (line) {
testFile.push(line);
});
done();
});
it("test", () => {
for(let i=0;i<testFile.length;i++){
let curLine = testFile[i];
console.log(curLine);
}
}).timeout(30000);
});
然后我像这样运行测试:
C:\Repository\Folder>npm test
> Test@0.0.1 test C:\Repository\Folder
> mocha -r ts-node/register -R spec test/**/*.ts
Test
√ test
1 passing (16ms)
看来它确实通过了,但是没有打印到控制台上,我在做什么错了?
答案 0 :(得分:1)
问题出在这段代码中:
lineReader.on('line', function (line) {
testFile.push(line);
});
done();
您的ReadLine阅读器异步工作。您附加了一个侦听器,并且在读取任何行之前,done()
已被调用,因为它是事件循环中的下一个条目。
要修复此问题,请等待读者关闭:
import chai = require('chai');
import chaiAsPromised = require('chai-as-promised');
import ReadLine = require('readline');
import FS = require('fs');
before((done) => {
chai.should();
chai.use(chaiAsPromised);
done();
});
describe("Test", function() {
this.timeout(20000);
let testFile: string [] = [];
before((done) => {
let lineReader = ReadLine.createInterface({
input: FS.createReadStream("MyFile.txt")
});
lineReader.on('line', function (line) {
testFile.push(line);
});
linereader.on('close', () => done()); // <=====
});
it("test", () => {
for(let i=0;i<testFile.length;i++){
let curLine = testFile[i];
console.log(curLine);
}
}).timeout(30000);
});
答案 1 :(得分:0)
您需要在for循环后使用done():
it("test", (done) => {
for(let i=0;i<testFile.length;i++){
let curLine = testFile[i];
console.log(curLine);
}
done();
}).timeout(30000);