对同一个幻象实例使用createPage()两次

我试图用PhantomJS设置摩卡testing,而且我遇到了一个问题,我无法使用相同的幻像实例来创build多个页面。 第一个testing用例运行得很好,但第二个testing用例运行良好。 我只想使用一个实例,因为它应该更快。

var assert = require('assert'); var phantom = require('phantom'); var path = require('path'); var ph; describe('document', function() { before(function(done) { // Create only one phantom instance for the whole suite this.timeout(10000); // Prevent test case from aborting while phantom loads phantom.create(function(p) { ph = p; done(); }, { dnodeOpts: {weak: false} }); }); it('should have a title', function(done) { ph.createPage(function(page) { var url = 'file:///' + path.resolve(__dirname + '/index.html'); page.open(url, function(status) { page.evaluate(function() { return document.title; }, function(title) { assert.equal('This is a title', title); ph.exit(); done(); }); }); }); }); it('should have the same title', function(done) { ph.createPage(function(page) { var url = 'file:///' + path.resolve(__dirname + '/index.html'); page.open(url, function(status) { page.evaluate(function() { return document.title; }, function(title) { assert.equal('This is a title', title); ph.exit(); done(); }); }); }); }); }); 

为什么不能第二次打开页面?

你在第一次testing后退出PhantomJS,所以第二次testing失败。 你需要运行ph.exit(); 在所有的testing之后只有一次。 我怀疑这可以做到:

 describe('document', function() { before(...); after(function(done) { ph.exit(); done(); }); it(...); it(...); }); 

你可能甚至可以在before page ,并在testing中使用page实例。 每个testing用例都应该打开一个新的URL,以便提供一个新的DOM。 这可能会更快,更有弹性反对内存泄漏。

顺便说一下,PhantomJS的localStorage永远不会被清除(因为它存储在磁盘上),所以你必须在每个testing用例之后或执行结束时自己清除它。
PhantomJS每个进程只有一个CookieJar(只在内存中),所以如果你testinglogin或类似的东西,你将不得不删除cookie。