我用这个问题作为例子:
使用不带ES6语法的Nightmare.js并生成
但如果我把它放在摩卡测试中,它会超时,这里的代码是:
describe('Google', function() {
it('should do things', function(done) {
var x = Date.now();
var nightmare = Nightmare();
Promise.resolve(nightmare
.goto('http://google.com')
.evaluate(function() {
return document.getElementsByTagName('html')[0].innerHTML;
}))
.then(function(html) {
console.log("done in " + (Date.now()-x) + "ms");
console.log("result", html);
expect(html).to.equal('abc');
done();
return nightmare.end();
}).then(function(result) {
}, function(err) {
console.error(err); // notice that `throw`ing in here doesn't work
});
});
});
但问题是done()
从未被调用。
我使用mocha生成器插件来实现收益。以下是我如何构建您的代码:
require('mocha-generators').install();
var Nightmare = require('nightmare');
var expect = require('chai').expect;
describe('test login', function() {
var nightmare;
beforeEach(function *() {
nightmare = Nightmare({
show: true,
});
afterEach(function*() {
yield nightmare.end();
});
it('should go to google', function*() {
this.timeout(5000);
var result = yield nightmare
.goto('http://google.com')
.dosomeotherstuff
expect(result).to.be('something')
});
});
如果使用生成器,则不需要done,因为done是一个处理异步的回调
您应该在求值后将末尾移到.end()之后,否则会出现许多错误,如done()未被调用,并且由于电子过程未关闭而超时。
describe('Google', function() {
it('should do things', function(done) {
var x = Date.now();
var nightmare = Nightmare();
nightmare
.goto('http://google.com')
.evaluate(() => {
return document.getElementsByTagName('html')[0].innerHTML;
})
.end()
.then( (html) => {
console.log("done in " + (Date.now()-x) + "ms");
console.log("result", html);
expect(html).to.equal('abc');
done();
})
.catch(done);
});
});