Commit c9b4c740 authored by JC Brand's avatar JC Brand

Exploring using karma

parent 74eed32e
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"plugins": ["lodash"], "plugins": ["lodash"],
"extends": ["eslint:recommended", "plugin:lodash/canonical"], "extends": ["eslint:recommended", "plugin:lodash/canonical"],
"globals": { "globals": {
"module": true,
"window": true, "window": true,
"sinon": true, "sinon": true,
"define": true, "define": true,
......
...@@ -11,11 +11,7 @@ ...@@ -11,11 +11,7 @@
<link rel="shortcut icon" type="image/ico" href="css/images/favicon.ico"/> <link rel="shortcut icon" type="image/ico" href="css/images/favicon.ico"/>
<link type="text/css" rel="stylesheet" media="screen" href="css/fullpage.css" /> <link type="text/css" rel="stylesheet" media="screen" href="css/fullpage.css" />
<link type="text/css" rel="stylesheet" media="screen" href="css/converse.css" /> <link type="text/css" rel="stylesheet" media="screen" href="css/converse.css" />
<script src="dist/converse.js"></script>
<![if gte IE 11]>
<link type="text/css" rel="stylesheet" media="screen" href="css/converse.css" />
<script src="dist/converse.js"></script>
<![endif]>
</head> </head>
<body class="reset"> <body class="reset">
......
// Karma configuration
// Generated on Sat Jun 02 2018 22:33:35 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'dist/converse.js',
'tests/utils.js',
'tests/mock.js',
'spec/messages.js'
],
// list of files / patterns to exclude
exclude: ['*.min.js'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -12,7 +12,7 @@ if (typeof(require) === 'undefined') { ...@@ -12,7 +12,7 @@ if (typeof(require) === 'undefined') {
}; };
} }
require.config({ window.config = {
baseUrl: '.', baseUrl: '.',
paths: { paths: {
"IPv6": "node_modules/urijs/src/IPv6", "IPv6": "node_modules/urijs/src/IPv6",
......
...@@ -11,9 +11,8 @@ ...@@ -11,9 +11,8 @@
<link rel="stylesheet" type="text/css" media="screen" href="../css/jasmine.css"> <link rel="stylesheet" type="text/css" media="screen" href="../css/jasmine.css">
<link type="text/css" rel="stylesheet" media="screen" href="../css/website.css" /> <link type="text/css" rel="stylesheet" media="screen" href="../css/website.css" />
<link type="text/css" rel="stylesheet" media="screen" href="../css/converse.css" /> <link type="text/css" rel="stylesheet" media="screen" href="../css/converse.css" />
<script src="dist/converse.js"></script>
<script src="../src/config.js"></script> <script src="runner.js"></script>
<script data-main="runner" src="../node_modules/requirejs/require.js"></script>
<style> <style>
.tests-brand-heading { .tests-brand-heading {
......
(function (root, factory) { var _ = converse.env._;
define("mock", ['converse'], factory); var Promise = converse.env.Promise;
}(this, function (converse) { var Strophe = converse.env.Strophe;
var _ = converse.env._; var $iq = converse.env.$iq;
var Promise = converse.env.Promise; window.mock = {};
var Strophe = converse.env.Strophe;
var $iq = converse.env.$iq;
var mock = {};
mock.view_mode = 'overlayed'; mock.view_mode = 'overlayed';
// Names from http://www.fakenamegenerator.com/ // Names from http://www.fakenamegenerator.com/
mock.req_names = [ mock.req_names = [
'Louw Spekman', 'Mohamad Stet', 'Dominik Beyer' 'Louw Spekman', 'Mohamad Stet', 'Dominik Beyer'
]; ];
mock.pend_names = [ mock.pend_names = [
'Suleyman van Beusichem', 'Nanja van Yperen', 'Nicole Diederich' 'Suleyman van Beusichem', 'Nanja van Yperen', 'Nicole Diederich'
]; ];
mock.cur_names = [ mock.cur_names = [
'Max Frankfurter', 'Candice van der Knijff', 'Irini Vlastuin', 'Rinse Sommer', 'Annegreet Gomez', 'Max Frankfurter', 'Candice van der Knijff', 'Irini Vlastuin', 'Rinse Sommer', 'Annegreet Gomez',
'Robin Schook', 'Marcel Eberhardt', 'Simone Brauer', 'Asmaa Haakman', 'Felix Amsel', 'Robin Schook', 'Marcel Eberhardt', 'Simone Brauer', 'Asmaa Haakman', 'Felix Amsel',
'Lena Grunewald', 'Laura Grunewald', 'Mandy Seiler', 'Sven Bosch', 'Nuriye Cuypers' 'Lena Grunewald', 'Laura Grunewald', 'Mandy Seiler', 'Sven Bosch', 'Nuriye Cuypers'
]; ];
mock.num_contacts = mock.req_names.length + mock.pend_names.length + mock.cur_names.length; mock.num_contacts = mock.req_names.length + mock.pend_names.length + mock.cur_names.length;
mock.groups = { mock.groups = {
'colleagues': 3, 'colleagues': 3,
'friends & acquaintences': 3, 'friends & acquaintences': 3,
'Family': 4, 'Family': 4,
'ænemies': 3, 'ænemies': 3,
'Ungrouped': 2 'Ungrouped': 2
}; };
mock.chatroom_names = [ mock.chatroom_names = [
'Dyon van de Wege', 'Thomas Kalb', 'Dirk Theissen', 'Felix Hofmann', 'Ka Lek', 'Anne Ebersbacher' 'Dyon van de Wege', 'Thomas Kalb', 'Dirk Theissen', 'Felix Hofmann', 'Ka Lek', 'Anne Ebersbacher'
]; ];
// TODO: need to also test other roles and affiliations // TODO: need to also test other roles and affiliations
mock.chatroom_roles = { mock.chatroom_roles = {
'Anne Ebersbacher': { affiliation: "owner", role: "moderator" }, 'Anne Ebersbacher': { affiliation: "owner", role: "moderator" },
'Dirk Theissen': { affiliation: "admin", role: "moderator" }, 'Dirk Theissen': { affiliation: "admin", role: "moderator" },
'Dyon van de Wege': { affiliation: "member", role: "occupant" }, 'Dyon van de Wege': { affiliation: "member", role: "occupant" },
'Felix Hofmann': { affiliation: "member", role: "occupant" }, 'Felix Hofmann': { affiliation: "member", role: "occupant" },
'Ka Lek': { affiliation: "member", role: "occupant" }, 'Ka Lek': { affiliation: "member", role: "occupant" },
'Thomas Kalb': { affiliation: "member", role: "occupant" } 'Thomas Kalb': { affiliation: "member", role: "occupant" }
}; };
mock.event = { mock.event = {
'preventDefault': function () {} 'preventDefault': function () {}
}; };
mock.mock_connection = function () { // eslint-disable-line wrap-iife mock.mock_connection = function () { // eslint-disable-line wrap-iife
return function () { return function () {
Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas
var c = new Strophe.Connection('jasmine tests'); var c = new Strophe.Connection('jasmine tests');
var sendIQ = c.sendIQ; var sendIQ = c.sendIQ;
c.IQ_stanzas = []; c.IQ_stanzas = [];
c.IQ_ids = []; c.IQ_ids = [];
c.sendIQ = function (iq, callback, errback) { c.sendIQ = function (iq, callback, errback) {
this.IQ_stanzas.push(iq); this.IQ_stanzas.push(iq);
var id = sendIQ.bind(this)(iq, callback, errback); var id = sendIQ.bind(this)(iq, callback, errback);
this.IQ_ids.push(id); this.IQ_ids.push(id);
return id; return id;
} }
c._proto._connect = function () { c._proto._connect = function () {
c.authenticated = true; c.authenticated = true;
c.connected = true; c.connected = true;
c.mock = true; c.mock = true;
c.jid = 'dummy@localhost/resource'; c.jid = 'dummy@localhost/resource';
c._changeConnectStatus(Strophe.Status.CONNECTED); c._changeConnectStatus(Strophe.Status.CONNECTED);
};
return c;
}; };
}(); return c;
};
}();
function initConverse (settings, spies, promises) { function initConverse (settings, spies, promises) {
window.localStorage.clear(); window.localStorage.clear();
window.sessionStorage.clear(); window.sessionStorage.clear();
var connection = mock.mock_connection(); var connection = mock.mock_connection();
if (!_.isUndefined(spies)) { if (!_.isUndefined(spies)) {
_.forEach(spies, function (method) { _.forEach(spies, function (method) {
spyOn(connection, method); spyOn(connection, method);
}); });
} }
var _converse = converse.initialize(_.extend({ var _converse = converse.initialize(_.extend({
'i18n': 'en', 'i18n': 'en',
'auto_subscribe': false, 'auto_subscribe': false,
'play_sounds': false, 'play_sounds': false,
'bosh_service_url': 'localhost', 'bosh_service_url': 'localhost',
'connection': connection, 'connection': connection,
'animate': false, 'animate': false,
'use_emojione': false, 'use_emojione': false,
'no_trimming': true, 'no_trimming': true,
'view_mode': mock.view_mode, 'view_mode': mock.view_mode,
'debug': false 'debug': false
}, settings || {})); }, settings || {}));
_converse.ChatBoxViews.prototype.trimChat = function () {}; _converse.ChatBoxViews.prototype.trimChat = function () {};
_converse.api.vcard.get = function (model, force) { _converse.api.vcard.get = function (model, force) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let jid; let jid;
if (_.isString(model)) { if (_.isString(model)) {
jid = model; jid = model;
} else if (!model.get('vcard_updated') || force) { } else if (!model.get('vcard_updated') || force) {
jid = model.get('jid') || model.get('muc_jid'); jid = model.get('jid') || model.get('muc_jid');
} }
var fullname; var fullname;
if (!jid || jid == 'dummy@localhost') { if (!jid || jid == 'dummy@localhost') {
jid = 'dummy@localhost'; jid = 'dummy@localhost';
fullname = 'Max Mustermann' ; fullname = 'Max Mustermann' ;
} else { } else {
var name = jid.split('@')[0].replace(/\./g, ' ').split(' '); var name = jid.split('@')[0].replace(/\./g, ' ').split(' ');
var last = name.length-1; var last = name.length-1;
name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1); name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1);
name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1); name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1);
fullname = name.join(' '); fullname = name.join(' ');
} }
var vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree; var vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree;
var result = { var result = {
'stanza': vcard, 'stanza': vcard,
'fullname': _.get(vcard.querySelector('FN'), 'textContent'), 'fullname': _.get(vcard.querySelector('FN'), 'textContent'),
'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'), 'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'),
'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'), 'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'),
'url': _.get(vcard.querySelector('URL'), 'textContent') 'url': _.get(vcard.querySelector('URL'), 'textContent')
}; };
resolve(result); resolve(result);
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL)); }).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}; };
if (_.get(settings, 'auto_login') !== false) { if (_.get(settings, 'auto_login') !== false) {
_converse.api.user.login({ _converse.api.user.login({
'jid': 'dummy@localhost', 'jid': 'dummy@localhost',
'password': 'secret' 'password': 'secret'
}); });
}
window.converse_disable_effects = true;
return _converse;
} }
window.converse_disable_effects = true;
return _converse;
}
mock.initConverseWithPromises = function (spies, promise_names, settings, func) { mock.initConverseWithPromises = function (spies, promise_names, settings, func) {
return function (done) { return function (done) {
var _converse = initConverse(settings, spies); var _converse = initConverse(settings, spies);
var promises = _.map(promise_names, _converse.api.waitUntil); var promises = _.map(promise_names, _converse.api.waitUntil);
Promise.all(promises) Promise.all(promises)
.then(_.partial(func, done, _converse)) .then(_.partial(func, done, _converse))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL)); .catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
} }
}; };
mock.initConverseWithConnectionSpies = function (spies, settings, func) { mock.initConverseWithConnectionSpies = function (spies, settings, func) {
return function (done) { return function (done) {
return func(done, initConverse(settings, spies)); return func(done, initConverse(settings, spies));
};
}; };
};
mock.initConverseWithAsync = function (settings, func) { mock.initConverseWithAsync = function (settings, func) {
if (_.isFunction(settings)) { if (_.isFunction(settings)) {
var _func = settings; var _func = settings;
settings = func; settings = func;
func = _func; func = _func;
} }
return function (done) { return function (done) {
return func(done, initConverse(settings)); return func(done, initConverse(settings));
};
}; };
mock.initConverse = function (settings, func) { };
if (_.isFunction(settings)) { mock.initConverse = function (settings, func) {
var _func = settings; if (_.isFunction(settings)) {
settings = func; var _func = settings;
func = _func; settings = func;
} func = _func;
return function () { }
return func(initConverse(settings)); return function () {
}; return func(initConverse(settings));
}; };
return mock; };
}));
/*global config */
var config = {
baseUrl: '/base/',
paths: {
"console-reporter": "tests/console-reporter",
"IPv6": "node_modules/urijs/src/IPv6",
"SecondLevelDomains": "node_modules/urijs/src/SecondLevelDomains",
"almond": "node_modules/almond/almond",
"awesomplete": "node_modules/awesomplete-avoid-xss/awesomplete",
"babel": "node_modules/requirejs-babel/babel-5.8.34.min",
"backbone": "node_modules/backbone/backbone",
"backbone.browserStorage": "node_modules/backbone.browserStorage/backbone.browserStorage",
"backbone.nativeview": "node_modules/backbone.nativeview/backbone.nativeview",
"backbone.noconflict": "src/backbone.noconflict",
"backbone.orderedlistview": "node_modules/backbone.overview/dist/backbone.orderedlistview",
"backbone.overview": "node_modules/backbone.overview/dist/backbone.overview",
"backbone.vdomview": "node_modules/backbone.vdomview/dist/backbone.vdomview",
"bootstrap": "node_modules/bootstrap.native/dist/bootstrap-native-v4",
"emojione": "node_modules/emojione/lib/js/emojione",
"es6-promise": "node_modules/es6-promise/dist/es6-promise.auto",
"eventemitter": "node_modules/otr/build/dep/eventemitter",
"filesize": "node_modules/filesize/lib/filesize",
"form-utils": "src/utils/form",
"i18n": "src/i18n",
"jed": "node_modules/jed/jed",
"jquery": "src/jquery-stub",
"lodash": "node_modules/lodash/lodash",
"lodash.converter": "3rdparty/lodash.fp",
"lodash.fp": "src/lodash.fp",
"lodash.noconflict": "src/lodash.noconflict",
"message-utils": "src/utils/message",
"muc-utils": "src/utils/muc",
"pluggable": "node_modules/pluggable.js/dist/pluggable",
"polyfill": "src/polyfill",
"punycode": "node_modules/urijs/src/punycode",
"sizzle": "node_modules/sizzle/dist/sizzle",
"snabbdom": "node_modules/snabbdom/dist/snabbdom",
"snabbdom-attributes": "node_modules/snabbdom/dist/snabbdom-attributes",
"snabbdom-class": "node_modules/snabbdom/dist/snabbdom-class",
"snabbdom-dataset": "node_modules/snabbdom/dist/snabbdom-dataset",
"snabbdom-eventlisteners": "node_modules/snabbdom/dist/snabbdom-eventlisteners",
"snabbdom-props": "node_modules/snabbdom/dist/snabbdom-props",
"snabbdom-style": "node_modules/snabbdom/dist/snabbdom-style",
"strophe": "node_modules/strophe.js/strophe",
"strophe.ping": "node_modules/strophejs-plugin-ping/strophe.ping",
"strophe.rsm": "node_modules/strophejs-plugin-rsm/strophe.rsm",
"text": "node_modules/text/text",
"tovnode": "node_modules/snabbdom/dist/tovnode",
"tpl": "node_modules/lodash-template-loader/loader",
"underscore": "src/underscore-shim",
"uri": "node_modules/urijs/src/URI",
"utils": "src/utils/core",
"vdom-parser": "node_modules/vdom-parser/dist",
"xss": "node_modules/xss/dist/xss",
"xss.noconflict": "src/xss.noconflict",
// Converse
"converse": "src/converse",
"converse-bookmarks": "src/converse-bookmarks",
"converse-chatboxes": "src/converse-chatboxes",
"converse-caps": "src/converse-caps",
"converse-chatview": "src/converse-chatview",
"converse-controlbox": "src/converse-controlbox",
"converse-core": "src/converse-core",
"converse-disco": "src/converse-disco",
"converse-dragresize": "src/converse-dragresize",
"converse-embedded": "src/converse-embedded",
"converse-fullscreen": "src/converse-fullscreen",
"converse-headline": "src/converse-headline",
"converse-mam": "src/converse-mam",
"converse-message-view": "src/converse-message-view",
"converse-minimize": "src/converse-minimize",
"converse-modal": "src/converse-modal",
"converse-muc": "src/converse-muc",
"converse-muc-views": "src/converse-muc-views",
"converse-notification": "src/converse-notification",
"converse-otr": "src/converse-otr",
"converse-ping": "src/converse-ping",
"converse-profile": "src/converse-profile",
"converse-register": "src/converse-register",
"converse-roomslist": "src/converse-roomslist",
"converse-roster": "src/converse-roster",
"converse-rosterview": "src/converse-rosterview",
"converse-singleton": "src/converse-singleton",
"converse-vcard": "src/converse-vcard",
// Off-the-record-encryption
// "bigint": "node_modules/otr/build/dep/bigint",
"bigint": "3rdparty/bigint",
"crypto": "node_modules/otr/build/dep/crypto",
"salsa20": "node_modules/otr/build/dep/salsa20",
"otr": "node_modules/otr/build/otr",
},
packages: [{
'name': 'moment',
'location': 'node_modules/moment',
'main': 'moment'
}],
map: {
// '*' means all modules will get the '*.noconflict' version
// as their dependency.
'*': {
'backbone': 'backbone.noconflict',
'lodash': 'lodash.noconflict'
},
// '*.noconflict' wants the real module
// If this line was not here, there would
// be an unresolvable cyclic dependency.
'backbone.noconflict': { 'backbone': 'backbone' },
'lodash.noconflict': { 'lodash': 'lodash' }
},
lodashLoader: {
// Configuration for requirejs-tpl
// Use Mustache style syntax for variable interpolation
root: "src/templates/",
templateSettings: {
"escape": /\{\{\{([\s\S]+?)\}\}\}/g,
"evaluate": /\{\[([\s\S]+?)\]\}/g,
"interpolate": /\{\{([\s\S]+?)\}\}/g,
// By default, template places the values from your data in the
// local scope via the with statement. However, you can specify
// a single variable name with the variable setting. This can
// significantly improve the speed at which a template is able
// to render.
"variable": 'o'
}
},
// define module dependencies for modules not using define
shim: {
'backbone.orderedlistview': { deps: ['backbone.nativeview'] },
'backbone.overview': { deps: ['backbone.nativeview'] },
'backbone.vdomview': { deps: ['backbone.nativeview'] },
'awesomplete': { exports: 'Awesomplete'},
'emojione': { exports: 'emojione'},
'xss': {
'init': function (xss_noconflict) {
return {
filterXSS: window.filterXSS,
filterCSS: window.filterCSS
}
}
}
}
};
// Extra test dependencies // Extra test dependencies
config.baseUrl = '../';
config.paths.jquery = "node_modules/jquery/dist/jquery"; config.paths.jquery = "node_modules/jquery/dist/jquery";
config.paths.mock = "tests/mock"; config.paths.mock = "tests/mock";
config.paths['wait-until-promise'] = "node_modules/wait-until-promise/index"; config.paths['wait-until-promise'] = "node_modules/wait-until-promise/index";
...@@ -11,7 +159,6 @@ config.paths.transcripts = "converse-logs/converse-logs"; ...@@ -11,7 +159,6 @@ config.paths.transcripts = "converse-logs/converse-logs";
config.paths["jasmine-core"] = "node_modules/jasmine-core/lib/jasmine-core/jasmine"; config.paths["jasmine-core"] = "node_modules/jasmine-core/lib/jasmine-core/jasmine";
config.paths.jasmine = "node_modules/jasmine-core/lib/jasmine-core/boot"; config.paths.jasmine = "node_modules/jasmine-core/lib/jasmine-core/boot";
config.paths["jasmine-console"] = "node_modules/jasmine-core/lib/console/console"; config.paths["jasmine-console"] = "node_modules/jasmine-core/lib/console/console";
config.paths["console-reporter"] = "tests/console-reporter";
config.paths["jasmine-html"] = "node_modules/jasmine-core/lib/jasmine-core/jasmine-html"; config.paths["jasmine-html"] = "node_modules/jasmine-core/lib/jasmine-core/jasmine-html";
config.shim.jasmine = { config.shim.jasmine = {
exports: 'window.jasmineRequire' exports: 'window.jasmineRequire'
...@@ -28,7 +175,7 @@ config.shim.jasmine = { ...@@ -28,7 +175,7 @@ config.shim.jasmine = {
deps: ['jasmine-core', 'jasmine-html', 'jasmine-console'], deps: ['jasmine-core', 'jasmine-html', 'jasmine-console'],
exports: 'window.jasmine' exports: 'window.jasmine'
}; };
require.config(config);
var specs = [ var specs = [
"jasmine", "jasmine",
...@@ -61,20 +208,26 @@ var specs = [ ...@@ -61,20 +208,26 @@ var specs = [
"spec/http-file-upload" "spec/http-file-upload"
]; ];
require(['console-reporter', 'mock', 'sinon', 'wait-until-promise', 'pluggable'], config.deps = specs;
function(ConsoleReporter, mock, sinon, waitUntilPromise, pluggable) { config.callback = window.__karma__.start;
if (config.view_mode) { require.config(config);
mock.view_mode = config.view_mode;
} // require(['console-reporter', 'mock', 'sinon', 'wait-until-promise', 'pluggable'],
window.sinon = sinon; // function(ConsoleReporter, mock, sinon, waitUntilPromise, pluggable) {
window.waitUntilPromise = waitUntilPromise.default; //
window.localStorage.clear(); // debugger;
window.sessionStorage.clear(); // if (config.view_mode) {
// Load the specs // mock.view_mode = config.view_mode;
require(specs, function (jasmine) { // }
var jasmineEnv = jasmine.getEnv(); // window.sinon = sinon;
jasmineEnv.addReporter(new ConsoleReporter()); // window.waitUntilPromise = waitUntilPromise.default;
window.onload(); // window.localStorage.clear();
}); // window.sessionStorage.clear();
}); // // Load the specs
// require(specs, function (jasmine) {
// var jasmineEnv = jasmine.getEnv();
// jasmineEnv.addReporter(new ConsoleReporter());
// window.onload();
// });
// });
(function (root, factory) { var _ = converse.env._;
define(['converse', 'es6-promise', 'mock', 'wait-until-promise'], factory); var $msg = converse.env.$msg;
}(this, function (converse_api, Promise, mock, waitUntilPromise) { var $pres = converse.env.$pres;
var _ = converse_api.env._; var $iq = converse.env.$iq;
var $msg = converse_api.env.$msg; var Strophe = converse.env.Strophe;
var $pres = converse_api.env.$pres; var u = converse.env.utils;
var $iq = converse_api.env.$iq; var utils = {};
var Strophe = converse_api.env.Strophe;
var u = converse_api.env.utils;
var utils = {};
if (typeof window.Promise === 'undefined') { if (typeof window.Promise === 'undefined') {
waitUntilPromise.setPromiseImplementation(Promise); waitUntilPromise.setPromiseImplementation(Promise);
} }
utils.waitUntil = waitUntilPromise.default; utils.waitUntil = waitUntilPromise.default;
utils.waitUntilDiscoConfirmed = function (_converse, entity_jid, identities, features, items, type) {
if (_.isNil(type)) {
type = 'info';
}
var IQ_disco, stanza;
return utils.waitUntil(function () {
IQ_disco = _.filter(_converse.connection.IQ_stanzas, function (iq) {
return iq.nodeTree.querySelector('query[xmlns="http://jabber.org/protocol/disco#'+type+'"]') &&
iq.nodeTree.getAttribute('to') === entity_jid;
}).pop();
return !_.isUndefined(IQ_disco);
}, 300).then(function () {
var info_IQ_id = IQ_disco.nodeTree.getAttribute('id');
var stanza = $iq({
'type': 'result',
'from': entity_jid,
'to': 'dummy@localhost/resource',
'id': info_IQ_id
}).c('query', {'xmlns': 'http://jabber.org/protocol/disco#'+type});
_.forEach(identities, function (identity) { utils.waitUntilDiscoConfirmed = function (_converse, entity_jid, identities, features, items, type) {
stanza.c('identity', {'category': identity.category, 'type': identity.type}).up() if (_.isNil(type)) {
}); type = 'info';
_.forEach(features, function (feature) {
stanza.c('feature', {'var': feature}).up();
});
_.forEach(items, function (item) {
stanza.c('item', {'jid': item}).up();
});
_converse.connection._dataRecv(utils.createRequest(stanza));
}).catch(_.partial(console.error, _));
} }
var IQ_disco, stanza;
return utils.waitUntil(function () {
IQ_disco = _.filter(_converse.connection.IQ_stanzas, function (iq) {
return iq.nodeTree.querySelector('query[xmlns="http://jabber.org/protocol/disco#'+type+'"]') &&
iq.nodeTree.getAttribute('to') === entity_jid;
}).pop();
return !_.isUndefined(IQ_disco);
}, 300).then(function () {
var info_IQ_id = IQ_disco.nodeTree.getAttribute('id');
var stanza = $iq({
'type': 'result',
'from': entity_jid,
'to': 'dummy@localhost/resource',
'id': info_IQ_id
}).c('query', {'xmlns': 'http://jabber.org/protocol/disco#'+type});
utils.createRequest = function (iq) { _.forEach(identities, function (identity) {
iq = typeof iq.tree == "function" ? iq.tree() : iq; stanza.c('identity', {'category': identity.category, 'type': identity.type}).up()
var req = new Strophe.Request(iq, function() {}); });
req.getResponse = function () { _.forEach(features, function (feature) {
var env = new Strophe.Builder('env', {type: 'mock'}).tree(); stanza.c('feature', {'var': feature}).up();
env.appendChild(iq); });
return env; _.forEach(items, function (item) {
}; stanza.c('item', {'jid': item}).up();
return req; });
}; _converse.connection._dataRecv(utils.createRequest(stanza));
}).catch(_.partial(console.error, _));
}
utils.closeAllChatBoxes = function (converse) { utils.createRequest = function (iq) {
var i, chatbox; iq = typeof iq.tree == "function" ? iq.tree() : iq;
for (i=converse.chatboxes.models.length-1; i>-1; i--) { var req = new Strophe.Request(iq, function() {});
chatbox = converse.chatboxes.models[i]; req.getResponse = function () {
converse.chatboxviews.get(chatbox.get('id')).close(); var env = new Strophe.Builder('env', {type: 'mock'}).tree();
} env.appendChild(iq);
return this; return env;
}; };
return req;
};
utils.openControlBox = function () { utils.closeAllChatBoxes = function (converse) {
var toggle = document.querySelector(".toggle-controlbox"); var i, chatbox;
if (!u.isVisible(document.querySelector("#controlbox"))) { for (i=converse.chatboxes.models.length-1; i>-1; i--) {
if (!u.isVisible(toggle)) { chatbox = converse.chatboxes.models[i];
u.removeClass('hidden', toggle); converse.chatboxviews.get(chatbox.get('id')).close();
} }
toggle.click(); return this;
} };
return this;
};
utils.closeControlBox = function () { utils.openControlBox = function () {
var controlbox = document.querySelector("#controlbox"); var toggle = document.querySelector(".toggle-controlbox");
if (u.isVisible(controlbox)) { if (!u.isVisible(document.querySelector("#controlbox"))) {
var button = controlbox.querySelector(".close-chatbox-button"); if (!u.isVisible(toggle)) {
if (!_.isNull(button)) { u.removeClass('hidden', toggle);
button.click();
}
} }
return this; toggle.click();
}; }
return this;
};
utils.openChatBoxes = function (converse, amount) { utils.closeControlBox = function () {
var i = 0, jid, views = []; var controlbox = document.querySelector("#controlbox");
for (i; i<amount; i++) { if (u.isVisible(controlbox)) {
jid = mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost'; var button = controlbox.querySelector(".close-chatbox-button");
views[i] = converse.roster.get(jid).trigger("open"); if (!_.isNull(button)) {
button.click();
} }
return views; }
}; return this;
};
utils.openChatBoxFor = function (converse, jid) { utils.openChatBoxes = function (converse, amount) {
return converse.roster.get(jid).trigger("open"); var i = 0, jid, views = [];
}; for (i; i<amount; i++) {
jid = mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost';
views[i] = converse.roster.get(jid).trigger("open");
}
return views;
};
utils.openChatBoxFor = function (converse, jid) {
return converse.roster.get(jid).trigger("open");
};
utils.openChatRoomViaModal = function (_converse, jid, nick) { utils.openChatRoomViaModal = function (_converse, jid, nick) {
// Opens a new chatroom // Opens a new chatroom
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
utils.openControlBox(_converse); utils.openControlBox(_converse);
var roomspanel = _converse.chatboxviews.get('controlbox').roomspanel; var roomspanel = _converse.chatboxviews.get('controlbox').roomspanel;
roomspanel.el.querySelector('.trigger-add-chatrooms-modal').click(); roomspanel.el.querySelector('.trigger-add-chatrooms-modal').click();
utils.closeControlBox(_converse); utils.closeControlBox(_converse);
const modal = roomspanel.add_room_modal; const modal = roomspanel.add_room_modal;
utils.waitUntil(function () { utils.waitUntil(function () {
return u.isVisible(modal.el); return u.isVisible(modal.el);
}, 1000).then(function () { }, 1000).then(function () {
modal.el.querySelector('input[name="chatroom"]').value = jid; modal.el.querySelector('input[name="chatroom"]').value = jid;
modal.el.querySelector('form input[type="submit"]').click(); modal.el.querySelector('form input[type="submit"]').click();
resolve(); resolve();
}).catch(_.partial(console.error, _));
}).catch(_.partial(console.error, _)); }).catch(_.partial(console.error, _));
}; }).catch(_.partial(console.error, _));
};
utils.openChatRoom = function (_converse, room, server, nick) { utils.openChatRoom = function (_converse, room, server, nick) {
_converse.api.rooms.open(`${room}@${server}`); _converse.api.rooms.open(`${room}@${server}`);
}; };
utils.openAndEnterChatRoom = function (_converse, room, server, nick) { utils.openAndEnterChatRoom = function (_converse, room, server, nick) {
let last_stanza; let last_stanza;
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
_converse.api.rooms.open(`${room}@${server}`); _converse.api.rooms.open(`${room}@${server}`);
const view = _converse.chatboxviews.get((room+'@'+server).toLowerCase()); const view = _converse.chatboxviews.get((room+'@'+server).toLowerCase());
// We pretend this is a new room, so no disco info is returned. // We pretend this is a new room, so no disco info is returned.
let last_stanza = _.last(_converse.connection.IQ_stanzas).nodeTree; let last_stanza = _.last(_converse.connection.IQ_stanzas).nodeTree;
const IQ_id = last_stanza.getAttribute('id'); const IQ_id = last_stanza.getAttribute('id');
const features_stanza = $iq({ const features_stanza = $iq({
'from': room+'@'+server, 'from': room+'@'+server,
'id': IQ_id, 'id': IQ_id,
'to': nick+'@'+server, 'to': nick+'@'+server,
'type': 'error' 'type': 'error'
}).c('error', {'type': 'cancel'}) }).c('error', {'type': 'cancel'})
.c('item-not-found', {'xmlns': "urn:ietf:params:xml:ns:xmpp-stanzas"}); .c('item-not-found', {'xmlns': "urn:ietf:params:xml:ns:xmpp-stanzas"});
_converse.connection._dataRecv(utils.createRequest(features_stanza)); _converse.connection._dataRecv(utils.createRequest(features_stanza));
utils.waitUntil(() => { utils.waitUntil(() => {
return _.filter( return _.filter(
_converse.connection.IQ_stanzas, (node) => { _converse.connection.IQ_stanzas, (node) => {
const query = node.nodeTree.querySelector('query'); const query = node.nodeTree.querySelector('query');
if (query && query.getAttribute('node') === 'x-roomuser-item') { if (query && query.getAttribute('node') === 'x-roomuser-item') {
last_stanza = node.nodeTree; last_stanza = node.nodeTree;
return true; return true;
} }
}).length }).length
}).then(function () { }).then(function () {
// The XMPP server returns the reserved nick for this user. // The XMPP server returns the reserved nick for this user.
const IQ_id = last_stanza.getAttribute('id'); const IQ_id = last_stanza.getAttribute('id');
const stanza = $iq({ const stanza = $iq({
'type': 'result', 'type': 'result',
'id': IQ_id, 'id': IQ_id,
'from': view.model.get('jid'), 'from': view.model.get('jid'),
'to': _converse.connection.jid 'to': _converse.connection.jid
}).c('query', {'xmlns': 'http://jabber.org/protocol/disco#info', 'node': 'x-roomuser-item'}) }).c('query', {'xmlns': 'http://jabber.org/protocol/disco#info', 'node': 'x-roomuser-item'})
.c('identity', {'category': 'conference', 'name': nick, 'type': 'text'}); .c('identity', {'category': 'conference', 'name': nick, 'type': 'text'});
_converse.connection._dataRecv(utils.createRequest(stanza)); _converse.connection._dataRecv(utils.createRequest(stanza));
// The user has just entered the room (because join was called) // The user has just entered the room (because join was called)
// and receives their own presence from the server. // and receives their own presence from the server.
// See example 24: http://xmpp.org/extensions/xep-0045.html#enter-pres // See example 24: http://xmpp.org/extensions/xep-0045.html#enter-pres
var presence = $pres({ var presence = $pres({
to: _converse.connection.jid, to: _converse.connection.jid,
from: room+'@'+server+'/'+nick, from: room+'@'+server+'/'+nick,
id: 'DC352437-C019-40EC-B590-AF29E879AF97' id: 'DC352437-C019-40EC-B590-AF29E879AF97'
}).c('x').attrs({xmlns:'http://jabber.org/protocol/muc#user'}) }).c('x').attrs({xmlns:'http://jabber.org/protocol/muc#user'})
.c('item').attrs({ .c('item').attrs({
affiliation: 'member', affiliation: 'member',
jid: _converse.bare_jid, jid: _converse.bare_jid,
role: 'participant' role: 'participant'
}).up() }).up()
.c('status').attrs({code:'110'}); .c('status').attrs({code:'110'});
_converse.connection._dataRecv(utils.createRequest(presence)); _converse.connection._dataRecv(utils.createRequest(presence));
resolve(); resolve();
}).catch(_.partial(console.error, _));
}).catch(_.partial(console.error, _)); }).catch(_.partial(console.error, _));
}; }).catch(_.partial(console.error, _));
};
utils.clearBrowserStorage = function () { utils.clearBrowserStorage = function () {
window.localStorage.clear(); window.localStorage.clear();
window.sessionStorage.clear(); window.sessionStorage.clear();
return this; return this;
}; };
utils.clearChatBoxMessages = function (converse, jid) { utils.clearChatBoxMessages = function (converse, jid) {
var view = converse.chatboxviews.get(jid); var view = converse.chatboxviews.get(jid);
view.el.querySelector('.chat-content').innerHTML = ''; view.el.querySelector('.chat-content').innerHTML = '';
view.model.messages.reset(); view.model.messages.reset();
view.model.messages.browserStorage._clear(); view.model.messages.browserStorage._clear();
}; };
utils.createContacts = function (converse, type, length) { utils.createContacts = function (converse, type, length) {
/* Create current (as opposed to requesting or pending) contacts /* Create current (as opposed to requesting or pending) contacts
* for the user's roster. * for the user's roster.
* *
* These contacts are not grouped. See below. * These contacts are not grouped. See below.
*/ */
var names, jid, subscription, requesting, ask; var names, jid, subscription, requesting, ask;
if (type === 'requesting') { if (type === 'requesting') {
names = mock.req_names; names = mock.req_names;
subscription = 'none'; subscription = 'none';
requesting = true; requesting = true;
ask = null; ask = null;
} else if (type === 'pending') { } else if (type === 'pending') {
names = mock.pend_names; names = mock.pend_names;
subscription = 'none'; subscription = 'none';
requesting = false; requesting = false;
ask = 'subscribe'; ask = 'subscribe';
} else if (type === 'current') { } else if (type === 'current') {
names = mock.cur_names; names = mock.cur_names;
subscription = 'both'; subscription = 'both';
requesting = false; requesting = false;
ask = null; ask = null;
} else if (type === 'all') { } else if (type === 'all') {
this.createContacts(converse, 'current') this.createContacts(converse, 'current')
.createContacts(converse, 'requesting') .createContacts(converse, 'requesting')
.createContacts(converse, 'pending'); .createContacts(converse, 'pending');
return this; return this;
} else { } else {
throw Error("Need to specify the type of contact to create"); throw Error("Need to specify the type of contact to create");
} }
if (typeof length === 'undefined') { if (typeof length === 'undefined') {
length = names.length; length = names.length;
} }
for (var i=0; i<length; i++) { for (var i=0; i<length; i++) {
jid = names[i].replace(/ /g,'.').toLowerCase() + '@localhost'; jid = names[i].replace(/ /g,'.').toLowerCase() + '@localhost';
if (!converse.roster.get(jid)) { if (!converse.roster.get(jid)) {
converse.roster.create({ converse.roster.create({
'ask': ask, 'ask': ask,
'fullname': names[i], 'fullname': names[i],
'jid': jid, 'jid': jid,
'requesting': requesting, 'requesting': requesting,
'subscription': subscription 'subscription': subscription
}); });
}
} }
return this; }
}; return this;
};
utils.createGroupedContacts = function (converse) { utils.createGroupedContacts = function (converse) {
/* Create grouped contacts /* Create grouped contacts
*/ */
var i=0, j=0; var i=0, j=0;
_.each(_.keys(mock.groups), function (name) { _.each(_.keys(mock.groups), function (name) {
j = i; j = i;
for (i=j; i<j+mock.groups[name]; i++) { for (i=j; i<j+mock.groups[name]; i++) {
converse.roster.create({ converse.roster.create({
jid: mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost', jid: mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost',
subscription: 'both', subscription: 'both',
ask: null, ask: null,
groups: name === 'ungrouped'? [] : [name], groups: name === 'ungrouped'? [] : [name],
fullname: mock.cur_names[i] fullname: mock.cur_names[i]
}); });
} }
}); });
}; };
utils.createChatMessage = function (_converse, sender_jid, message) { utils.createChatMessage = function (_converse, sender_jid, message) {
return $msg({ return $msg({
from: sender_jid, from: sender_jid,
to: _converse.connection.jid, to: _converse.connection.jid,
type: 'chat', type: 'chat',
id: (new Date()).getTime() id: (new Date()).getTime()
}) })
.c('body').t(message).up() .c('body').t(message).up()
.c('active', {'xmlns': Strophe.NS.CHATSTATES}).tree(); .c('active', {'xmlns': Strophe.NS.CHATSTATES}).tree();
} }
utils.sendMessage = function (chatboxview, message) { utils.sendMessage = function (chatboxview, message) {
chatboxview.el.querySelector('.chat-textarea').value = message; chatboxview.el.querySelector('.chat-textarea').value = message;
chatboxview.keyPressed({ chatboxview.keyPressed({
target: chatboxview.el.querySelector('textarea.chat-textarea'), target: chatboxview.el.querySelector('textarea.chat-textarea'),
preventDefault: _.noop, preventDefault: _.noop,
keyCode: 13 keyCode: 13
}); });
}; };
return utils;
}));
...@@ -75,6 +75,18 @@ const config = { ...@@ -75,6 +75,18 @@ const config = {
path.resolve(__dirname, "src"), path.resolve(__dirname, "src"),
], ],
alias: { alias: {
"jquery": path.resolve(__dirname, "node_modules/jquery/dist/jquery"),
"mock": path.resolve(__dirname, "tests/mock"),
"wait-until-promise": path.resolve(__dirname, "node_modules/wait-until-promise/index"),
"test-utils": path.resolve(__dirname, "tests/utils"),
"sinon": path.resolve(__dirname, "node_modules/sinon/pkg/sinon"),
"transcripts": path.resolve(__dirname, "converse-logs/converse-logs"),
"jasmine-core": path.resolve(__dirname, "node_modules/jasmine-core/lib/jasmine-core/jasmine"),
"jasmine": path.resolve(__dirname, "node_modules/jasmine-core/lib/jasmine-core/boot"),
"jasmine-console": path.resolve(__dirname, "node_modules/jasmine-core/lib/console/console"),
"console-reporter": path.resolve(__dirname, "tests/console-reporter"),
"jasmine-html": path.resolve(__dirname, "node_modules/jasmine-core/lib/jasmine-core/jasmine-html"),
"IPv6": path.resolve(__dirname, "node_modules/urijs/src/IPv6"), "IPv6": path.resolve(__dirname, "node_modules/urijs/src/IPv6"),
"SecondLevelDomains": path.resolve(__dirname, "node_modules/urijs/src/SecondLevelDomains"), "SecondLevelDomains": path.resolve(__dirname, "node_modules/urijs/src/SecondLevelDomains"),
"awesomplete": path.resolve(__dirname, "node_modules/awesomplete-avoid-xss/awesomplete"), "awesomplete": path.resolve(__dirname, "node_modules/awesomplete-avoid-xss/awesomplete"),
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment