Commit c9b4c740 authored by JC Brand's avatar JC Brand

Exploring using karma

parent 74eed32e
......@@ -9,6 +9,7 @@
"plugins": ["lodash"],
"extends": ["eslint:recommended", "plugin:lodash/canonical"],
"globals": {
"module": true,
"window": true,
"sinon": true,
"define": true,
......
......@@ -11,11 +11,7 @@
<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/converse.css" />
<![if gte IE 11]>
<link type="text/css" rel="stylesheet" media="screen" href="css/converse.css" />
<script src="dist/converse.js"></script>
<![endif]>
<script src="dist/converse.js"></script>
</head>
<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') {
};
}
require.config({
window.config = {
baseUrl: '.',
paths: {
"IPv6": "node_modules/urijs/src/IPv6",
......
......@@ -11,9 +11,8 @@
<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/converse.css" />
<script src="../src/config.js"></script>
<script data-main="runner" src="../node_modules/requirejs/require.js"></script>
<script src="dist/converse.js"></script>
<script src="runner.js"></script>
<style>
.tests-brand-heading {
......
(function (root, factory) {
define("mock", ['converse'], factory);
}(this, function (converse) {
var _ = converse.env._;
var Promise = converse.env.Promise;
var Strophe = converse.env.Strophe;
var $iq = converse.env.$iq;
var mock = {};
var _ = converse.env._;
var Promise = converse.env.Promise;
var Strophe = converse.env.Strophe;
var $iq = converse.env.$iq;
window.mock = {};
mock.view_mode = 'overlayed';
mock.view_mode = 'overlayed';
// Names from http://www.fakenamegenerator.com/
mock.req_names = [
'Louw Spekman', 'Mohamad Stet', 'Dominik Beyer'
];
mock.pend_names = [
'Suleyman van Beusichem', 'Nanja van Yperen', 'Nicole Diederich'
];
mock.cur_names = [
'Max Frankfurter', 'Candice van der Knijff', 'Irini Vlastuin', 'Rinse Sommer', 'Annegreet Gomez',
'Robin Schook', 'Marcel Eberhardt', 'Simone Brauer', 'Asmaa Haakman', 'Felix Amsel',
'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;
// Names from http://www.fakenamegenerator.com/
mock.req_names = [
'Louw Spekman', 'Mohamad Stet', 'Dominik Beyer'
];
mock.pend_names = [
'Suleyman van Beusichem', 'Nanja van Yperen', 'Nicole Diederich'
];
mock.cur_names = [
'Max Frankfurter', 'Candice van der Knijff', 'Irini Vlastuin', 'Rinse Sommer', 'Annegreet Gomez',
'Robin Schook', 'Marcel Eberhardt', 'Simone Brauer', 'Asmaa Haakman', 'Felix Amsel',
'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.groups = {
'colleagues': 3,
'friends & acquaintences': 3,
'Family': 4,
'ænemies': 3,
'Ungrouped': 2
};
mock.groups = {
'colleagues': 3,
'friends & acquaintences': 3,
'Family': 4,
'ænemies': 3,
'Ungrouped': 2
};
mock.chatroom_names = [
'Dyon van de Wege', 'Thomas Kalb', 'Dirk Theissen', 'Felix Hofmann', 'Ka Lek', 'Anne Ebersbacher'
];
// TODO: need to also test other roles and affiliations
mock.chatroom_roles = {
'Anne Ebersbacher': { affiliation: "owner", role: "moderator" },
'Dirk Theissen': { affiliation: "admin", role: "moderator" },
'Dyon van de Wege': { affiliation: "member", role: "occupant" },
'Felix Hofmann': { affiliation: "member", role: "occupant" },
'Ka Lek': { affiliation: "member", role: "occupant" },
'Thomas Kalb': { affiliation: "member", role: "occupant" }
};
mock.chatroom_names = [
'Dyon van de Wege', 'Thomas Kalb', 'Dirk Theissen', 'Felix Hofmann', 'Ka Lek', 'Anne Ebersbacher'
];
// TODO: need to also test other roles and affiliations
mock.chatroom_roles = {
'Anne Ebersbacher': { affiliation: "owner", role: "moderator" },
'Dirk Theissen': { affiliation: "admin", role: "moderator" },
'Dyon van de Wege': { affiliation: "member", role: "occupant" },
'Felix Hofmann': { affiliation: "member", role: "occupant" },
'Ka Lek': { affiliation: "member", role: "occupant" },
'Thomas Kalb': { affiliation: "member", role: "occupant" }
};
mock.event = {
'preventDefault': function () {}
};
mock.event = {
'preventDefault': function () {}
};
mock.mock_connection = function () { // eslint-disable-line wrap-iife
return function () {
Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas
var c = new Strophe.Connection('jasmine tests');
var sendIQ = c.sendIQ;
mock.mock_connection = function () { // eslint-disable-line wrap-iife
return function () {
Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas
var c = new Strophe.Connection('jasmine tests');
var sendIQ = c.sendIQ;
c.IQ_stanzas = [];
c.IQ_ids = [];
c.sendIQ = function (iq, callback, errback) {
this.IQ_stanzas.push(iq);
var id = sendIQ.bind(this)(iq, callback, errback);
this.IQ_ids.push(id);
return id;
}
c.IQ_stanzas = [];
c.IQ_ids = [];
c.sendIQ = function (iq, callback, errback) {
this.IQ_stanzas.push(iq);
var id = sendIQ.bind(this)(iq, callback, errback);
this.IQ_ids.push(id);
return id;
}
c._proto._connect = function () {
c.authenticated = true;
c.connected = true;
c.mock = true;
c.jid = 'dummy@localhost/resource';
c._changeConnectStatus(Strophe.Status.CONNECTED);
};
return c;
c._proto._connect = function () {
c.authenticated = true;
c.connected = true;
c.mock = true;
c.jid = 'dummy@localhost/resource';
c._changeConnectStatus(Strophe.Status.CONNECTED);
};
}();
return c;
};
}();
function initConverse (settings, spies, promises) {
window.localStorage.clear();
window.sessionStorage.clear();
function initConverse (settings, spies, promises) {
window.localStorage.clear();
window.sessionStorage.clear();
var connection = mock.mock_connection();
if (!_.isUndefined(spies)) {
_.forEach(spies, function (method) {
spyOn(connection, method);
});
}
var connection = mock.mock_connection();
if (!_.isUndefined(spies)) {
_.forEach(spies, function (method) {
spyOn(connection, method);
});
}
var _converse = converse.initialize(_.extend({
'i18n': 'en',
'auto_subscribe': false,
'play_sounds': false,
'bosh_service_url': 'localhost',
'connection': connection,
'animate': false,
'use_emojione': false,
'no_trimming': true,
'view_mode': mock.view_mode,
'debug': false
}, settings || {}));
var _converse = converse.initialize(_.extend({
'i18n': 'en',
'auto_subscribe': false,
'play_sounds': false,
'bosh_service_url': 'localhost',
'connection': connection,
'animate': false,
'use_emojione': false,
'no_trimming': true,
'view_mode': mock.view_mode,
'debug': false
}, settings || {}));
_converse.ChatBoxViews.prototype.trimChat = function () {};
_converse.api.vcard.get = function (model, force) {
return new Promise((resolve, reject) => {
let jid;
if (_.isString(model)) {
jid = model;
} else if (!model.get('vcard_updated') || force) {
jid = model.get('jid') || model.get('muc_jid');
}
var fullname;
if (!jid || jid == 'dummy@localhost') {
jid = 'dummy@localhost';
fullname = 'Max Mustermann' ;
} else {
var name = jid.split('@')[0].replace(/\./g, ' ').split(' ');
var last = name.length-1;
name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1);
name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1);
fullname = name.join(' ');
}
var vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree;
var result = {
'stanza': vcard,
'fullname': _.get(vcard.querySelector('FN'), 'textContent'),
'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'),
'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'),
'url': _.get(vcard.querySelector('URL'), 'textContent')
};
resolve(result);
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
};
if (_.get(settings, 'auto_login') !== false) {
_converse.api.user.login({
'jid': 'dummy@localhost',
'password': 'secret'
});
}
window.converse_disable_effects = true;
return _converse;
_converse.ChatBoxViews.prototype.trimChat = function () {};
_converse.api.vcard.get = function (model, force) {
return new Promise((resolve, reject) => {
let jid;
if (_.isString(model)) {
jid = model;
} else if (!model.get('vcard_updated') || force) {
jid = model.get('jid') || model.get('muc_jid');
}
var fullname;
if (!jid || jid == 'dummy@localhost') {
jid = 'dummy@localhost';
fullname = 'Max Mustermann' ;
} else {
var name = jid.split('@')[0].replace(/\./g, ' ').split(' ');
var last = name.length-1;
name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1);
name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1);
fullname = name.join(' ');
}
var vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree;
var result = {
'stanza': vcard,
'fullname': _.get(vcard.querySelector('FN'), 'textContent'),
'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'),
'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'),
'url': _.get(vcard.querySelector('URL'), 'textContent')
};
resolve(result);
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
};
if (_.get(settings, 'auto_login') !== false) {
_converse.api.user.login({
'jid': 'dummy@localhost',
'password': 'secret'
});
}
window.converse_disable_effects = true;
return _converse;
}
mock.initConverseWithPromises = function (spies, promise_names, settings, func) {
return function (done) {
var _converse = initConverse(settings, spies);
var promises = _.map(promise_names, _converse.api.waitUntil);
Promise.all(promises)
.then(_.partial(func, done, _converse))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}
};
mock.initConverseWithPromises = function (spies, promise_names, settings, func) {
return function (done) {
var _converse = initConverse(settings, spies);
var promises = _.map(promise_names, _converse.api.waitUntil);
Promise.all(promises)
.then(_.partial(func, done, _converse))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}
};
mock.initConverseWithConnectionSpies = function (spies, settings, func) {
return function (done) {
return func(done, initConverse(settings, spies));
};
mock.initConverseWithConnectionSpies = function (spies, settings, func) {
return function (done) {
return func(done, initConverse(settings, spies));
};
};
mock.initConverseWithAsync = function (settings, func) {
if (_.isFunction(settings)) {
var _func = settings;
settings = func;
func = _func;
}
return function (done) {
return func(done, initConverse(settings));
};
mock.initConverseWithAsync = function (settings, func) {
if (_.isFunction(settings)) {
var _func = settings;
settings = func;
func = _func;
}
return function (done) {
return func(done, initConverse(settings));
};
mock.initConverse = function (settings, func) {
if (_.isFunction(settings)) {
var _func = settings;
settings = func;
func = _func;
}
return function () {
return func(initConverse(settings));
};
};
mock.initConverse = function (settings, func) {
if (_.isFunction(settings)) {
var _func = settings;
settings = func;
func = _func;
}
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
config.baseUrl = '../';
config.paths.jquery = "node_modules/jquery/dist/jquery";
config.paths.mock = "tests/mock";
config.paths['wait-until-promise'] = "node_modules/wait-until-promise/index";
......@@ -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 = "node_modules/jasmine-core/lib/jasmine-core/boot";
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.shim.jasmine = {
exports: 'window.jasmineRequire'
......@@ -28,7 +175,7 @@ config.shim.jasmine = {
deps: ['jasmine-core', 'jasmine-html', 'jasmine-console'],
exports: 'window.jasmine'
};
require.config(config);
var specs = [
"jasmine",
......@@ -61,20 +208,26 @@ var specs = [
"spec/http-file-upload"
];
require(['console-reporter', 'mock', 'sinon', 'wait-until-promise', 'pluggable'],
function(ConsoleReporter, mock, sinon, waitUntilPromise, pluggable) {
config.deps = specs;
config.callback = window.__karma__.start;
if (config.view_mode) {
mock.view_mode = config.view_mode;
}
window.sinon = sinon;
window.waitUntilPromise = waitUntilPromise.default;
window.localStorage.clear();
window.sessionStorage.clear();
// Load the specs
require(specs, function (jasmine) {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter(new ConsoleReporter());
window.onload();
});
});
require.config(config);
// require(['console-reporter', 'mock', 'sinon', 'wait-until-promise', 'pluggable'],
// function(ConsoleReporter, mock, sinon, waitUntilPromise, pluggable) {
//
// debugger;
// if (config.view_mode) {
// mock.view_mode = config.view_mode;
// }
// window.sinon = sinon;
// window.waitUntilPromise = waitUntilPromise.default;
// 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) {
define(['converse', 'es6-promise', 'mock', 'wait-until-promise'], factory);
}(this, function (converse_api, Promise, mock, waitUntilPromise) {
var _ = converse_api.env._;
var $msg = converse_api.env.$msg;
var $pres = converse_api.env.$pres;
var $iq = converse_api.env.$iq;
var Strophe = converse_api.env.Strophe;
var u = converse_api.env.utils;
var utils = {};
var _ = converse.env._;
var $msg = converse.env.$msg;
var $pres = converse.env.$pres;
var $iq = converse.env.$iq;
var Strophe = converse.env.Strophe;
var u = converse.env.utils;
var utils = {};
if (typeof window.Promise === 'undefined') {
waitUntilPromise.setPromiseImplementation(Promise);
}
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});
if (typeof window.Promise === 'undefined') {
waitUntilPromise.setPromiseImplementation(Promise);
}
utils.waitUntil = waitUntilPromise.default;
_.forEach(identities, function (identity) {
stanza.c('identity', {'category': identity.category, 'type': identity.type}).up()
});
_.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, _));
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});
utils.createRequest = function (iq) {
iq = typeof iq.tree == "function" ? iq.tree() : iq;
var req = new Strophe.Request(iq, function() {});
req.getResponse = function () {
var env = new Strophe.Builder('env', {type: 'mock'}).tree();
env.appendChild(iq);
return env;
};
return req;
};
_.forEach(identities, function (identity) {
stanza.c('identity', {'category': identity.category, 'type': identity.type}).up()
});
_.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, _));
}
utils.closeAllChatBoxes = function (converse) {
var i, chatbox;
for (i=converse.chatboxes.models.length-1; i>-1; i--) {
chatbox = converse.chatboxes.models[i];
converse.chatboxviews.get(chatbox.get('id')).close();
}
return this;
utils.createRequest = function (iq) {
iq = typeof iq.tree == "function" ? iq.tree() : iq;
var req = new Strophe.Request(iq, function() {});
req.getResponse = function () {
var env = new Strophe.Builder('env', {type: 'mock'}).tree();
env.appendChild(iq);
return env;
};
return req;
};
utils.openControlBox = function () {
var toggle = document.querySelector(".toggle-controlbox");
if (!u.isVisible(document.querySelector("#controlbox"))) {
if (!u.isVisible(toggle)) {
u.removeClass('hidden', toggle);
}
toggle.click();
}
return this;
};
utils.closeAllChatBoxes = function (converse) {
var i, chatbox;
for (i=converse.chatboxes.models.length-1; i>-1; i--) {
chatbox = converse.chatboxes.models[i];
converse.chatboxviews.get(chatbox.get('id')).close();
}
return this;
};
utils.closeControlBox = function () {
var controlbox = document.querySelector("#controlbox");
if (u.isVisible(controlbox)) {
var button = controlbox.querySelector(".close-chatbox-button");
if (!_.isNull(button)) {
button.click();
}
utils.openControlBox = function () {
var toggle = document.querySelector(".toggle-controlbox");
if (!u.isVisible(document.querySelector("#controlbox"))) {
if (!u.isVisible(toggle)) {
u.removeClass('hidden', toggle);
}
return this;
};
toggle.click();
}
return this;
};
utils.openChatBoxes = function (converse, amount) {
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");
utils.closeControlBox = function () {
var controlbox = document.querySelector("#controlbox");
if (u.isVisible(controlbox)) {
var button = controlbox.querySelector(".close-chatbox-button");
if (!_.isNull(button)) {
button.click();
}
return views;
};
}
return this;
};
utils.openChatBoxFor = function (converse, jid) {
return converse.roster.get(jid).trigger("open");
};
utils.openChatBoxes = function (converse, amount) {
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) {
// Opens a new chatroom
return new Promise(function (resolve, reject) {
utils.openControlBox(_converse);
var roomspanel = _converse.chatboxviews.get('controlbox').roomspanel;
roomspanel.el.querySelector('.trigger-add-chatrooms-modal').click();
utils.closeControlBox(_converse);
const modal = roomspanel.add_room_modal;
utils.waitUntil(function () {
return u.isVisible(modal.el);
}, 1000).then(function () {
modal.el.querySelector('input[name="chatroom"]').value = jid;
modal.el.querySelector('form input[type="submit"]').click();
resolve();
}).catch(_.partial(console.error, _));
utils.openChatRoomViaModal = function (_converse, jid, nick) {
// Opens a new chatroom
return new Promise(function (resolve, reject) {
utils.openControlBox(_converse);
var roomspanel = _converse.chatboxviews.get('controlbox').roomspanel;
roomspanel.el.querySelector('.trigger-add-chatrooms-modal').click();
utils.closeControlBox(_converse);
const modal = roomspanel.add_room_modal;
utils.waitUntil(function () {
return u.isVisible(modal.el);
}, 1000).then(function () {
modal.el.querySelector('input[name="chatroom"]').value = jid;
modal.el.querySelector('form input[type="submit"]').click();
resolve();
}).catch(_.partial(console.error, _));
};
}).catch(_.partial(console.error, _));
};
utils.openChatRoom = function (_converse, room, server, nick) {
_converse.api.rooms.open(`${room}@${server}`);
};
utils.openChatRoom = function (_converse, room, server, nick) {
_converse.api.rooms.open(`${room}@${server}`);
};
utils.openAndEnterChatRoom = function (_converse, room, server, nick) {
let last_stanza;
utils.openAndEnterChatRoom = function (_converse, room, server, nick) {
let last_stanza;
return new Promise(function (resolve, reject) {
_converse.api.rooms.open(`${room}@${server}`);
const view = _converse.chatboxviews.get((room+'@'+server).toLowerCase());
// We pretend this is a new room, so no disco info is returned.
let last_stanza = _.last(_converse.connection.IQ_stanzas).nodeTree;
const IQ_id = last_stanza.getAttribute('id');
const features_stanza = $iq({
'from': room+'@'+server,
'id': IQ_id,
'to': nick+'@'+server,
'type': 'error'
}).c('error', {'type': 'cancel'})
.c('item-not-found', {'xmlns': "urn:ietf:params:xml:ns:xmpp-stanzas"});
_converse.connection._dataRecv(utils.createRequest(features_stanza));
return new Promise(function (resolve, reject) {
_converse.api.rooms.open(`${room}@${server}`);
const view = _converse.chatboxviews.get((room+'@'+server).toLowerCase());
// We pretend this is a new room, so no disco info is returned.
let last_stanza = _.last(_converse.connection.IQ_stanzas).nodeTree;
const IQ_id = last_stanza.getAttribute('id');
const features_stanza = $iq({
'from': room+'@'+server,
'id': IQ_id,
'to': nick+'@'+server,
'type': 'error'
}).c('error', {'type': 'cancel'})
.c('item-not-found', {'xmlns': "urn:ietf:params:xml:ns:xmpp-stanzas"});
_converse.connection._dataRecv(utils.createRequest(features_stanza));
utils.waitUntil(() => {
return _.filter(
_converse.connection.IQ_stanzas, (node) => {
const query = node.nodeTree.querySelector('query');
if (query && query.getAttribute('node') === 'x-roomuser-item') {
last_stanza = node.nodeTree;
return true;
}
}).length
}).then(function () {
// The XMPP server returns the reserved nick for this user.
const IQ_id = last_stanza.getAttribute('id');
const stanza = $iq({
'type': 'result',
'id': IQ_id,
'from': view.model.get('jid'),
'to': _converse.connection.jid
}).c('query', {'xmlns': 'http://jabber.org/protocol/disco#info', 'node': 'x-roomuser-item'})
.c('identity', {'category': 'conference', 'name': nick, 'type': 'text'});
_converse.connection._dataRecv(utils.createRequest(stanza));
// The user has just entered the room (because join was called)
// and receives their own presence from the server.
// See example 24: http://xmpp.org/extensions/xep-0045.html#enter-pres
var presence = $pres({
to: _converse.connection.jid,
from: room+'@'+server+'/'+nick,
id: 'DC352437-C019-40EC-B590-AF29E879AF97'
}).c('x').attrs({xmlns:'http://jabber.org/protocol/muc#user'})
.c('item').attrs({
affiliation: 'member',
jid: _converse.bare_jid,
role: 'participant'
}).up()
.c('status').attrs({code:'110'});
_converse.connection._dataRecv(utils.createRequest(presence));
resolve();
utils.waitUntil(() => {
return _.filter(
_converse.connection.IQ_stanzas, (node) => {
const query = node.nodeTree.querySelector('query');
if (query && query.getAttribute('node') === 'x-roomuser-item') {
last_stanza = node.nodeTree;
return true;
}
}).length
}).then(function () {
// The XMPP server returns the reserved nick for this user.
const IQ_id = last_stanza.getAttribute('id');
const stanza = $iq({
'type': 'result',
'id': IQ_id,
'from': view.model.get('jid'),
'to': _converse.connection.jid
}).c('query', {'xmlns': 'http://jabber.org/protocol/disco#info', 'node': 'x-roomuser-item'})
.c('identity', {'category': 'conference', 'name': nick, 'type': 'text'});
_converse.connection._dataRecv(utils.createRequest(stanza));
// The user has just entered the room (because join was called)
// and receives their own presence from the server.
// See example 24: http://xmpp.org/extensions/xep-0045.html#enter-pres
var presence = $pres({
to: _converse.connection.jid,
from: room+'@'+server+'/'+nick,
id: 'DC352437-C019-40EC-B590-AF29E879AF97'
}).c('x').attrs({xmlns:'http://jabber.org/protocol/muc#user'})
.c('item').attrs({
affiliation: 'member',
jid: _converse.bare_jid,
role: 'participant'
}).up()
.c('status').attrs({code:'110'});
_converse.connection._dataRecv(utils.createRequest(presence));
resolve();
}).catch(_.partial(console.error, _));
}).catch(_.partial(console.error, _));
};
}).catch(_.partial(console.error, _));
};
utils.clearBrowserStorage = function () {
window.localStorage.clear();
window.sessionStorage.clear();
return this;
};
utils.clearBrowserStorage = function () {
window.localStorage.clear();
window.sessionStorage.clear();
return this;
};
utils.clearChatBoxMessages = function (converse, jid) {
var view = converse.chatboxviews.get(jid);
view.el.querySelector('.chat-content').innerHTML = '';
view.model.messages.reset();
view.model.messages.browserStorage._clear();
};
utils.clearChatBoxMessages = function (converse, jid) {
var view = converse.chatboxviews.get(jid);
view.el.querySelector('.chat-content').innerHTML = '';
view.model.messages.reset();
view.model.messages.browserStorage._clear();
};
utils.createContacts = function (converse, type, length) {
/* Create current (as opposed to requesting or pending) contacts
* for the user's roster.
*
* These contacts are not grouped. See below.
*/
var names, jid, subscription, requesting, ask;
if (type === 'requesting') {
names = mock.req_names;
subscription = 'none';
requesting = true;
ask = null;
} else if (type === 'pending') {
names = mock.pend_names;
subscription = 'none';
requesting = false;
ask = 'subscribe';
} else if (type === 'current') {
names = mock.cur_names;
subscription = 'both';
requesting = false;
ask = null;
} else if (type === 'all') {
this.createContacts(converse, 'current')
.createContacts(converse, 'requesting')
.createContacts(converse, 'pending');
return this;
} else {
throw Error("Need to specify the type of contact to create");
}
utils.createContacts = function (converse, type, length) {
/* Create current (as opposed to requesting or pending) contacts
* for the user's roster.
*
* These contacts are not grouped. See below.
*/
var names, jid, subscription, requesting, ask;
if (type === 'requesting') {
names = mock.req_names;
subscription = 'none';
requesting = true;
ask = null;
} else if (type === 'pending') {
names = mock.pend_names;
subscription = 'none';
requesting = false;
ask = 'subscribe';
} else if (type === 'current') {
names = mock.cur_names;
subscription = 'both';
requesting = false;
ask = null;
} else if (type === 'all') {
this.createContacts(converse, 'current')
.createContacts(converse, 'requesting')
.createContacts(converse, 'pending');
return this;
} else {
throw Error("Need to specify the type of contact to create");
}
if (typeof length === 'undefined') {
length = names.length;
}
for (var i=0; i<length; i++) {
jid = names[i].replace(/ /g,'.').toLowerCase() + '@localhost';
if (!converse.roster.get(jid)) {
converse.roster.create({
'ask': ask,
'fullname': names[i],
'jid': jid,
'requesting': requesting,
'subscription': subscription
});
}
if (typeof length === 'undefined') {
length = names.length;
}
for (var i=0; i<length; i++) {
jid = names[i].replace(/ /g,'.').toLowerCase() + '@localhost';
if (!converse.roster.get(jid)) {
converse.roster.create({
'ask': ask,
'fullname': names[i],
'jid': jid,
'requesting': requesting,
'subscription': subscription
});
}
return this;
};
}
return this;
};
utils.createGroupedContacts = function (converse) {
/* Create grouped contacts
*/
var i=0, j=0;
_.each(_.keys(mock.groups), function (name) {
j = i;
for (i=j; i<j+mock.groups[name]; i++) {
converse.roster.create({
jid: mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost',
subscription: 'both',
ask: null,
groups: name === 'ungrouped'? [] : [name],
fullname: mock.cur_names[i]
});
}
});
};
utils.createGroupedContacts = function (converse) {
/* Create grouped contacts
*/
var i=0, j=0;
_.each(_.keys(mock.groups), function (name) {
j = i;
for (i=j; i<j+mock.groups[name]; i++) {
converse.roster.create({
jid: mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@localhost',
subscription: 'both',
ask: null,
groups: name === 'ungrouped'? [] : [name],
fullname: mock.cur_names[i]
});
}
});
};
utils.createChatMessage = function (_converse, sender_jid, message) {
return $msg({
from: sender_jid,
to: _converse.connection.jid,
type: 'chat',
id: (new Date()).getTime()
})
.c('body').t(message).up()
.c('active', {'xmlns': Strophe.NS.CHATSTATES}).tree();
}
utils.createChatMessage = function (_converse, sender_jid, message) {
return $msg({
from: sender_jid,
to: _converse.connection.jid,
type: 'chat',
id: (new Date()).getTime()
})
.c('body').t(message).up()
.c('active', {'xmlns': Strophe.NS.CHATSTATES}).tree();
}
utils.sendMessage = function (chatboxview, message) {
chatboxview.el.querySelector('.chat-textarea').value = message;
chatboxview.keyPressed({
target: chatboxview.el.querySelector('textarea.chat-textarea'),
preventDefault: _.noop,
keyCode: 13
});
};
return utils;
}));
utils.sendMessage = function (chatboxview, message) {
chatboxview.el.querySelector('.chat-textarea').value = message;
chatboxview.keyPressed({
target: chatboxview.el.querySelector('textarea.chat-textarea'),
preventDefault: _.noop,
keyCode: 13
});
};
......@@ -75,6 +75,18 @@ const config = {
path.resolve(__dirname, "src"),
],
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"),
"SecondLevelDomains": path.resolve(__dirname, "node_modules/urijs/src/SecondLevelDomains"),
"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