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()功能.这只是为了说明我认为需要的功能.
事实证明,将网页加载到无头 Jasmine 规范中非常容易……但是您需要将 PhantomJS 替换为jsdom。
战略:
beforeAll()函数。JSDOM.fromURL()window并jQuery在测试用例中使用。done()表明测试现已准备好运行。window确保在测试运行后关闭。
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 进行了更新
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |