我以这个问题为例:
Use Nightmare.js without ES6 syntax and yield
但如果我把它放在摩卡测试中,这将会超时,这里是代码:
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()
。
答案 0 :(得分:2)
我使用mocha-generators插件来做收益。下面我将如何构建您的代码:
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是一个处理异步的回调
答案 1 :(得分:0)
你应该在评估之后移动.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);
});
});