将网页加载到运行PhantomJS的无头Jasmine规范中

Dem*_*ian 20 javascript headless-browser jasmine jsdom phantomjs

如何在一个页面中读localhost入无头的Jasmine规范,以便测试用例可以在DOM元素上工作?

我的Gulp任务成功运行Jasmine规范进行单元测试,现在我需要构建集成测试来验证所提供的完整网页localhost.我正在使用该gulp-jasmine-browser插件运行PhantomJS.

例:

gulpfile.js

var gulp =           require('gulp');
var jasmineBrowser = require('gulp-jasmine-browser');

function specRunner() {
   gulp.src(['node_modules/jquery/dist/jquery.js', 'src/js/*.js', 'spec/*.js'])
      .pipe(jasmineBrowser.specRunner({ console: true }))
      .pipe(jasmineBrowser.headless());
   }

gulp.task('spec', specRunner);
Run Code Online (Sandbox Code Playgroud)


规格/车,spec.js

describe('Cart component', function() {

   it('displays on the gateway page', function() {
      var page = loadWebPage('http://localhost/');  //DOES NOT WORK
      var cart = page.find('#cart');
      expect(cart.length).toBe(1);
      });

   });
Run Code Online (Sandbox Code Playgroud)

没有loadWebPage()功能.这只是为了说明我认为需要的功能.

Dem*_*ian 0

jsdom 来救援!

事实证明,将网页加载到无头 Jasmine 规范中非常容易……但是您需要将 PhantomJS 替换为jsdom

战略:

  1. 使用 Jasmine 调用将运行以请求网页的beforeAll()函数。JSDOM.fromURL()
  2. 将网页加载到 DOM 中后,即可公开windowjQuery在测试用例中使用。
  3. 最后,致电done()表明测试现已准备好运行。

window确保在测试运行后关闭。

规范.js

const url  = 'http://dnajs.org/';
const { JSDOM } = require('jsdom');
let window, $;
function loadWebPage(done) {
   function handleWebPage(dom) {
      function waitForScripts() {
         window = dom.window;
         $ = dom.window.jQuery;
         done();
         }
      dom.window.onload = waitForScripts;
      }
   const options = { resources: 'usable', runScripts: 'dangerously' };
   JSDOM.fromURL(url, options).then(handleWebPage);
   }
function closeWebPage() { window.close(); }

describe('The web page', () => {

   beforeAll(loadWebPage);
   afterAll(closeWebPage);

   it('has the correct URL', () => {
      expect(window.location.href).toBe(url);
      });

   it('has exactly one header, main, and footer', () => {
      const actual =   {
          header: $('body >header').length,
          main:   $('body >main').length,
          footer: $('body >footer').length
          };
      const expected = { header: 1, main: 1, footer: 1 };
      expect(actual).toEqual(expected);
      });

   });
Run Code Online (Sandbox Code Playgroud)


测试输出

截屏
注意:上面的屏幕截图来自类似的 Mocha 规范,因为 Mocha 有一个很好的默认报告器。

项目

如果您想自己尝试一下,它位于 GitHub 上: https:
//github.com/dnajs/load-web-page-jsdom-jasmine


编辑:针对 jsdom 11 进行了更新