最近我开始学习 NodeJS,并且我编写了一个简单的 Youtube 抓取工具,它使用 NightmareJS 并返回每个视频 URL 的点赞数、观看次数、作者和标题名称。
现在我正在尝试使用 Mocha 对我的代码进行单元测试(练习一些单元测试),但由于某种原因它失败并出现以下错误:
错误:超过 2000 毫秒的超时。确保在此测试中调用了 done() 回调。
我试图增加超时(最多 15 秒),但它没有帮助,我猜它挂在某个地方。我错过了什么?我也很高兴听到一些关于代码结构和实现的建设性批评。
这是我的代码:
var Nightmare = require('nightmare');
var expect = require('chai').expect;
var assert = require('chai').assert;
youtube_url = 'https://www.youtube.com/watch?v=0_oPsFTyhjY';
describe('test youtube video url results', function() {
it('should return the actual video url/title/author name/num of likes and views', function(done) {
var nightmare = Nightmare({ show: false, gotoTimeout: 3000 })
nightmare
.goto(youtube_url)
.scrollTo(10000,0)
.wait('#comment-section-renderer-items')
.evaluate(function (youtube_url) {
var authorSelector = '#watch7-user-header > div > a';
var titleSelector = '#eow-title';
var vcountSelector = '#watch7-views-info > div.watch-view-count';
var lcountSelector = '#watch8-sentiment-actions > span > span:nth-child(1) > button > span';
var authorElement = document.querySelector(authorSelector);
var titleElement = document.querySelector(titleSelector);
var vcountElement = document.querySelector(vcountSelector);
var lcountElement = document.querySelector(lcountSelector);
var JSONres = {'VIDEO URL':url, 'VIDEO TITLE': titleElement.innerText,'AUTHOR NAME': authorElement.innerText,
'NUMBER OF VIEWS': vcountElement.innerText, 'NUMBER OF LIKES': lcountElement.innerText};
return (JSONres)
},youtube_url)
.end()
.then(function (result) {
try{
expect(result['VIDEO URL']).to.equal(youtube_url);
expect(result['VIDEO TITLE']).to.equal('The Best Mouse in the World?');
expect(result['AUTHOR NAME']).to.equal('Unbox Therapy');
assert.isAtLeast(result['NUMBER OF VIEWS'], 1816808, 'The number of views is at least the number of views that has been already seen');
// It's possible to remove your like from the video so hypothetically many users may remove their likes thus there is no upper/lower
// bound on the like amount a video can have at any time except that it must be non-negative.
assert.isAtLeast(result['NUMBER OF LIKES'], 0, 'The number of likes is at least a non-negative number');
done();
}
catch(error){
done(error);
}
})
});
});