简体   繁体   English

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

[英]Load a web page into a headless Jasmine spec running PhantomJS

How do I read in a page from localhost into a headless Jasmine spec so test cases can work on the DOM elements? 如何从localhost读入一个无头的Jasmine规范页面,以便测试用例可以在DOM元素上工作?

My Gulp task is successfully running Jasmine specs for unit testing, and now I need to build integration tests to verify full web pages served from localhost . 我的Gulp任务成功运行Jasmine规范进行单元测试,现在我需要构建集成测试来验证localhost完整网页。 I'm using the gulp-jasmine-browser plugin to run PhantomJS. 我正在使用gulp-jasmine-browser插件来运行PhantomJS。

Example: 例:

gulpfile.js 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);


spec/cart-spec.js 规格/车,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);
      });

   });

There is no loadWebPage() function. 没有loadWebPage()函数。 It's just to illustrate the functionality I believe is needed. 这只是为了说明我认为需要的功能。

End-to-End testing frameworks like a Selenium , WebdriverIO , Nightwatch.js , Protractor and so on are more suitable in such case. SeleniumWebdriverIONightwatch.jsProtractor等端到端测试框架更适合这种情况。

The gulp-jasmine-browser plugin still is about the Unit testing in the browser environment. gulp-jasmine-browser插件仍然是关于浏览器环境中的单元测试。 It is not possible to navigate between pages. 无法在页面之间导航。

I put together the following code that appears to work. 我把以下似乎有用的代码放在一起。 Please feel free to check out my repo and confirm in your own environment. 请随时查看我的回购并在您自己的环境中确认。

package.json 的package.json

{
  "name": "40646680",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "gulp jasmine"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-jasmine-browser": "^1.7.1",
    "jasmine": "^2.5.2",
    "phantomjs": "^2.1.7"
  }
}

gulpfile.js gulpfile.js

(() => {
    "use strict";

    var gulp = require("gulp"),
        jasmineBrowser = require("gulp-jasmine-browser");

    gulp.task("jasmine", () => {
        return gulp.src("test/*.js")
            .pipe(jasmineBrowser.specRunner({
                console: true
            }))
            .pipe(jasmineBrowser.headless());
    });
})();

test/sampleJasmine.js 测试/ sampleJasmine.js

describe("A suite", function() {
    it("contains spec with an expectation", function() {
        expect(true).toBe(true);
    });
    it("contains failing spec with an expectation", function() {
        expect(true).toBe(false);
    });
});

Execution 执行

Bob Chatman@CHATBAG42 F:\Development\StackOverflow\40646680
> npm test

> 40646680@1.0.0 test F:\Development\StackOverflow\40646680
> gulp jasmine

[21:56:44] Using gulpfile F:\Development\StackOverflow\40646680\gulpfile.js
[21:56:44] Starting 'jasmine'...
[21:56:44] Jasmine server listening on port 8000
.F
Failures:
1) A suite contains failing spec with an expectation
1.1) Expected true to be false.

2 specs, 1 failure
Finished in 0 seconds
[21:56:49] 'jasmine' errored after 4.26 s
[21:56:49] Error in plugin 'gulp-jasmine-browser'
Message:
    1 failure
npm ERR! Test failed.  See above for more details.

Dependencies 依赖

node 7.2
npm 3.9.3
jasmine 2.5.2
phantomjs 2.1.7 
gulp 3.9.1

jsdom to the rescue! jsdom救援!

It turns out it's pretty easy to load a web page into a headless Jasmine spec... but you need to swap out PhantomJS for jsdom . 事实证明,将网页加载到无头的Jasmine规范中非常容易......但是你需要换掉PhantomJS用于jsdom

Strategy: 战略:

  1. Use Jasmine's beforeAll() to call a function that will run JSDOM.fromURL() to request the web page. 使用Jasmine的beforeAll()来调用一个函数,该函数将运行JSDOM.fromURL()来请求网页。
  2. Once the web page has been loaded into the DOM, expose window and jQuery for use in your test cases. 将网页加载到DOM后,公开windowjQuery以便在测试用例中使用。
  3. Finally, call done() to indicate the tests are now ready to run. 最后,调用done()表示测试现在可以运行了。

Make sure to close the window after the tests have run. 确保在测试运行后关闭window

spec.js spec.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);
      });

   });


Test output 测试输出

截图
Note: Above screenshot is from a similar Mocha spec since Mocha has a nice default reporter. 注意:上面的截图来自类似的Mocha规范,因为Mocha有一个不错的默认记者。

Project 项目

It's on GitHub if you want try it out yourself: 如果你想自己尝试一下,它就在GitHub上:
https://github.com/dnajs/load-web-page-jsdom-jasmine https://github.com/dnajs/load-web-page-jsdom-jasmine


EDITED: Updated for jsdom 11 编辑:更新了jsdom 11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM