'), edx.HtmlUtils.HTML(htmlString));
+ $div.find('code').each(function(index, code) {
edx.HtmlUtils.setHtml(
$(code),
edx.HtmlUtils.HTML(processor(codeArchive[index], 'code'))
@@ -421,15 +420,15 @@
return edx.HtmlUtils.HTML(
htmlSnippet.toString().replace(
/\<\;highlight\>\;/g,
- "
'
)
);
};
DiscussionUtil.stripHighlight = function(htmlString) {
return htmlString
- .replace(/\&(amp\;)?lt\;highlight\&(amp\;)?gt\;/g, "")
- .replace(/\&(amp\;)?lt\;\/highlight\&(amp\;)?gt\;/g, "");
+ .replace(/\&(amp\;)?lt\;highlight\&(amp\;)?gt\;/g, '')
+ .replace(/\&(amp\;)?lt\;\/highlight\&(amp\;)?gt\;/g, '');
};
DiscussionUtil.stripLatexHighlight = function(htmlSnippet) {
@@ -443,7 +442,7 @@
*/
DiscussionUtil.markdownWithHighlight = function(unsafeText) {
var converter;
- unsafeText = unsafeText.replace(/^\>\;/gm, ">");
+ unsafeText = unsafeText.replace(/^\>\;/gm, '>');
converter = Markdown.getMathCompatibleConverter();
/*
* converter.makeHtml and HTML escaping:
@@ -476,8 +475,8 @@
};
DiscussionUtil.typesetMathJax = function(element) {
- if (typeof MathJax !== "undefined" && MathJax !== null) {
- MathJax.Hub.Queue(["Typeset", MathJax.Hub, element[0]]);
+ if (typeof MathJax !== 'undefined' && MathJax !== null) {
+ MathJax.Hub.Queue(['Typeset', MathJax.Hub, element[0]]);
}
};
@@ -489,23 +488,23 @@
ellipsis: gettext('…')
}));
$result = $(edx.HtmlUtils.joinHtml(
- edx.HtmlUtils.HTML("
')
).toString());
- imagesToReplace = $result.find("img:not(:first)");
+ imagesToReplace = $result.find('img:not(:first)');
if (imagesToReplace.length > 0) {
edx.HtmlUtils.append(
$result,
edx.HtmlUtils.interpolateHtml(
- edx.HtmlUtils.HTML("
"),
- {text: gettext("Some images in this post have been omitted")}
+ edx.HtmlUtils.HTML('
'),
+ {text: gettext('Some images in this post have been omitted')}
)
);
}
// See TNL-4983 for an explanation of why the linter requires ensureHtml()
var afterMessage = edx.HtmlUtils.interpolateHtml(
- edx.HtmlUtils.HTML("
'), {text: gettext('image omitted')}
);
imagesToReplace.after(edx.HtmlUtils.ensureHtml(afterMessage).toString()).remove();
return $result.html();
diff --git a/common/static/common/js/discussion/views/discussion_content_view.js b/common/static/common/js/discussion/views/discussion_content_view.js
index 55bded5d34..19e965e143 100644
--- a/common/static/common/js/discussion/views/discussion_content_view.js
+++ b/common/static/common/js/discussion/views/discussion_content_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionContentView = (function(_super) {
-
__extends(DiscussionContentView, _super);
function DiscussionContentView() {
@@ -41,8 +40,8 @@
}
DiscussionContentView.prototype.events = {
- "click .discussion-flag-abuse": "toggleFlagAbuse",
- "keydown .discussion-flag-abuse": function(event) {
+ 'click .discussion-flag-abuse': 'toggleFlagAbuse',
+ 'keydown .discussion-flag-abuse': function(event) {
return DiscussionUtil.activateOnSpace(event, this.toggleFlagAbuse);
}
};
@@ -53,7 +52,7 @@
_ref = this.abilityRenderer;
_results = [];
for (action in _ref) {
- if (_ref.hasOwnProperty(action)){
+ if (_ref.hasOwnProperty(action)) {
selector = _ref[action];
if (!ability[action]) {
_results.push(selector.disable.apply(this));
@@ -69,40 +68,40 @@
DiscussionContentView.prototype.abilityRenderer = {
editable: {
enable: function() {
- return this.$(".action-edit").closest(".actions-item").removeClass("is-hidden");
+ return this.$('.action-edit').closest('.actions-item').removeClass('is-hidden');
},
disable: function() {
- return this.$(".action-edit").closest(".actions-item").addClass("is-hidden");
+ return this.$('.action-edit').closest('.actions-item').addClass('is-hidden');
}
},
can_delete: {
enable: function() {
- return this.$(".action-delete").closest(".actions-item").removeClass("is-hidden");
+ return this.$('.action-delete').closest('.actions-item').removeClass('is-hidden');
},
disable: function() {
- return this.$(".action-delete").closest(".actions-item").addClass("is-hidden");
+ return this.$('.action-delete').closest('.actions-item').addClass('is-hidden');
}
},
can_openclose: {
enable: function() {
var self = this;
- return _.each([".action-close", ".action-pin"], function(selector) {
- return self.$(selector).closest(".actions-item").removeClass("is-hidden");
+ return _.each(['.action-close', '.action-pin'], function(selector) {
+ return self.$(selector).closest('.actions-item').removeClass('is-hidden');
});
},
disable: function() {
var self = this;
- return _.each([".action-close", ".action-pin"], function(selector) {
- return self.$(selector).closest(".actions-item").addClass("is-hidden");
+ return _.each(['.action-close', '.action-pin'], function(selector) {
+ return self.$(selector).closest('.actions-item').addClass('is-hidden');
});
}
},
can_report: {
enable: function() {
- return this.$(".action-report").closest(".actions-item").removeClass("is-hidden");
+ return this.$('.action-report').closest('.actions-item').removeClass('is-hidden');
},
disable: function() {
- return this.$(".action-report").closest(".actions-item").addClass("is-hidden");
+ return this.$('.action-report').closest('.actions-item').addClass('is-hidden');
}
},
can_vote: {
@@ -150,7 +149,7 @@
};
DiscussionContentView.prototype.makeWmdEditor = function(cls_identifier) {
- if (!this.$el.find(".wmd-panel").length) {
+ if (!this.$el.find('.wmd-panel').length) {
return DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), cls_identifier);
}
};
@@ -170,15 +169,14 @@
DiscussionContentView.prototype.initialize = function() {
var self = this;
this.model.bind('change', this.renderPartialAttrs, this);
- return this.listenTo(this.model, "change:endorsed", function() {
+ return this.listenTo(this.model, 'change:endorsed', function() {
if (self.model instanceof Comment) {
- return self.trigger("comment:endorse");
+ return self.trigger('comment:endorse');
}
});
};
return DiscussionContentView;
-
})(Backbone.View);
this.DiscussionContentShowView = (function(_super) {
__extends(DiscussionContentShowView, _super);
@@ -220,25 +218,25 @@
DiscussionContentShowView.prototype.events = _.reduce(
[
- [".action-follow", "toggleFollow"],
- [".action-answer", "toggleEndorse"],
- [".action-endorse", "toggleEndorse"],
- [".action-vote", "toggleVote"],
- [".action-more", "toggleSecondaryActions"],
- [".action-pin", "togglePin"],
- [".action-edit", "edit"],
- [".action-delete", "_delete"],
- [".action-report", "toggleReport"],
- [".action-close", "toggleClose"]
+ ['.action-follow', 'toggleFollow'],
+ ['.action-answer', 'toggleEndorse'],
+ ['.action-endorse', 'toggleEndorse'],
+ ['.action-vote', 'toggleVote'],
+ ['.action-more', 'toggleSecondaryActions'],
+ ['.action-pin', 'togglePin'],
+ ['.action-edit', 'edit'],
+ ['.action-delete', '_delete'],
+ ['.action-report', 'toggleReport'],
+ ['.action-close', 'toggleClose']
],
function(obj, event) {
var funcName, selector;
selector = event[0];
funcName = event[1];
- obj["click " + selector] = function(event) {
+ obj['click ' + selector] = function(event) {
return this[funcName](event);
};
- obj["keydown " + selector] = function(event) {
+ obj['keydown ' + selector] = function(event) {
return DiscussionUtil.activateOnSpace(event, this[funcName]);
};
return obj;
@@ -249,8 +247,8 @@
DiscussionContentShowView.prototype.updateButtonState = function(selector, checked) {
var $button;
$button = this.$(selector);
- $button.toggleClass("is-checked", checked);
- return $button.attr("aria-checked", checked);
+ $button.toggleClass('is-checked', checked);
+ return $button.attr('aria-checked', checked);
};
DiscussionContentShowView.prototype.attrRenderer = $.extend(
@@ -258,50 +256,50 @@
DiscussionContentView.prototype.attrRenderer,
{
subscribed: function(subscribed) {
- return this.updateButtonState(".action-follow", subscribed);
+ return this.updateButtonState('.action-follow', subscribed);
},
endorsed: function(endorsed) {
var $button, selector;
- selector = this.model.get("thread").get("thread_type") === "question" ?
- ".action-answer" :
- ".action-endorse";
+ selector = this.model.get('thread').get('thread_type') === 'question' ?
+ '.action-answer' :
+ '.action-endorse';
this.updateButtonState(selector, endorsed);
$button = this.$(selector);
- $button.closest(".actions-item").toggleClass("is-hidden", !this.model.canBeEndorsed());
- return $button.toggleClass("is-checked", endorsed);
+ $button.closest('.actions-item').toggleClass('is-hidden', !this.model.canBeEndorsed());
+ return $button.toggleClass('is-checked', endorsed);
},
votes: function(votes) {
var button, numVotes, selector, votesText, votesCountMsg;
- selector = ".action-vote";
+ selector = '.action-vote';
this.updateButtonState(selector, window.user.voted(this.model));
button = this.$el.find(selector);
numVotes = votes.up_count;
votesCountMsg = ngettext(
- "there is currently {numVotes} vote", "there are currently {numVotes} votes", numVotes
+ 'there is currently {numVotes} vote', 'there are currently {numVotes} votes', numVotes
);
- button.find(".js-sr-vote-count").empty().text(
- edx.StringUtils.interpolate(votesCountMsg, {numVotes: numVotes })
+ button.find('.js-sr-vote-count').empty().text(
+ edx.StringUtils.interpolate(votesCountMsg, {numVotes: numVotes})
);
votesText = edx.StringUtils.interpolate(
- ngettext("{numVotes} Vote", "{numVotes} Votes", numVotes),
- { numVotes: numVotes });
- button.find(".vote-count").empty().text(votesText);
+ ngettext('{numVotes} Vote', '{numVotes} Votes', numVotes),
+ {numVotes: numVotes});
+ button.find('.vote-count').empty().text(votesText);
this.$el.find('.display-vote .vote-count').empty().text(votesText);
},
pinned: function(pinned) {
- this.updateButtonState(".action-pin", pinned);
- return this.$(".post-label-pinned").toggleClass("is-hidden", !pinned);
+ this.updateButtonState('.action-pin', pinned);
+ return this.$('.post-label-pinned').toggleClass('is-hidden', !pinned);
},
abuse_flaggers: function() {
var flagged;
flagged = this.model.isFlagged();
- this.updateButtonState(".action-report", flagged);
- return this.$(".post-label-reported").toggleClass("is-hidden", !flagged);
+ this.updateButtonState('.action-report', flagged);
+ return this.$('.post-label-reported').toggleClass('is-hidden', !flagged);
},
closed: function(closed) {
- this.updateButtonState(".action-close", closed);
- this.$(".post-label-closed").toggleClass("is-hidden", !closed);
- return this.$(".display-vote").toggle(closed);
+ this.updateButtonState('.action-close', closed);
+ this.$('.post-label-closed').toggleClass('is-hidden', !closed);
+ return this.$('.display-vote').toggle(closed);
}
}
);
@@ -310,36 +308,36 @@
event.preventDefault();
event.stopPropagation();
this.secondaryActionsExpanded = !this.secondaryActionsExpanded;
- this.$(".action-more").toggleClass("is-expanded", this.secondaryActionsExpanded);
- this.$(".actions-dropdown")
- .toggleClass("is-expanded", this.secondaryActionsExpanded)
- .attr("aria-expanded", this.secondaryActionsExpanded);
+ this.$('.action-more').toggleClass('is-expanded', this.secondaryActionsExpanded);
+ this.$('.actions-dropdown')
+ .toggleClass('is-expanded', this.secondaryActionsExpanded)
+ .attr('aria-expanded', this.secondaryActionsExpanded);
if (this.secondaryActionsExpanded) {
- if (event.type === "keydown") {
- this.$(".action-list-item:first").focus();
+ if (event.type === 'keydown') {
+ this.$('.action-list-item:first').focus();
}
- $("body").on("click", this.toggleSecondaryActions);
- $("body").on("keydown", this.handleSecondaryActionEscape);
- return this.$(".action-list-item").on("blur", this.handleSecondaryActionBlur);
+ $('body').on('click', this.toggleSecondaryActions);
+ $('body').on('keydown', this.handleSecondaryActionEscape);
+ return this.$('.action-list-item').on('blur', this.handleSecondaryActionBlur);
} else {
- $("body").off("click", this.toggleSecondaryActions);
- $("body").off("keydown", this.handleSecondaryActionEscape);
- return this.$(".action-list-item").off("blur", this.handleSecondaryActionBlur);
+ $('body').off('click', this.toggleSecondaryActions);
+ $('body').off('keydown', this.handleSecondaryActionEscape);
+ return this.$('.action-list-item').off('blur', this.handleSecondaryActionBlur);
}
};
DiscussionContentShowView.prototype.handleSecondaryActionEscape = function(event) {
if (event.keyCode === 27) {
this.toggleSecondaryActions(event);
- return this.$(".action-more").focus();
+ return this.$('.action-more').focus();
}
};
DiscussionContentShowView.prototype.handleSecondaryActionBlur = function(event) {
var self = this;
return setTimeout(function() {
- if (self.secondaryActionsExpanded && self.$(".actions-dropdown :focus").length === 0) {
+ if (self.secondaryActionsExpanded && self.$('.actions-dropdown :focus').length === 0) {
return self.toggleSecondaryActions(event);
}
}, 10);
@@ -348,18 +346,18 @@
DiscussionContentShowView.prototype.toggleFollow = function(event) {
var is_subscribing, msg, url;
event.preventDefault();
- is_subscribing = !this.model.get("subscribed");
- url = this.model.urlFor(is_subscribing ? "follow" : "unfollow");
+ is_subscribing = !this.model.get('subscribed');
+ url = this.model.urlFor(is_subscribing ? 'follow' : 'unfollow');
if (is_subscribing) {
- msg = gettext("We had some trouble subscribing you to this thread. Please try again.");
+ msg = gettext('We had some trouble subscribing you to this thread. Please try again.');
} else {
- msg = gettext("We had some trouble unsubscribing you from this thread. Please try again.");
+ msg = gettext('We had some trouble unsubscribing you from this thread. Please try again.');
}
return DiscussionUtil.updateWithUndo(this.model, {
- "subscribed": is_subscribing
+ 'subscribed': is_subscribing
}, {
url: url,
- type: "POST",
+ type: 'POST',
$elem: $(event.currentTarget)
}, msg);
};
@@ -368,27 +366,27 @@
var beforeFunc, is_endorsing, msg, updates, url,
self = this;
event.preventDefault();
- is_endorsing = !this.model.get("endorsed");
- url = this.model.urlFor("endorse");
+ is_endorsing = !this.model.get('endorsed');
+ url = this.model.urlFor('endorse');
updates = {
endorsed: is_endorsing,
endorsement: is_endorsing ? {
- username: DiscussionUtil.getUser().get("username"),
+ username: DiscussionUtil.getUser().get('username'),
user_id: DiscussionUtil.getUser().id,
time: new Date().toISOString()
} : null
};
if (this.model.get('thread').get('thread_type') === 'question') {
if (is_endorsing) {
- msg = gettext("We had some trouble marking this response as an answer. Please try again.");
+ msg = gettext('We had some trouble marking this response as an answer. Please try again.');
} else {
- msg = gettext("We had some trouble removing this response as an answer. Please try again.");
+ msg = gettext('We had some trouble removing this response as an answer. Please try again.');
}
} else {
if (is_endorsing) {
- msg = gettext("We had some trouble marking this response endorsed. Please try again.");
+ msg = gettext('We had some trouble marking this response endorsed. Please try again.');
} else {
- msg = gettext("We had some trouble removing this endorsement. Please try again.");
+ msg = gettext('We had some trouble removing this endorsement. Please try again.');
}
}
return DiscussionUtil.updateWithUndo(
@@ -396,13 +394,13 @@
updates,
{
url: url,
- type: "POST",
- data: { endorsed: is_endorsing },
+ type: 'POST',
+ data: {endorsed: is_endorsing},
$elem: $(event.currentTarget)
},
msg,
- function() { return self.trigger("comment:endorse"); }
- ).always(this.trigger("comment:endorse"));
+ function() { return self.trigger('comment:endorse'); }
+ ).always(this.trigger('comment:endorse'));
};
DiscussionContentShowView.prototype.toggleVote = function(event) {
@@ -411,16 +409,16 @@
event.preventDefault();
user = DiscussionUtil.getUser();
is_voting = !user.voted(this.model);
- url = this.model.urlFor(is_voting ? "upvote" : "unvote");
+ url = this.model.urlFor(is_voting ? 'upvote' : 'unvote');
updates = {
upvoted_ids: (is_voting ? _.union : _.difference)(user.get('upvoted_ids'), [this.model.id])
};
- if (!$(event.target.closest(".actions-item")).hasClass('is-disabled')) {
+ if (!$(event.target.closest('.actions-item')).hasClass('is-disabled')) {
return DiscussionUtil.updateWithUndo(user, updates, {
url: url,
- type: "POST",
+ type: 'POST',
$elem: $(event.currentTarget)
- }, gettext("We had some trouble saving your vote. Please try again.")).done(function() {
+ }, gettext('We had some trouble saving your vote. Please try again.')).done(function() {
if (is_voting) {
return self.model.vote();
} else {
@@ -433,18 +431,18 @@
DiscussionContentShowView.prototype.togglePin = function(event) {
var is_pinning, msg, url;
event.preventDefault();
- is_pinning = !this.model.get("pinned");
- url = this.model.urlFor(is_pinning ? "pinThread" : "unPinThread");
+ is_pinning = !this.model.get('pinned');
+ url = this.model.urlFor(is_pinning ? 'pinThread' : 'unPinThread');
if (is_pinning) {
- msg = gettext("We had some trouble pinning this thread. Please try again.");
+ msg = gettext('We had some trouble pinning this thread. Please try again.');
} else {
- msg = gettext("We had some trouble unpinning this thread. Please try again.");
+ msg = gettext('We had some trouble unpinning this thread. Please try again.');
}
return DiscussionUtil.updateWithUndo(this.model, {
pinned: is_pinning
}, {
url: url,
- type: "POST",
+ type: 'POST',
$elem: $(event.currentTarget)
}, msg);
};
@@ -454,20 +452,20 @@
event.preventDefault();
if (this.model.isFlagged()) {
is_flagging = false;
- msg = gettext("We had some trouble removing your flag on this post. Please try again.");
+ msg = gettext('We had some trouble removing your flag on this post. Please try again.');
} else {
is_flagging = true;
- msg = gettext("We had some trouble reporting this post. Please try again.");
+ msg = gettext('We had some trouble reporting this post. Please try again.');
}
- url = this.model.urlFor(is_flagging ? "flagAbuse" : "unFlagAbuse");
+ url = this.model.urlFor(is_flagging ? 'flagAbuse' : 'unFlagAbuse');
updates = {
abuse_flaggers: (is_flagging ? _.union : _.difference)(
- this.model.get("abuse_flaggers"), [DiscussionUtil.getUser().id]
+ this.model.get('abuse_flaggers'), [DiscussionUtil.getUser().id]
)
};
return DiscussionUtil.updateWithUndo(this.model, updates, {
url: url,
- type: "POST",
+ type: 'POST',
$elem: $(event.currentTarget)
}, msg);
};
@@ -477,23 +475,23 @@
event.preventDefault();
is_closing = !this.model.get('closed');
if (is_closing) {
- msg = gettext("We had some trouble closing this thread. Please try again.");
+ msg = gettext('We had some trouble closing this thread. Please try again.');
} else {
- msg = gettext("We had some trouble reopening this thread. Please try again.");
+ msg = gettext('We had some trouble reopening this thread. Please try again.');
}
updates = {
closed: is_closing
};
return DiscussionUtil.updateWithUndo(this.model, updates, {
- url: this.model.urlFor("close"),
- type: "POST",
+ url: this.model.urlFor('close'),
+ type: 'POST',
data: updates,
$elem: $(event.currentTarget)
}, msg);
};
DiscussionContentShowView.prototype.getAuthorDisplay = function() {
- return _.template($("#post-user-display-template").html())({
+ return _.template($('#post-user-display-template').html())({
username: this.model.get('username') || null,
user_url: this.model.get('user_url'),
is_community_ta: this.model.get('community_ta_authored'),
@@ -505,7 +503,7 @@
var endorsement;
endorsement = this.model.get('endorsement');
if (endorsement && endorsement.username) {
- return _.template($("#post-user-display-template").html())({
+ return _.template($('#post-user-display-template').html())({
username: endorsement.username,
user_url: DiscussionUtil.urlFor('user_profile', endorsement.user_id),
is_community_ta: DiscussionUtil.isTA(endorsement.user_id),
@@ -517,8 +515,6 @@
};
return DiscussionContentShowView;
-
}).call(this, this.DiscussionContentView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/discussion_thread_edit_view.js b/common/static/common/js/discussion/views/discussion_thread_edit_view.js
index c693768091..2bf10032a7 100644
--- a/common/static/common/js/discussion/views/discussion_thread_edit_view.js
+++ b/common/static/common/js/discussion/views/discussion_thread_edit_view.js
@@ -25,15 +25,15 @@
},
render: function() {
- var formId = _.uniqueId("form-"),
- threadTypeTemplate = edx.HtmlUtils.template($("#thread-type-template").html()),
+ var formId = _.uniqueId('form-'),
+ threadTypeTemplate = edx.HtmlUtils.template($('#thread-type-template').html()),
$threadTypeSelector = $(threadTypeTemplate({form_id: formId}).toString()),
mainTemplate = edx.HtmlUtils.template($('#thread-edit-template').html());
edx.HtmlUtils.setHtml(this.$el, mainTemplate(this.model.toJSON()));
this.container.append(this.$el);
this.$submitBtn = this.$('.post-update');
this.addField($threadTypeSelector);
- this.$("#" + formId + "-post-type-" + this.threadType).attr('checked', true);
+ this.$('#' + formId + '-post-type-' + this.threadType).attr('checked', true);
// Only allow the topic field for course threads, as standalone threads
// cannot be moved.
if (this.context === 'course') {
@@ -58,7 +58,7 @@
save: function() {
var title = this.$('.edit-post-title').val(),
- threadType = this.$(".post-type-input:checked").val(),
+ threadType = this.$('.post-type-input:checked').val(),
body = this.$('.edit-post-body textarea').val(),
postData = {
title: title,
@@ -87,7 +87,7 @@
this.model.set(postData).unset('abbreviatedBody');
this.trigger('thread:updated');
if (this.threadType !== threadType) {
- this.model.set("thread_type", threadType);
+ this.model.set('thread_type', threadType);
this.model.trigger('thread:thread_type_updated');
this.trigger('comment:endorse');
}
@@ -105,7 +105,7 @@
cancelHandler: function(event) {
event.preventDefault();
- this.trigger("thread:cancel_edit", event);
+ this.trigger('thread:cancel_edit', event);
this.remove();
return this;
}
diff --git a/common/static/common/js/discussion/views/discussion_thread_list_view.js b/common/static/common/js/discussion/views/discussion_thread_list_view.js
index 58061d1520..21be544aaa 100644
--- a/common/static/common/js/discussion/views/discussion_thread_list_view.js
+++ b/common/static/common/js/discussion/views/discussion_thread_list_view.js
@@ -18,7 +18,7 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionThreadListView = (function(_super) {
__extends(DiscussionThreadListView, _super);
@@ -91,20 +91,20 @@
}
DiscussionThreadListView.prototype.events = {
- "click .forum-nav-browse": "toggleBrowseMenu",
- "keypress .forum-nav-browse-filter-input": function(event) {
+ 'click .forum-nav-browse': 'toggleBrowseMenu',
+ 'keypress .forum-nav-browse-filter-input': function(event) {
return DiscussionUtil.ignoreEnterKey(event);
},
- "keyup .forum-nav-browse-filter-input": "filterTopics",
- "click .forum-nav-browse-menu-wrapper": "ignoreClick",
- "click .forum-nav-browse-title": "selectTopicHandler",
- "keydown .forum-nav-search-input": "performSearch",
- "click .fa-search": "performSearch",
- "change .forum-nav-sort-control": "sortThreads",
- "click .forum-nav-thread-link": "threadSelected",
- "click .forum-nav-load-more-link": "loadMorePages",
- "change .forum-nav-filter-main-control": "chooseFilter",
- "change .forum-nav-filter-cohort-control": "chooseCohort"
+ 'keyup .forum-nav-browse-filter-input': 'filterTopics',
+ 'click .forum-nav-browse-menu-wrapper': 'ignoreClick',
+ 'click .forum-nav-browse-title': 'selectTopicHandler',
+ 'keydown .forum-nav-search-input': 'performSearch',
+ 'click .fa-search': 'performSearch',
+ 'change .forum-nav-sort-control': 'sortThreads',
+ 'click .forum-nav-thread-link': 'threadSelected',
+ 'click .forum-nav-load-more-link': 'loadMorePages',
+ 'change .forum-nav-filter-main-control': 'chooseFilter',
+ 'change .forum-nav-filter-cohort-control': 'chooseCohort'
};
DiscussionThreadListView.prototype.initialize = function(options) {
@@ -113,43 +113,43 @@
this.displayedCollection = new Discussion(this.collection.models, {
pages: this.collection.pages
});
- this.collection.on("change", this.reloadDisplayedCollection);
- this.discussionIds = "";
- this.collection.on("reset", function(discussion) {
+ this.collection.on('change', this.reloadDisplayedCollection);
+ this.discussionIds = '';
+ this.collection.on('reset', function(discussion) {
var board;
- board = $(".current-board").html();
+ board = $('.current-board').html();
self.displayedCollection.current_page = discussion.current_page;
self.displayedCollection.pages = discussion.pages;
return self.displayedCollection.reset(discussion.models);
});
- this.collection.on("add", this.addAndSelectThread);
- this.collection.on("thread:remove", this.threadRemoved);
+ this.collection.on('add', this.addAndSelectThread);
+ this.collection.on('thread:remove', this.threadRemoved);
this.sidebar_padding = 10;
this.boardName = null;
- this.template = _.template($("#thread-list-template").html());
- this.current_search = "";
+ this.template = _.template($('#thread-list-template').html());
+ this.current_search = '';
this.mode = 'all';
this.searchAlertCollection = new Backbone.Collection([], {
model: Backbone.Model
});
- this.searchAlertCollection.on("add", function(searchAlert) {
+ this.searchAlertCollection.on('add', function(searchAlert) {
var content;
- content = edx.HtmlUtils.template($("#search-alert-template").html())({
+ content = edx.HtmlUtils.template($('#search-alert-template').html())({
'messageHtml': searchAlert.attributes.message,
'cid': searchAlert.cid,
'css_class': searchAlert.attributes.css_class
});
- edx.HtmlUtils.append(self.$(".search-alerts"), content);
- return self.$("#search-alert-" + searchAlert.cid + " a.dismiss")
- .bind("click", searchAlert, function(event) {
+ edx.HtmlUtils.append(self.$('.search-alerts'), content);
+ return self.$('#search-alert-' + searchAlert.cid + ' a.dismiss')
+ .bind('click', searchAlert, function(event) {
return self.removeSearchAlert(event.data.cid);
});
});
- this.searchAlertCollection.on("remove", function(searchAlert) {
- return self.$("#search-alert-" + searchAlert.cid).remove();
+ this.searchAlertCollection.on('remove', function(searchAlert) {
+ return self.$('#search-alert-' + searchAlert.cid).remove();
});
- return this.searchAlertCollection.on("reset", function() {
- return self.$(".search-alerts").empty();
+ return this.searchAlertCollection.on('reset', function() {
+ return self.$('.search-alerts').empty();
});
};
@@ -163,9 +163,9 @@
DiscussionThreadListView.prototype.addSearchAlert = function(message, css_class) {
var m;
if (typeof css_class === 'undefined' || css_class === null) {
- css_class = "";
+ css_class = '';
}
- m = new Backbone.Model({"message": message, "css_class": css_class});
+ m = new Backbone.Model({'message': message, 'css_class': css_class});
this.searchAlertCollection.add(m);
return m;
};
@@ -183,8 +183,8 @@
this.clearSearchAlerts();
thread_id = thread.get('id');
$content = this.renderThread(thread);
- current_el = this.$(".forum-nav-thread[data-id=" + thread_id + "]");
- active = current_el.has(".forum-nav-thread-link.is-active").length !== 0;
+ current_el = this.$('.forum-nav-thread[data-id=' + thread_id + ']');
+ active = current_el.has('.forum-nav-thread-link.is-active').length !== 0;
current_el.replaceWith($content);
this.showMetadataAccordingToSort();
if (active) {
@@ -200,13 +200,13 @@
DiscussionThreadListView.prototype.addAndSelectThread = function(thread) {
var commentable_id, menuItem,
self = this;
- commentable_id = thread.get("commentable_id");
- menuItem = this.$(".forum-nav-browse-menu-item[data-discussion-id]").filter(function() {
- return $(this).data("discussion-id") === commentable_id;
+ commentable_id = thread.get('commentable_id');
+ menuItem = this.$('.forum-nav-browse-menu-item[data-discussion-id]').filter(function() {
+ return $(this).data('discussion-id') === commentable_id;
});
this.setCurrentTopicDisplay(this.getPathText(menuItem));
return this.retrieveDiscussion(commentable_id, function() {
- return self.trigger("thread:created", thread.get('id'));
+ return self.trigger('thread:created', thread.get('id'));
});
};
@@ -216,10 +216,10 @@
windowHeight;
scrollTop = $(window).scrollTop();
windowHeight = $(window).height();
- discussionBody = $(".discussion-column");
+ discussionBody = $('.discussion-column');
discussionsBodyTop = discussionBody[0] ? discussionBody.offset().top : void 0;
discussionsBodyBottom = discussionsBodyTop + discussionBody.outerHeight();
- sidebar = $(".forum-nav");
+ sidebar = $('.forum-nav');
if (scrollTop > discussionsBodyTop - this.sidebar_padding) {
sidebar.css('top', scrollTop - discussionsBodyTop + this.sidebar_padding);
} else {
@@ -232,9 +232,9 @@
sidebarHeight = sidebarHeight - this.sidebar_padding - amount;
sidebarHeight = Math.min(sidebarHeight + 1, discussionBody.outerHeight());
sidebar.css('height', sidebarHeight);
- headerHeight = this.$(".forum-nav-header").outerHeight();
- refineBarHeight = this.$(".forum-nav-refine-bar").outerHeight();
- browseFilterHeight = this.$(".forum-nav-browse-filter").outerHeight();
+ headerHeight = this.$('.forum-nav-header').outerHeight();
+ refineBarHeight = this.$('.forum-nav-refine-bar').outerHeight();
+ browseFilterHeight = this.$('.forum-nav-browse-filter').outerHeight();
this.$('.forum-nav-thread-list')
.css('height', (sidebarHeight - headerHeight - refineBarHeight - 2) + 'px');
this.$('.forum-nav-browse-menu')
@@ -248,21 +248,21 @@
DiscussionThreadListView.prototype.render = function() {
var self = this,
$elem = this.template({
- isCohorted: this.courseSettings.get("is_cohorted"),
+ isCohorted: this.courseSettings.get('is_cohorted'),
isPrivilegedUser: DiscussionUtil.isPrivilegedUser()
});
this.timer = 0;
this.$el.empty();
this.$el.append($elem);
- this.$(".forum-nav-sort-control option").removeProp("selected");
- this.$(".forum-nav-sort-control option[value=" + this.collection.sort_preference + "]")
- .prop("selected", true);
- $(window).bind("load scroll resize", this.updateSidebar);
- this.displayedCollection.on("reset", this.renderThreads);
- this.displayedCollection.on("thread:remove", this.renderThreads);
- this.displayedCollection.on("change:commentable_id", function() {
- if (self.mode === "commentables") {
- return self.retrieveDiscussions(self.discussionIds.split(","));
+ this.$('.forum-nav-sort-control option').removeProp('selected');
+ this.$('.forum-nav-sort-control option[value=' + this.collection.sort_preference + ']')
+ .prop('selected', true);
+ $(window).bind('load scroll resize', this.updateSidebar);
+ this.displayedCollection.on('reset', this.renderThreads);
+ this.displayedCollection.on('thread:remove', this.renderThreads);
+ this.displayedCollection.on('change:commentable_id', function() {
+ if (self.mode === 'commentables') {
+ return self.retrieveDiscussions(self.discussionIds.split(','));
}
});
this.renderThreads();
@@ -271,44 +271,44 @@
DiscussionThreadListView.prototype.renderThreads = function() {
var $content, thread, i, len;
- this.$(".forum-nav-thread-list").empty();
+ this.$('.forum-nav-thread-list').empty();
for (i = 0, len = this.displayedCollection.models.length; i < len; i++) {
thread = this.displayedCollection.models[i];
$content = this.renderThread(thread);
- this.$(".forum-nav-thread-list").append($content);
+ this.$('.forum-nav-thread-list').append($content);
}
this.showMetadataAccordingToSort();
this.renderMorePages();
this.updateSidebar();
- this.trigger("threads:rendered");
+ this.trigger('threads:rendered');
};
DiscussionThreadListView.prototype.showMetadataAccordingToSort = function() {
var commentCounts, voteCounts;
- voteCounts = this.$(".forum-nav-thread-votes-count");
- commentCounts = this.$(".forum-nav-thread-comments-count");
+ voteCounts = this.$('.forum-nav-thread-votes-count');
+ commentCounts = this.$('.forum-nav-thread-comments-count');
voteCounts.hide();
commentCounts.hide();
- switch (this.$(".forum-nav-sort-control").val()) {
- case "activity":
- case "comments":
- return commentCounts.show();
- case "votes":
- return voteCounts.show();
+ switch (this.$('.forum-nav-sort-control').val()) {
+ case 'activity':
+ case 'comments':
+ return commentCounts.show();
+ case 'votes':
+ return voteCounts.show();
}
};
DiscussionThreadListView.prototype.renderMorePages = function() {
if (this.displayedCollection.hasMorePages()) {
edx.HtmlUtils.append(
- this.$(".forum-nav-thread-list"),
- edx.HtmlUtils.template($("#nav-load-more-link").html())({})
+ this.$('.forum-nav-thread-list'),
+ edx.HtmlUtils.template($('#nav-load-more-link').html())({})
);
}
};
DiscussionThreadListView.prototype.getLoadingContent = function(srText) {
- return edx.HtmlUtils.template($("#nav-loading-template").html())({srText: srText});
+ return edx.HtmlUtils.template($('#nav-loading-template').html())({srText: srText});
};
DiscussionThreadListView.prototype.loadMorePages = function(event) {
@@ -317,69 +317,69 @@
if (event) {
event.preventDefault();
}
- loadMoreElem = this.$(".forum-nav-load-more");
+ loadMoreElem = this.$('.forum-nav-load-more');
loadMoreElem.empty();
- edx.HtmlUtils.append(loadMoreElem, this.getLoadingContent(gettext("Loading more threads")));
- loadingElem = loadMoreElem.find(".forum-nav-loading");
+ edx.HtmlUtils.append(loadMoreElem, this.getLoadingContent(gettext('Loading more threads')));
+ loadingElem = loadMoreElem.find('.forum-nav-loading');
DiscussionUtil.makeFocusTrap(loadingElem);
loadingElem.focus();
options = {
filter: this.filter
};
switch (this.mode) {
- case 'search':
- options.search_text = this.current_search;
- if (this.group_id) {
- options.group_id = this.group_id;
- }
- break;
- case 'followed':
- options.user_id = window.user.id;
- break;
- case 'commentables':
- options.commentable_ids = this.discussionIds;
- if (this.group_id) {
- options.group_id = this.group_id;
- }
- break;
- case 'all':
- if (this.group_id) {
- options.group_id = this.group_id;
- }
+ case 'search':
+ options.search_text = this.current_search;
+ if (this.group_id) {
+ options.group_id = this.group_id;
+ }
+ break;
+ case 'followed':
+ options.user_id = window.user.id;
+ break;
+ case 'commentables':
+ options.commentable_ids = this.discussionIds;
+ if (this.group_id) {
+ options.group_id = this.group_id;
+ }
+ break;
+ case 'all':
+ if (this.group_id) {
+ options.group_id = this.group_id;
+ }
}
_ref = this.collection.last();
lastThread = _ref ? _ref.get('id') : void 0;
if (lastThread) {
- this.once("threads:rendered", function() {
+ this.once('threads:rendered', function() {
var classSelector =
".forum-nav-thread[data-id='" + lastThread + "'] + .forum-nav-thread " +
- ".forum-nav-thread-link";
+ '.forum-nav-thread-link';
return $(classSelector).focus();
});
} else {
- this.once("threads:rendered", function() {
- var _ref1 = $(".forum-nav-thread-link").first();
+ this.once('threads:rendered', function() {
+ var _ref1 = $('.forum-nav-thread-link').first();
return _ref1 ? _ref1.focus() : void 0;
});
}
error = function() {
self.renderThreads();
DiscussionUtil.discussionAlert(
- gettext("Sorry"), gettext("We had some trouble loading more threads. Please try again.")
+ gettext('Sorry'), gettext('We had some trouble loading more threads. Please try again.')
);
};
return this.collection.retrieveAnotherPage(this.mode, options, {
- sort_key: this.$(".forum-nav-sort-control").val()
+ sort_key: this.$('.forum-nav-sort-control').val()
}, error);
};
DiscussionThreadListView.prototype.renderThread = function(thread) {
var content, unreadCount;
- content = $(_.template($("#thread-list-item-template").html())(thread.toJSON()));
- unreadCount = thread.get('unread_comments_count') + (thread.get("read") ? 0 : 1);
+ content = $(_.template($('#thread-list-item-template').html())(thread.toJSON()));
+ unreadCount = thread.get('unread_comments_count') + (thread.get('read') ? 0 : 1);
if (unreadCount > 0) {
content.find('.forum-nav-thread-comments-count').attr(
- "data-tooltip",
+ 'data-tooltip',
edx.StringUtils.interpolate(
ngettext('{unread_count} new comment', '{unread_count} new comments', unreadCount),
{unread_count: unreadCount},
@@ -392,42 +392,42 @@
DiscussionThreadListView.prototype.threadSelected = function(e) {
var thread_id;
- thread_id = $(e.target).closest(".forum-nav-thread").attr("data-id");
+ thread_id = $(e.target).closest('.forum-nav-thread').attr('data-id');
this.setActiveThread(thread_id);
- this.trigger("thread:selected", thread_id);
+ this.trigger('thread:selected', thread_id);
return false;
};
DiscussionThreadListView.prototype.threadRemoved = function(thread) {
- this.trigger("thread:removed", thread);
+ this.trigger('thread:removed', thread);
};
DiscussionThreadListView.prototype.setActiveThread = function(thread_id) {
var $srElem;
- this.$(".forum-nav-thread-link").find(".sr").remove();
+ this.$('.forum-nav-thread-link').find('.sr').remove();
this.$(".forum-nav-thread[data-id!='" + thread_id + "'] .forum-nav-thread-link")
- .removeClass("is-active");
+ .removeClass('is-active');
$srElem = edx.HtmlUtils.joinHtml(
edx.HtmlUtils.HTML('
')
).toString();
this.$(".forum-nav-thread[data-id='" + thread_id + "'] .forum-nav-thread-link")
- .addClass("is-active").find(".forum-nav-thread-wrapper-1")
+ .addClass('is-active').find('.forum-nav-thread-wrapper-1')
.prepend($srElem);
};
DiscussionThreadListView.prototype.goHome = function() {
var url, $tpl_content;
- this.template = _.template($("#discussion-home-template").html());
+ this.template = _.template($('#discussion-home-template').html());
$tpl_content = $(this.template());
- $(".forum-content").empty().append($tpl_content);
- $(".forum-nav-thread-list a").removeClass("is-active").find(".sr").remove();
- $("input.email-setting").bind("click", this.updateEmailNotifications);
- url = DiscussionUtil.urlFor("notifications_status", window.user.get("id"));
+ $('.forum-content').empty().append($tpl_content);
+ $('.forum-nav-thread-list a').removeClass('is-active').find('.sr').remove();
+ $('input.email-setting').bind('click', this.updateEmailNotifications);
+ url = DiscussionUtil.urlFor('notifications_status', window.user.get('id'));
DiscussionUtil.safeAjax({
url: url,
- type: "GET",
+ type: 'GET',
success: function(response) {
$('input.email-setting').prop('checked', response.status);
}
@@ -435,26 +435,26 @@
};
DiscussionThreadListView.prototype.isBrowseMenuVisible = function() {
- return this.$(".forum-nav-browse-menu-wrapper").is(":visible");
+ return this.$('.forum-nav-browse-menu-wrapper').is(':visible');
};
DiscussionThreadListView.prototype.showBrowseMenu = function() {
if (!this.isBrowseMenuVisible()) {
- this.$(".forum-nav-browse").addClass("is-active");
- this.$(".forum-nav-browse-menu-wrapper").show();
- this.$(".forum-nav-thread-list-wrapper").hide();
- $(".forum-nav-browse-filter-input").focus();
- $("body").bind("click", this.hideBrowseMenu);
+ this.$('.forum-nav-browse').addClass('is-active');
+ this.$('.forum-nav-browse-menu-wrapper').show();
+ this.$('.forum-nav-thread-list-wrapper').hide();
+ $('.forum-nav-browse-filter-input').focus();
+ $('body').bind('click', this.hideBrowseMenu);
return this.updateSidebar();
}
};
DiscussionThreadListView.prototype.hideBrowseMenu = function() {
if (this.isBrowseMenuVisible()) {
- this.$(".forum-nav-browse").removeClass("is-active");
- this.$(".forum-nav-browse-menu-wrapper").hide();
- this.$(".forum-nav-thread-list-wrapper").show();
- $("body").unbind("click", this.hideBrowseMenu);
+ this.$('.forum-nav-browse').removeClass('is-active');
+ this.$('.forum-nav-browse-menu-wrapper').hide();
+ this.$('.forum-nav-thread-list-wrapper').show();
+ $('body').unbind('click', this.hideBrowseMenu);
return this.updateSidebar();
}
};
@@ -471,18 +471,18 @@
DiscussionThreadListView.prototype.getPathText = function(item) {
var path, pathTitles;
- path = item.parents(".forum-nav-browse-menu-item").andSelf();
- pathTitles = path.children(".forum-nav-browse-title").map(function(i, elem) {
+ path = item.parents('.forum-nav-browse-menu-item').andSelf();
+ pathTitles = path.children('.forum-nav-browse-title').map(function(i, elem) {
return $(elem).text();
}).get();
- return pathTitles.join(" / ");
+ return pathTitles.join(' / ');
};
DiscussionThreadListView.prototype.filterTopics = function(event) {
var items, query,
self = this;
query = $(event.target).val();
- items = this.$(".forum-nav-browse-menu-item");
+ items = this.$('.forum-nav-browse-menu-item');
if (query.length === 0) {
return items.show();
} else {
@@ -490,13 +490,13 @@
return items.each(function(i, item) {
var path, pathText;
item = $(item);
- if (!item.is(":visible")) {
+ if (!item.is(':visible')) {
pathText = self.getPathText(item).toLowerCase();
- if (query.split(" ").every(function(term) {
- return pathText.search(term.toLowerCase()) !== -1;
- })) {
- path = item.parents(".forum-nav-browse-menu-item").andSelf();
- return path.add(item.find(".forum-nav-browse-menu-item")).show();
+ if (query.split(' ').every(function(term) {
+ return pathText.search(term.toLowerCase()) !== -1;
+ })) {
+ path = item.parents('.forum-nav-browse-menu-item').andSelf();
+ return path.add(item.find('.forum-nav-browse-menu-item')).show();
}
}
});
@@ -504,20 +504,20 @@
};
DiscussionThreadListView.prototype.setCurrentTopicDisplay = function(text) {
- return this.$(".forum-nav-browse-current").text(this.fitName(text));
+ return this.$('.forum-nav-browse-current').text(this.fitName(text));
};
DiscussionThreadListView.prototype.getNameWidth = function(name) {
var $test, width;
- $test = $("
");
+ $test = $('
');
$test.css({
- "font-size": this.$(".forum-nav-browse-current").css('font-size'),
+ 'font-size': this.$('.forum-nav-browse-current').css('font-size'),
opacity: 0,
position: 'absolute',
left: -1000,
top: -1000
});
- $("body").append($test);
+ $('body').append($test);
$test.text(name);
width = $test.width();
$test.remove();
@@ -526,28 +526,28 @@
DiscussionThreadListView.prototype.fitName = function(name) {
var partialName, path, prefix, rawName, width, x;
- this.maxNameWidth = this.$(".forum-nav-browse").width() -
- this.$(".forum-nav-browse .icon").outerWidth(true) -
- this.$(".forum-nav-browse-drop-arrow").outerWidth(true);
+ this.maxNameWidth = this.$('.forum-nav-browse').width() -
+ this.$('.forum-nav-browse .icon').outerWidth(true) -
+ this.$('.forum-nav-browse-drop-arrow').outerWidth(true);
width = this.getNameWidth(name);
if (width < this.maxNameWidth) {
return name;
}
path = (function() {
var _i, _len, _ref, _results;
- _ref = name.split("/");
+ _ref = name.split('/');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
x = _ref[_i];
- _results.push(x.replace(/^\s+|\s+$/g, ""));
+ _results.push(x.replace(/^\s+|\s+$/g, ''));
}
return _results;
})();
- prefix = "";
+ prefix = '';
while (path.length > 1) {
- prefix = gettext("…") + "/";
+ prefix = gettext('…') + '/';
path.shift();
- partialName = prefix + path.join("/");
+ partialName = prefix + path.join('/');
if (this.getNameWidth(partialName) < this.maxNameWidth) {
return partialName;
}
@@ -556,7 +556,7 @@
name = prefix + rawName;
while (this.getNameWidth(name) > this.maxNameWidth) {
rawName = rawName.slice(0, rawName.length - 1);
- name = prefix + rawName + gettext("…");
+ name = prefix + rawName + gettext('…');
}
return name;
};
@@ -572,25 +572,25 @@
this.clearSearch();
item = $target.closest('.forum-nav-browse-menu-item');
this.setCurrentTopicDisplay(this.getPathText(item));
- if (item.hasClass("forum-nav-browse-menu-all")) {
- this.discussionIds = "";
+ if (item.hasClass('forum-nav-browse-menu-all')) {
+ this.discussionIds = '';
this.$('.forum-nav-filter-cohort').show();
return this.retrieveAllThreads();
- } else if (item.hasClass("forum-nav-browse-menu-following")) {
+ } else if (item.hasClass('forum-nav-browse-menu-following')) {
this.retrieveFollowed();
return this.$('.forum-nav-filter-cohort').hide();
} else {
- allItems = item.find(".forum-nav-browse-menu-item").andSelf();
- discussionIds = allItems.filter("[data-discussion-id]").map(function(i, elem) {
- return $(elem).data("discussion-id");
+ allItems = item.find('.forum-nav-browse-menu-item').andSelf();
+ discussionIds = allItems.filter('[data-discussion-id]').map(function(i, elem) {
+ return $(elem).data('discussion-id');
}).get();
this.retrieveDiscussions(discussionIds);
- return this.$(".forum-nav-filter-cohort").toggle(item.data('cohorted') === true);
+ return this.$('.forum-nav-filter-cohort').toggle(item.data('cohorted') === true);
}
};
DiscussionThreadListView.prototype.chooseFilter = function() {
- this.filter = $(".forum-nav-filter-main-control :selected").val();
+ this.filter = $('.forum-nav-filter-main-control :selected').val();
return this.retrieveFirstPage();
};
@@ -601,10 +601,10 @@
DiscussionThreadListView.prototype.retrieveDiscussion = function(discussion_id, callback) {
var url, self = this;
- url = DiscussionUtil.urlFor("retrieve_discussion", discussion_id);
+ url = DiscussionUtil.urlFor('retrieve_discussion', discussion_id);
return DiscussionUtil.safeAjax({
url: url,
- type: "GET",
+ type: 'GET',
success: function(response) {
self.collection.current_page = response.page;
self.collection.pages = response.num_pages;
@@ -636,7 +636,7 @@
};
DiscussionThreadListView.prototype.sortThreads = function(event) {
- this.displayedCollection.setSortComparator(this.$(".forum-nav-sort-control").val());
+ this.displayedCollection.setSortComparator(this.$('.forum-nav-sort-control').val());
return this.retrieveFirstPage(event);
};
@@ -649,8 +649,8 @@
if (event.which === 13 || event.type === 'click') {
event.preventDefault();
this.hideBrowseMenu();
- this.setCurrentTopicDisplay(gettext("Search Results"));
- text = this.$(".forum-nav-search-input").val();
+ this.setCurrentTopicDisplay(gettext('Search Results'));
+ text = this.$('.forum-nav-search-input').val();
return this.searchFor(text);
}
};
@@ -661,7 +661,7 @@
this.clearFilters();
this.mode = 'search';
this.current_search = text;
- url = DiscussionUtil.urlFor("search");
+ url = DiscussionUtil.urlFor('search');
/*
TODO: This might be better done by setting discussion.current_page=0 and
calling discussion.loadMorePages
@@ -670,28 +670,28 @@
*/
return DiscussionUtil.safeAjax({
- $elem: this.$(".forum-nav-search-input"),
+ $elem: this.$('.forum-nav-search-input'),
data: {
text: text
},
url: url,
- type: "GET",
+ type: 'GET',
dataType: 'json',
$loading: $,
loadingCallback: function() {
- var element = self.$(".forum-nav-thread-list");
+ var element = self.$('.forum-nav-thread-list');
element.empty();
edx.HtmlUtils.append(
element,
edx.HtmlUtils.joinHtml(
edx.HtmlUtils.HTML("
"),
- self.getLoadingContent(gettext("Loading thread list")),
- edx.HtmlUtils.HTML(" ")
+ self.getLoadingContent(gettext('Loading thread list')),
+ edx.HtmlUtils.HTML('')
)
);
},
loadedCallback: function() {
- return self.$(".forum-nav-thread-list .forum-nav-load-more").remove();
+ return self.$('.forum-nav-thread-list .forum-nav-load-more').remove();
},
success: function(response, textStatus) {
var message, noResponseMsg;
@@ -710,13 +710,13 @@
message = edx.HtmlUtils.interpolateHtml(
noResponseMsg,
{
- "original_query": edx.HtmlUtils.joinHtml(
- edx.HtmlUtils.HTML("
"), text, edx.HtmlUtils.HTML(" ")
+ 'original_query': edx.HtmlUtils.joinHtml(
+ edx.HtmlUtils.HTML('
'), text, edx.HtmlUtils.HTML(' ')
),
- "suggested_query": edx.HtmlUtils.joinHtml(
- edx.HtmlUtils.HTML("
"),
- response.corrected_text ,
- edx.HtmlUtils.HTML(" ")
+ 'suggested_query': edx.HtmlUtils.joinHtml(
+ edx.HtmlUtils.HTML('
'),
+ response.corrected_text,
+ edx.HtmlUtils.HTML(' ')
)
}
);
@@ -739,8 +739,8 @@
data: {
username: text
},
- url: DiscussionUtil.urlFor("users"),
- type: "GET",
+ url: DiscussionUtil.urlFor('users'),
+ type: 'GET',
dataType: 'json',
error: function() {},
success: function(response) {
@@ -749,14 +749,14 @@
username = edx.HtmlUtils.joinHtml(
edx.HtmlUtils.interpolateHtml(
edx.HtmlUtils.HTML('
'),
- {url: DiscussionUtil.urlFor("user_profile", response.users[0].id)}
+ {url: DiscussionUtil.urlFor('user_profile', response.users[0].id)}
),
response.users[0].username,
- edx.HtmlUtils.HTML(" ")
+ edx.HtmlUtils.HTML('')
);
message = edx.HtmlUtils.interpolateHtml(
- gettext('Show posts by {username}.'), {"username": username}
+ gettext('Show posts by {username}.'), {'username': username}
);
return self.addSearchAlert(message, 'search-by-user');
}
@@ -765,14 +765,14 @@
};
DiscussionThreadListView.prototype.clearSearch = function() {
- this.$(".forum-nav-search-input").val("");
- this.current_search = "";
+ this.$('.forum-nav-search-input').val('');
+ this.current_search = '';
return this.clearSearchAlerts();
};
DiscussionThreadListView.prototype.clearFilters = function() {
- this.$(".forum-nav-filter-main-control").val("all");
- return this.$(".forum-nav-filter-cohort-control").val("all");
+ this.$('.forum-nav-filter-main-control').val('all');
+ return this.$('.forum-nav-filter-cohort-control').val('all');
};
DiscussionThreadListView.prototype.retrieveFollowed = function() {
@@ -784,10 +784,10 @@
var $checkbox, checked, urlName;
$checkbox = $('input.email-setting');
checked = $checkbox.prop('checked');
- urlName = (checked) ? "enable_notifications" : "disable_notifications";
+ urlName = (checked) ? 'enable_notifications' : 'disable_notifications';
DiscussionUtil.safeAjax({
url: DiscussionUtil.urlFor(urlName),
- type: "POST",
+ type: 'POST',
error: function() {
$checkbox.prop('checked', !checked);
}
@@ -795,8 +795,6 @@
};
return DiscussionThreadListView;
-
}).call(this, Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/discussion_thread_profile_view.js b/common/static/common/js/discussion/views/discussion_thread_profile_view.js
index 96b84381bb..5d6b65c928 100644
--- a/common/static/common/js/discussion/views/discussion_thread_profile_view.js
+++ b/common/static/common/js/discussion/views/discussion_thread_profile_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionThreadProfileView = (function(_super) {
-
__extends(DiscussionThreadProfileView, _super);
function DiscussionThreadProfileView() {
@@ -44,16 +43,16 @@
}
edx.HtmlUtils.setHtml(
this.$el,
- edx.HtmlUtils.template($("#profile-thread-template").html())(params)
+ edx.HtmlUtils.template($('#profile-thread-template').html())(params)
);
- this.$("span.timeago").timeago();
- DiscussionUtil.typesetMathJax(this.$(".post-body"));
+ this.$('span.timeago').timeago();
+ DiscussionUtil.typesetMathJax(this.$('.post-body'));
return this;
};
DiscussionThreadProfileView.prototype.convertMath = function() {
var htmlSnippet = DiscussionUtil.markdownWithHighlight(this.model.get('body'));
- this.model.set('markdownBody', htmlSnippet);
+ this.model.set('markdownBody', htmlSnippet);
};
DiscussionThreadProfileView.prototype.abbreviateBody = function() {
@@ -63,8 +62,6 @@
};
return DiscussionThreadProfileView;
-
})(Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/discussion_thread_show_view.js b/common/static/common/js/discussion/views/discussion_thread_show_view.js
index 6e13898b69..9e01c6326b 100644
--- a/common/static/common/js/discussion/views/discussion_thread_show_view.js
+++ b/common/static/common/js/discussion/views/discussion_thread_show_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionThreadShowView = (function(_super) {
-
__extends(DiscussionThreadShowView, _super);
function DiscussionThreadShowView() {
@@ -30,9 +29,9 @@
DiscussionThreadShowView.prototype.initialize = function(options) {
var _ref;
DiscussionThreadShowView.__super__.initialize.call(this);
- this.mode = options.mode || "inline";
- if ((_ref = this.mode) !== "tab" && _ref !== "inline") {
- throw new Error("invalid mode: " + this.mode);
+ this.mode = options.mode || 'inline';
+ if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') {
+ throw new Error('invalid mode: ' + this.mode);
}
};
@@ -45,7 +44,7 @@
cid: this.model.cid,
readOnly: $('.discussion-module').data('read-only')
}, this.model.attributes);
- return edx.HtmlUtils.template($("#thread-show-template").html())(context);
+ return edx.HtmlUtils.template($('#thread-show-template').html())(context);
};
DiscussionThreadShowView.prototype.render = function() {
@@ -55,28 +54,26 @@
);
this.delegateEvents();
this.renderAttrs();
- this.$("span.timeago").timeago();
+ this.$('span.timeago').timeago();
this.convertMath();
- this.$(".post-body");
- this.$("h1,h3");
+ this.$('.post-body');
+ this.$('h1,h3');
return this;
};
DiscussionThreadShowView.prototype.convertMath = function() {
- DiscussionUtil.convertMath(this.$(".post-body"));
+ DiscussionUtil.convertMath(this.$('.post-body'));
};
DiscussionThreadShowView.prototype.edit = function(event) {
- return this.trigger("thread:edit", event);
+ return this.trigger('thread:edit', event);
};
DiscussionThreadShowView.prototype._delete = function(event) {
- return this.trigger("thread:_delete", event);
+ return this.trigger('thread:_delete', event);
};
return DiscussionThreadShowView;
-
})(DiscussionContentShowView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/discussion_thread_view.js b/common/static/common/js/discussion/views/discussion_thread_view.js
index 8a859e77cb..9ae6ff5ce8 100644
--- a/common/static/common/js/discussion/views/discussion_thread_view.js
+++ b/common/static/common/js/discussion/views/discussion_thread_view.js
@@ -21,7 +21,7 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionThreadView = (function(_super) {
var INITIAL_RESPONSE_PAGE_SIZE, SUBSEQUENT_RESPONSE_PAGE_SIZE;
@@ -61,10 +61,10 @@
SUBSEQUENT_RESPONSE_PAGE_SIZE = 100;
DiscussionThreadView.prototype.events = {
- "click .discussion-submit-post": "submitComment",
- "click .add-response-btn": "scrollToAddResponse",
- "click .forum-thread-expand": "expand",
- "click .forum-thread-collapse": "collapse"
+ 'click .discussion-submit-post': 'submitComment',
+ 'click .add-response-btn': 'scrollToAddResponse',
+ 'click .forum-thread-expand': 'expand',
+ 'click .forum-thread-collapse': 'collapse'
};
DiscussionThreadView.prototype.$ = function(selector) {
@@ -72,23 +72,23 @@
};
DiscussionThreadView.prototype.isQuestion = function() {
- return this.model.get("thread_type") === "question";
+ return this.model.get('thread_type') === 'question';
};
DiscussionThreadView.prototype.initialize = function(options) {
var _ref,
self = this;
DiscussionThreadView.__super__.initialize.call(this);
- this.mode = options.mode || "inline";
- this.context = options.context || "course";
+ this.mode = options.mode || 'inline';
+ this.context = options.context || 'course';
this.options = _.extend({}, options);
- if ((_ref = this.mode) !== "tab" && _ref !== "inline") {
- throw new Error("invalid mode: " + this.mode);
+ if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') {
+ throw new Error('invalid mode: ' + this.mode);
}
- this.readOnly = $(".discussion-module").data('read-only');
- this.model.collection.on("reset", function(collection) {
+ this.readOnly = $('.discussion-module').data('read-only');
+ this.model.collection.on('reset', function(collection) {
var id;
- id = self.model.get("id");
+ id = self.model.get('id');
if (collection.get(id)) {
self.model = collection.get(id);
self.rerender();
@@ -120,14 +120,14 @@
DiscussionThreadView.prototype.renderTemplate = function() {
var container, templateData;
- this.template = _.template($("#thread-template").html());
- container = $("#discussion-container");
+ this.template = _.template($('#thread-template').html());
+ container = $('#discussion-container');
if (!container.length) {
- container = $(".discussion-module");
+ container = $('.discussion-module');
}
templateData = _.extend(this.model.toJSON(), {
readOnly: this.readOnly,
- can_create_comment: container.data("user-create-comment")
+ can_create_comment: container.data('user-create-comment')
});
return this.template(templateData);
};
@@ -140,24 +140,24 @@
this.delegateEvents();
this.renderShowView();
this.renderAttrs();
- this.$("span.timeago").timeago();
- this.makeWmdEditor("reply-body");
+ this.$('span.timeago').timeago();
+ this.makeWmdEditor('reply-body');
this.renderAddResponseButton();
- this.responses.on("add", function(response) {
- return self.renderResponseToList(response, ".js-response-list", {});
+ this.responses.on('add', function(response) {
+ return self.renderResponseToList(response, '.js-response-list', {});
});
if (this.isQuestion()) {
- this.markedAnswers.on("add", function(response) {
- return self.renderResponseToList(response, ".js-marked-answer-list", {
+ this.markedAnswers.on('add', function(response) {
+ return self.renderResponseToList(response, '.js-marked-answer-list', {
collapseComments: true
});
});
}
- if (this.mode === "tab") {
+ if (this.mode === 'tab') {
setTimeout(function() {
return self.loadInitialResponses();
}, 100);
- return this.$(".post-tools").hide();
+ return this.$('.post-tools').hide();
} else {
return this.collapse();
}
@@ -165,10 +165,10 @@
DiscussionThreadView.prototype.attrRenderer = $.extend({}, DiscussionContentView.prototype.attrRenderer, {
closed: function(closed) {
- this.$(".discussion-reply-new").toggle(!closed);
+ this.$('.discussion-reply-new').toggle(!closed);
this.$('.comment-form').closest('li').toggle(!closed);
- this.$(".action-vote").toggle(!closed);
- this.$(".display-vote").toggle(closed);
+ this.$('.action-vote').toggle(!closed);
+ this.$('.display-vote').toggle(closed);
return this.renderAddResponseButton();
}
});
@@ -177,12 +177,12 @@
if (event) {
event.preventDefault();
}
- this.$el.addClass("expanded");
- this.$el.find(".post-body").text(this.model.get("body"));
+ this.$el.addClass('expanded');
+ this.$el.find('.post-body').text(this.model.get('body'));
this.showView.convertMath();
- this.$el.find(".forum-thread-expand").hide();
- this.$el.find(".forum-thread-collapse").show();
- this.$el.find(".post-extended-content").show();
+ this.$el.find('.forum-thread-expand').hide();
+ this.$el.find('.forum-thread-collapse').show();
+ this.$el.find('.post-extended-content').show();
if (!this.loadedResponses) {
return this.loadInitialResponses();
}
@@ -192,28 +192,31 @@
if (event) {
event.preventDefault();
}
- this.$el.removeClass("expanded");
- this.$el.find(".post-body").text(this.getAbbreviatedBody());
+ this.$el.removeClass('expanded');
+ this.$el.find('.post-body').text(this.getAbbreviatedBody());
this.showView.convertMath();
- this.$el.find(".forum-thread-expand").show();
- this.$el.find(".forum-thread-collapse").hide();
- return this.$el.find(".post-extended-content").hide();
+ this.$el.find('.forum-thread-expand').show();
+ this.$el.find('.forum-thread-collapse').hide();
+ return this.$el.find('.post-extended-content').hide();
};
DiscussionThreadView.prototype.getAbbreviatedBody = function() {
var abbreviated, cached;
- cached = this.model.get("abbreviatedBody");
+ cached = this.model.get('abbreviatedBody');
if (cached) {
return cached;
} else {
- abbreviated = DiscussionUtil.abbreviateString(this.model.get("body"), 140);
- this.model.set("abbreviatedBody", abbreviated);
+ abbreviated = DiscussionUtil.abbreviateString(this.model.get('body'), 140);
+ this.model.set('abbreviatedBody', abbreviated);
return abbreviated;
}
};
DiscussionThreadView.prototype.cleanup = function() {
- if (this.responsesRequest) {
+ // jQuery.ajax after 1.5 returns a jqXHR which doesn't implement .abort
+ // but I don't feel confident enough about what's going on here to remove this code
+ // so just check to make sure we can abort before we try to
+ if (this.responsesRequest && this.responsesRequest.abort) {
return this.responsesRequest.abort();
}
};
@@ -221,7 +224,7 @@
DiscussionThreadView.prototype.loadResponses = function(responseLimit, $elem, firstLoad) {
var takeFocus,
self = this;
- takeFocus = this.mode === "tab" ? false : true;
+ takeFocus = this.mode === 'tab' ? false : true;
this.responsesRequest = DiscussionUtil.safeAjax({
url: DiscussionUtil.urlFor(
'retrieve_single_thread', this.model.get('commentable_id'), this.model.id
@@ -249,7 +252,7 @@
data.content.non_endorsed_resp_total :
data.content.resp_total
);
- self.trigger("thread:responses:rendered");
+ self.trigger('thread:responses:rendered');
self.loadedResponses = true;
return self.$el.find('.discussion-article[data-id="' + self.model.id + '"]').focus();
},
@@ -259,18 +262,18 @@
}
if (xhr.status === 404) {
DiscussionUtil.discussionAlert(
- gettext("Sorry"),
- gettext("The thread you selected has been deleted. Please select another thread.")
+ gettext('Sorry'),
+ gettext('The thread you selected has been deleted. Please select another thread.')
);
} else if (firstLoad) {
DiscussionUtil.discussionAlert(
- gettext("Sorry"),
- gettext("We had some trouble loading responses. Please reload the page.")
+ gettext('Sorry'),
+ gettext('We had some trouble loading responses. Please reload the page.')
);
} else {
DiscussionUtil.discussionAlert(
- gettext("Sorry"),
- gettext("We had some trouble loading more responses. Please try again.")
+ gettext('Sorry'),
+ gettext('We had some trouble loading more responses. Please try again.')
);
}
}
@@ -278,7 +281,7 @@
};
DiscussionThreadView.prototype.loadInitialResponses = function() {
- return this.loadResponses(INITIAL_RESPONSE_PAGE_SIZE, this.$el.find(".js-response-list"), true);
+ return this.loadResponses(INITIAL_RESPONSE_PAGE_SIZE, this.$el.find('.js-response-list'), true);
};
DiscussionThreadView.prototype.renderResponseCountAndPagination = function(responseTotal) {
@@ -286,47 +289,47 @@
responsesRemaining, showingResponsesText, self = this;
if (this.isQuestion() && this.markedAnswers.length !== 0) {
responseCountFormat = ngettext(
- "{numResponses} other response", "{numResponses} other responses", responseTotal
+ '{numResponses} other response', '{numResponses} other responses', responseTotal
);
} else {
responseCountFormat = ngettext(
- "{numResponses} response", "{numResponses} responses", responseTotal
+ '{numResponses} response', '{numResponses} responses', responseTotal
);
}
- this.$el.find(".response-count").text(
+ this.$el.find('.response-count').text(
edx.StringUtils.interpolate(responseCountFormat, {numResponses: responseTotal}, true)
);
- responsePagination = this.$el.find(".response-pagination");
+ responsePagination = this.$el.find('.response-pagination');
responsePagination.empty();
if (responseTotal > 0) {
responsesRemaining = responseTotal - this.responses.size();
if (responsesRemaining === 0) {
- showingResponsesText = gettext("Showing all responses");
+ showingResponsesText = gettext('Showing all responses');
}
else {
showingResponsesText = edx.StringUtils.interpolate(
ngettext(
- "Showing first response", "Showing first {numResponses} responses",
+ 'Showing first response', 'Showing first {numResponses} responses',
this.responses.size()
),
- { numResponses: this.responses.size() },
+ {numResponses: this.responses.size()},
true
);
}
- responsePagination.append($("
")
- .addClass("response-display-count").text(showingResponsesText));
+ responsePagination.append($('')
+ .addClass('response-display-count').text(showingResponsesText));
if (responsesRemaining > 0) {
if (responsesRemaining < SUBSEQUENT_RESPONSE_PAGE_SIZE) {
responseLimit = null;
- buttonText = gettext("Load all responses");
+ buttonText = gettext('Load all responses');
} else {
responseLimit = SUBSEQUENT_RESPONSE_PAGE_SIZE;
- buttonText = edx.StringUtils.interpolate(gettext("Load next {numResponses} responses"), {
+ buttonText = edx.StringUtils.interpolate(gettext('Load next {numResponses} responses'), {
numResponses: responseLimit
}, true);
}
- $loadMoreButton = $("").addClass("load-response-button").text(buttonText);
+ $loadMoreButton = $('').addClass('load-response-button').text(buttonText);
$loadMoreButton.click(function() {
return self.loadResponses(responseLimit, $loadMoreButton);
});
@@ -341,8 +344,8 @@
view = new ThreadResponseView($.extend({
model: response
}, options));
- view.on("comment:add", this.addComment);
- view.on("comment:endorse", this.endorseThread);
+ view.on('comment:add', this.addComment);
+ view.on('comment:endorse', this.endorseThread);
view.render();
this.$el.find(listSelector).append(view.el);
return view.afterInsert();
@@ -369,37 +372,37 @@
};
DiscussionThreadView.prototype.endorseThread = function() {
- return this.model.set('endorsed', this.$el.find(".action-answer.is-checked").length > 0);
+ return this.model.set('endorsed', this.$el.find('.action-answer.is-checked').length > 0);
};
DiscussionThreadView.prototype.submitComment = function(event) {
var body, comment, url;
event.preventDefault();
url = this.model.urlFor('reply');
- body = this.getWmdContent("reply-body");
+ body = this.getWmdContent('reply-body');
if (!body.trim().length) {
return;
}
- this.setWmdContent("reply-body", "");
+ this.setWmdContent('reply-body', '');
comment = new Comment({
body: body,
created_at: (new Date()).toISOString(),
- username: window.user.get("username"),
+ username: window.user.get('username'),
votes: {
up_count: 0
},
abuse_flaggers: [],
endorsed: false,
- user_id: window.user.get("id")
+ user_id: window.user.get('id')
});
comment.set('thread', this.model.get('thread'));
- this.renderResponseToList(comment, ".js-response-list");
+ this.renderResponseToList(comment, '.js-response-list');
this.model.addComment();
this.renderAddResponseButton();
return DiscussionUtil.safeAjax({
$elem: $(event.target),
url: url,
- type: "POST",
+ type: 'POST',
dataType: 'json',
data: {
body: body
@@ -429,8 +432,8 @@
context: this.context,
course_settings: this.options.course_settings
});
- this.editView.bind("thread:updated thread:cancel_edit", this.closeEditView);
- return this.editView.bind("comment:endorse", this.endorseThread);
+ this.editView.bind('thread:updated thread:cancel_edit', this.closeEditView);
+ return this.editView.bind('comment:endorse', this.endorseThread);
};
DiscussionThreadView.prototype.renderSubView = function(view) {
@@ -448,8 +451,8 @@
model: this.model,
mode: this.mode
});
- this.showView.bind("thread:_delete", this._delete);
- return this.showView.bind("thread:edit", this.edit);
+ this.showView.bind('thread:_delete', this._delete);
+ return this.showView.bind('thread:edit', this.edit);
};
DiscussionThreadView.prototype.renderShowView = function() {
@@ -460,7 +463,7 @@
this.createShowView();
this.renderShowView();
this.renderAttrs();
- return this.$el.find(".post-extended-content").show();
+ return this.$el.find('.post-extended-content').show();
};
DiscussionThreadView.prototype._delete = function(event) {
@@ -469,7 +472,7 @@
if (!this.model.can('can_delete')) {
return;
}
- if (!confirm(gettext("Are you sure you want to delete this post?"))) {
+ if (!confirm(gettext('Are you sure you want to delete this post?'))) {
return;
}
this.model.remove();
@@ -480,13 +483,11 @@
return DiscussionUtil.safeAjax({
$elem: $elem,
url: url,
- type: "POST"
+ type: 'POST'
});
};
return DiscussionThreadView;
-
})(DiscussionContentView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/discussion_topic_menu_view.js b/common/static/common/js/discussion/views/discussion_topic_menu_view.js
index 5b701822b4..bebd6c7db7 100644
--- a/common/static/common/js/discussion/views/discussion_topic_menu_view.js
+++ b/common/static/common/js/discussion/views/discussion_topic_menu_view.js
@@ -153,7 +153,7 @@
if (name.length < this.maxNameWidth) {
return name;
} else {
- path = _.map(name.split('/'), function(item){
+ path = _.map(name.split('/'), function(item) {
return item.replace(/^\s+|\s+$/g, '');
});
while (path.length > 1) {
@@ -166,9 +166,9 @@
rawName = path[0];
name = ellipsisText + ' / ' + rawName;
if (name.length > this.maxNameWidth) {
- concatedLength = ellipsisText.length + ' / '.length + ellipsisText.length;
- rawName = rawName.slice(0, this.maxNameWidth - concatedLength);
- name = ellipsisText + ' / ' + rawName + ' ' + ellipsisText;
+ concatedLength = ellipsisText.length + ' / '.length + ellipsisText.length;
+ rawName = rawName.slice(0, this.maxNameWidth - concatedLength);
+ name = ellipsisText + ' / ' + rawName + ' ' + ellipsisText;
}
}
return name;
@@ -191,14 +191,14 @@
$items.addClass('hidden');
$items.each(function(_index, item) {
var path, pathText, pathTitles;
- path = $(item).parents(".topic-menu-item").andSelf();
- pathTitles = path.children(".topic-title").map(function(_, elem) {
+ path = $(item).parents('.topic-menu-item').andSelf();
+ pathTitles = path.children('.topic-title').map(function(_, elem) {
return $(elem).text();
}).get();
- pathText = pathTitles.join(" / ").toLowerCase();
- if (query.split(" ").every(function(term) {
- return pathText.search(term.toLowerCase()) !== -1;
- })) {
+ pathText = pathTitles.join(' / ').toLowerCase();
+ if (query.split(' ').every(function(term) {
+ return pathText.search(term.toLowerCase()) !== -1;
+ })) {
$(item).removeClass('hidden');
$(item).find('.topic-menu-item').removeClass('hidden');
$(item).parents('.topic-menu-item').removeClass('hidden');
diff --git a/common/static/common/js/discussion/views/discussion_user_profile_view.js b/common/static/common/js/discussion/views/discussion_user_profile_view.js
index b182ba66ca..69c773199f 100644
--- a/common/static/common/js/discussion/views/discussion_user_profile_view.js
+++ b/common/static/common/js/discussion/views/discussion_user_profile_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.DiscussionUserProfileView = (function(_super) {
-
__extends(DiscussionUserProfileView, _super);
function DiscussionUserProfileView() {
@@ -32,7 +31,7 @@
}
DiscussionUserProfileView.prototype.events = {
- "click .discussion-paginator a": "changePage"
+ 'click .discussion-paginator a': 'changePage'
};
DiscussionUserProfileView.prototype.initialize = function(options) {
@@ -40,7 +39,7 @@
this.page = options.page;
this.numPages = options.numPages;
this.discussion = new Discussion();
- this.discussion.on("reset", this.render);
+ this.discussion.on('reset', this.render);
return this.discussion.reset(this.collection, {
silent: false
});
@@ -49,59 +48,57 @@
DiscussionUserProfileView.prototype.render = function() {
var baseUri, pageUrlFunc, paginationParams,
self = this;
- this.$el.html(_.template($("#user-profile-template").html())({
+ this.$el.html(_.template($('#user-profile-template').html())({
threads: this.discussion.models
}));
this.discussion.map(function(thread) {
return new DiscussionThreadProfileView({
- el: self.$("article#thread_" + thread.id),
+ el: self.$('article#thread_' + thread.id),
model: thread
}).render();
});
- baseUri = URI(window.location).removeSearch("page");
+ baseUri = URI(window.location).removeSearch('page');
pageUrlFunc = function(page) {
- return baseUri.clone().addSearch("page", page);
+ return baseUri.clone().addSearch('page', page);
};
paginationParams = DiscussionUtil.getPaginationParams(this.page, this.numPages, pageUrlFunc);
- this.$el.find(".discussion-pagination")
- .html(_.template($("#pagination-template").html())(paginationParams));
+ this.$el.find('.discussion-pagination')
+ .html(_.template($('#pagination-template').html())(paginationParams));
};
DiscussionUserProfileView.prototype.changePage = function(event) {
var url,
self = this;
event.preventDefault();
- url = $(event.target).attr("href");
+ url = $(event.target).attr('href');
return DiscussionUtil.safeAjax({
$elem: this.$el,
$loading: $(event.target),
takeFocus: true,
url: url,
- type: "GET",
- dataType: "json",
+ type: 'GET',
+ dataType: 'json',
success: function(response) {
self.page = response.page;
self.numPages = response.num_pages;
self.discussion.reset(response.discussion_data, {
silent: false
});
- history.pushState({}, "", url);
- return $("html, body").animate({
+ history.pushState({}, '', url);
+ return $('html, body').animate({
scrollTop: 0
});
},
error: function() {
return DiscussionUtil.discussionAlert(
- gettext("Sorry"),
- gettext("We had some trouble loading the page you requested. Please try again.")
+ gettext('Sorry'),
+ gettext('We had some trouble loading the page you requested. Please try again.')
);
}
});
};
return DiscussionUserProfileView;
-
})(Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/new_post_view.js b/common/static/common/js/discussion/views/new_post_view.js
index 396ff5c247..4bbadff0e0 100644
--- a/common/static/common/js/discussion/views/new_post_view.js
+++ b/common/static/common/js/discussion/views/new_post_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.NewPostView = (function(_super) {
-
__extends(NewPostView, _super);
function NewPostView() {
@@ -36,9 +35,9 @@
NewPostView.prototype.initialize = function(options) {
var _ref;
- this.mode = options.mode || "inline";
- if ((_ref = this.mode) !== "tab" && _ref !== "inline") {
- throw new Error("invalid mode: " + this.mode);
+ this.mode = options.mode || 'inline';
+ if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') {
+ throw new Error('invalid mode: ' + this.mode);
}
this.course_settings = options.course_settings;
this.is_commentable_cohorted = options.is_commentable_cohorted;
@@ -52,15 +51,15 @@
cohort_options: this.getCohortOptions(),
is_commentable_cohorted: this.is_commentable_cohorted,
mode: this.mode,
- form_id: this.mode + (this.topicId ? "-" + this.topicId : "")
+ form_id: this.mode + (this.topicId ? '-' + this.topicId : '')
});
- this.$el.html(_.template($("#new-post-template").html())(context));
- threadTypeTemplate = _.template($("#thread-type-template").html());
+ this.$el.html(_.template($('#new-post-template').html())(context));
+ threadTypeTemplate = _.template($('#thread-type-template').html());
if ($('.js-group-select').is(':disabled')) {
$('.group-selector-wrapper').addClass('disabled');
}
this.addField(threadTypeTemplate({
- form_id: _.uniqueId("form-")
+ form_id: _.uniqueId('form-')
}));
if (this.isTabMode()) {
this.topicView = new DiscussionTopicMenuView({
@@ -70,7 +69,7 @@
this.topicView.on('thread:topic_change', this.toggleGroupDropdown);
this.addField(this.topicView.render());
}
- return DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), "js-post-body");
+ return DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), 'js-post-body');
};
NewPostView.prototype.addField = function(fieldView) {
@@ -78,14 +77,14 @@
};
NewPostView.prototype.isTabMode = function() {
- return this.mode === "tab";
+ return this.mode === 'tab';
};
NewPostView.prototype.getCohortOptions = function() {
var user_cohort_id;
- if (this.course_settings.get("is_cohorted") && DiscussionUtil.isPrivilegedUser()) {
- user_cohort_id = $("#discussion-container").data("user-cohort-id");
- return _.map(this.course_settings.get("cohorts"), function(cohort) {
+ if (this.course_settings.get('is_cohorted') && DiscussionUtil.isPrivilegedUser()) {
+ user_cohort_id = $('#discussion-container').data('user-cohort-id');
+ return _.map(this.course_settings.get('cohorts'), function(cohort) {
return {
value: cohort.id,
text: cohort.name,
@@ -98,10 +97,10 @@
};
NewPostView.prototype.events = {
- "submit .forum-new-post-form": "createPost",
- "change .post-option-input": "postOptionChange",
- "click .cancel": "cancel",
- "reset .forum-new-post-form": "updateStyles"
+ 'submit .forum-new-post-form': 'createPost',
+ 'change .post-option-input': 'postOptionChange',
+ 'click .cancel': 'cancel',
+ 'reset .forum-new-post-form': 'updateStyles'
};
NewPostView.prototype.toggleGroupDropdown = function($target) {
@@ -117,11 +116,11 @@
NewPostView.prototype.postOptionChange = function(event) {
var $optionElem, $target;
$target = $(event.target);
- $optionElem = $target.closest(".post-option");
- if ($target.is(":checked")) {
- return $optionElem.addClass("is-enabled");
+ $optionElem = $target.closest('.post-option');
+ if ($target.is(':checked')) {
+ return $optionElem.addClass('is-enabled');
} else {
- return $optionElem.removeClass("is-enabled");
+ return $optionElem.removeClass('is-enabled');
}
};
@@ -129,20 +128,20 @@
var anonymous, anonymous_to_peers, body, follow, group, thread_type, title, topicId, url,
self = this;
event.preventDefault();
- thread_type = this.$(".post-type-input:checked").val();
- title = this.$(".js-post-title").val();
- body = this.$(".js-post-body").find(".wmd-input").val();
- group = this.$(".js-group-select option:selected").attr("value");
- anonymous = false || this.$(".js-anon").is(":checked");
- anonymous_to_peers = false || this.$(".js-anon-peers").is(":checked");
- follow = false || this.$(".js-follow").is(":checked");
+ thread_type = this.$('.post-type-input:checked').val();
+ title = this.$('.js-post-title').val();
+ body = this.$('.js-post-body').find('.wmd-input').val();
+ group = this.$('.js-group-select option:selected').attr('value');
+ anonymous = false || this.$('.js-anon').is(':checked');
+ anonymous_to_peers = false || this.$('.js-anon-peers').is(':checked');
+ follow = false || this.$('.js-follow').is(':checked');
topicId = this.isTabMode() ? this.topicView.getCurrentTopicId() : this.topicId;
url = DiscussionUtil.urlFor('create_thread', topicId);
return DiscussionUtil.safeAjax({
$elem: $(event.target),
$loading: event ? $(event.target) : void 0,
url: url,
- type: "POST",
+ type: 'POST',
dataType: 'json',
data: {
thread_type: thread_type,
@@ -153,7 +152,7 @@
auto_subscribe: follow,
group_id: group
},
- error: DiscussionUtil.formErrorHandler(this.$(".post-errors")),
+ error: DiscussionUtil.formErrorHandler(this.$('.post-errors')),
success: function(response) {
var thread;
thread = new Thread(response.content);
@@ -166,7 +165,7 @@
NewPostView.prototype.cancel = function(event) {
event.preventDefault();
- if (!confirm(gettext("Your post will be discarded."))) {
+ if (!confirm(gettext('Your post will be discarded.'))) {
return;
}
this.trigger('newPost:cancel');
@@ -174,22 +173,20 @@
};
NewPostView.prototype.resetForm = function() {
- this.$(".forum-new-post-form")[0].reset();
- DiscussionUtil.clearFormErrors(this.$(".post-errors"));
- this.$(".wmd-preview p").html("");
+ this.$('.forum-new-post-form')[0].reset();
+ DiscussionUtil.clearFormErrors(this.$('.post-errors'));
+ this.$('.wmd-preview p').html('');
if (this.isTabMode()) {
- return this.topicView.setTopic(this.$("a.topic-title").first());
+ return this.topicView.setTopic(this.$('a.topic-title').first());
}
};
NewPostView.prototype.updateStyles = function() {
var self = this;
- return setTimeout(function() {return self.$(".post-option-input").trigger("change");}, 1);
+ return setTimeout(function() { return self.$('.post-option-input').trigger('change'); }, 1);
};
return NewPostView;
-
})(Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/response_comment_edit_view.js b/common/static/common/js/discussion/views/response_comment_edit_view.js
index 57ad3ebf1b..a7de68e051 100644
--- a/common/static/common/js/discussion/views/response_comment_edit_view.js
+++ b/common/static/common/js/discussion/views/response_comment_edit_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ResponseCommentEditView = (function(_super) {
-
__extends(ResponseCommentEditView, _super);
function ResponseCommentEditView() {
@@ -28,8 +27,8 @@
}
ResponseCommentEditView.prototype.events = {
- "click .post-update": "update",
- "click .post-cancel": "cancel_edit"
+ 'click .post-update': 'update',
+ 'click .post-cancel': 'cancel_edit'
};
ResponseCommentEditView.prototype.$ = function(selector) {
@@ -41,24 +40,22 @@
};
ResponseCommentEditView.prototype.render = function() {
- this.template = _.template($("#response-comment-edit-template").html());
+ this.template = _.template($('#response-comment-edit-template').html());
this.$el.html(this.template(this.model.toJSON()));
this.delegateEvents();
- DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), "edit-comment-body");
+ DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), 'edit-comment-body');
return this;
};
ResponseCommentEditView.prototype.update = function(event) {
- return this.trigger("comment:update", event);
+ return this.trigger('comment:update', event);
};
ResponseCommentEditView.prototype.cancel_edit = function(event) {
- return this.trigger("comment:cancel_edit", event);
+ return this.trigger('comment:cancel_edit', event);
};
return ResponseCommentEditView;
-
})(Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/response_comment_show_view.js b/common/static/common/js/discussion/views/response_comment_show_view.js
index 731d9e9766..bba177d851 100644
--- a/common/static/common/js/discussion/views/response_comment_show_view.js
+++ b/common/static/common/js/discussion/views/response_comment_show_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ResponseCommentShowView = (function(_super) {
-
__extends(ResponseCommentShowView, _super);
function ResponseCommentShowView() {
@@ -34,10 +33,10 @@
return ResponseCommentShowView.__super__.constructor.apply(this, arguments);
}
- ResponseCommentShowView.prototype.tagName = "li";
+ ResponseCommentShowView.prototype.tagName = 'li';
ResponseCommentShowView.prototype.render = function() {
- var template = edx.HtmlUtils.template($("#response-comment-show-template").html());
+ var template = edx.HtmlUtils.template($('#response-comment-show-template').html());
var context = _.extend({
cid: this.model.cid,
author_display: this.getAuthorDisplay(),
@@ -47,7 +46,7 @@
edx.HtmlUtils.setHtml(this.$el, template(context));
this.delegateEvents();
this.renderAttrs();
- this.$el.find(".timeago").timeago();
+ this.$el.find('.timeago').timeago();
this.convertMath();
this.addReplyLink();
return this;
@@ -56,7 +55,7 @@
ResponseCommentShowView.prototype.addReplyLink = function() {
var html, name;
if (this.model.hasOwnProperty('parent')) {
- name = this.model.parent.get('username') || gettext("anonymous");
+ name = this.model.parent.get('username') || gettext('anonymous');
html = edx.HtmlUtils.interpolateHtml(
edx.HtmlUtils.HTML("@{name} : "),
{
@@ -72,20 +71,18 @@
};
ResponseCommentShowView.prototype.convertMath = function() {
- DiscussionUtil.convertMath(this.$el.find(".response-body"));
+ DiscussionUtil.convertMath(this.$el.find('.response-body'));
};
ResponseCommentShowView.prototype._delete = function(event) {
- return this.trigger("comment:_delete", event);
+ return this.trigger('comment:_delete', event);
};
ResponseCommentShowView.prototype.edit = function(event) {
- return this.trigger("comment:edit", event);
+ return this.trigger('comment:edit', event);
};
return ResponseCommentShowView;
-
})(DiscussionContentShowView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/response_comment_view.js b/common/static/common/js/discussion/views/response_comment_view.js
index 7fb3429fd4..7e7afd63e4 100644
--- a/common/static/common/js/discussion/views/response_comment_view.js
+++ b/common/static/common/js/discussion/views/response_comment_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ResponseCommentView = (function(_super) {
-
__extends(ResponseCommentView, _super);
function ResponseCommentView() {
@@ -40,7 +39,7 @@
return ResponseCommentView.__super__.constructor.apply(this, arguments);
}
- ResponseCommentView.prototype.tagName = "li";
+ ResponseCommentView.prototype.tagName = 'li';
ResponseCommentView.prototype.$ = function(selector) {
return this.$el.find(selector);
@@ -71,8 +70,8 @@
this.showView = new ResponseCommentShowView({
model: this.model
});
- this.showView.bind("comment:_delete", this._delete);
- this.showView.bind("comment:edit", this.edit);
+ this.showView.bind('comment:_delete', this._delete);
+ this.showView.bind('comment:edit', this.edit);
return this.renderSubView(this.showView);
}
};
@@ -87,8 +86,8 @@
this.editView = new ResponseCommentEditView({
model: this.model
});
- this.editView.bind("comment:update", this.update);
- this.editView.bind("comment:cancel_edit", this.cancelEdit);
+ this.editView.bind('comment:update', this.update);
+ this.editView.bind('comment:cancel_edit', this.cancelEdit);
return this.renderSubView(this.editView);
}
};
@@ -100,7 +99,7 @@
if (!this.model.can('can_delete')) {
return;
}
- if (!confirm(gettext("Are you sure you want to delete this comment?"))) {
+ if (!confirm(gettext('Are you sure you want to delete this comment?'))) {
return;
}
url = this.model.urlFor('_delete');
@@ -108,55 +107,53 @@
return DiscussionUtil.safeAjax({
$elem: $elem,
url: url,
- type: "POST",
+ type: 'POST',
success: function() {
self.model.remove();
return self.$el.remove();
},
error: function() {
return DiscussionUtil.discussionAlert(
- gettext("Sorry"),
- gettext("We had some trouble deleting this comment. Please try again.")
+ gettext('Sorry'),
+ gettext('We had some trouble deleting this comment. Please try again.')
);
}
});
};
ResponseCommentView.prototype.cancelEdit = function(event) {
- this.trigger("comment:cancel_edit", event);
+ this.trigger('comment:cancel_edit', event);
return this.renderShowView();
};
ResponseCommentView.prototype.edit = function(event) {
- this.trigger("comment:edit", event);
+ this.trigger('comment:edit', event);
return this.renderEditView();
};
ResponseCommentView.prototype.update = function(event) {
var newBody, url,
self = this;
- newBody = this.editView.$(".edit-comment-body textarea").val();
- url = DiscussionUtil.urlFor("update_comment", this.model.id);
+ newBody = this.editView.$('.edit-comment-body textarea').val();
+ url = DiscussionUtil.urlFor('update_comment', this.model.id);
return DiscussionUtil.safeAjax({
$elem: $(event.target),
$loading: $(event.target),
url: url,
- type: "POST",
- dataType: "json",
+ type: 'POST',
+ dataType: 'json',
data: {
body: newBody
},
- error: DiscussionUtil.formErrorHandler(this.$(".edit-comment-form-errors")),
+ error: DiscussionUtil.formErrorHandler(this.$('.edit-comment-form-errors')),
success: function() {
- self.model.set("body", newBody);
+ self.model.set('body', newBody);
return self.cancelEdit();
}
});
};
return ResponseCommentView;
-
})(DiscussionContentView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/thread_response_edit_view.js b/common/static/common/js/discussion/views/thread_response_edit_view.js
index 610167db06..e41a6daf9c 100644
--- a/common/static/common/js/discussion/views/thread_response_edit_view.js
+++ b/common/static/common/js/discussion/views/thread_response_edit_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ThreadResponseEditView = (function(_super) {
-
__extends(ThreadResponseEditView, _super);
function ThreadResponseEditView() {
@@ -28,8 +27,8 @@
}
ThreadResponseEditView.prototype.events = {
- "click .post-update": "update",
- "click .post-cancel": "cancel_edit"
+ 'click .post-update': 'update',
+ 'click .post-cancel': 'cancel_edit'
};
ThreadResponseEditView.prototype.$ = function(selector) {
@@ -41,24 +40,22 @@
};
ThreadResponseEditView.prototype.render = function() {
- this.template = _.template($("#thread-response-edit-template").html());
+ this.template = _.template($('#thread-response-edit-template').html());
this.$el.html(this.template(this.model.toJSON()));
this.delegateEvents();
- DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), "edit-post-body");
+ DiscussionUtil.makeWmdEditor(this.$el, $.proxy(this.$, this), 'edit-post-body');
return this;
};
ThreadResponseEditView.prototype.update = function(event) {
- return this.trigger("response:update", event);
+ return this.trigger('response:update', event);
};
ThreadResponseEditView.prototype.cancel_edit = function(event) {
- return this.trigger("response:cancel_edit", event);
+ return this.trigger('response:cancel_edit', event);
};
return ThreadResponseEditView;
-
})(Backbone.View);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/thread_response_show_view.js b/common/static/common/js/discussion/views/thread_response_show_view.js
index 4ab9914442..896b05b837 100644
--- a/common/static/common/js/discussion/views/thread_response_show_view.js
+++ b/common/static/common/js/discussion/views/thread_response_show_view.js
@@ -18,9 +18,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ThreadResponseShowView = (function(_super) {
-
__extends(ThreadResponseShowView, _super);
function ThreadResponseShowView() {
@@ -29,11 +28,11 @@
ThreadResponseShowView.prototype.initialize = function() {
ThreadResponseShowView.__super__.initialize.call(this);
- return this.listenTo(this.model, "change", this.render);
+ return this.listenTo(this.model, 'change', this.render);
};
ThreadResponseShowView.prototype.renderTemplate = function() {
- var template = edx.HtmlUtils.template($("#thread-response-show-template").html()),
+ var template = edx.HtmlUtils.template($('#thread-response-show-template').html()),
context = _.extend({
cid: this.model.cid,
author_display: this.getAuthorDisplay(),
@@ -47,26 +46,24 @@
edx.HtmlUtils.setHtml(this.$el, this.renderTemplate());
this.delegateEvents();
this.renderAttrs();
- this.$el.find(".posted-details .timeago").timeago();
+ this.$el.find('.posted-details .timeago').timeago();
this.convertMath();
return this;
};
ThreadResponseShowView.prototype.convertMath = function() {
- DiscussionUtil.convertMath(this.$(".response-body"));
+ DiscussionUtil.convertMath(this.$('.response-body'));
};
ThreadResponseShowView.prototype.edit = function(event) {
- return this.trigger("response:edit", event);
+ return this.trigger('response:edit', event);
};
ThreadResponseShowView.prototype._delete = function(event) {
- return this.trigger("response:_delete", event);
+ return this.trigger('response:_delete', event);
};
return ThreadResponseShowView;
-
})(DiscussionContentShowView);
}
-
}).call(window);
diff --git a/common/static/common/js/discussion/views/thread_response_view.js b/common/static/common/js/discussion/views/thread_response_view.js
index e93a25225c..41ed8691a7 100644
--- a/common/static/common/js/discussion/views/thread_response_view.js
+++ b/common/static/common/js/discussion/views/thread_response_view.js
@@ -21,9 +21,8 @@
return child;
};
- if (typeof Backbone !== "undefined" && Backbone !== null) {
+ if (typeof Backbone !== 'undefined' && Backbone !== null) {
this.ThreadResponseView = (function(_super) {
-
__extends(ThreadResponseView, _super);
function ThreadResponseView() {
@@ -46,13 +45,13 @@
return ThreadResponseView.__super__.constructor.apply(this, arguments);
}
- ThreadResponseView.prototype.tagName = "li";
+ ThreadResponseView.prototype.tagName = 'li';
- ThreadResponseView.prototype.className = "forum-response";
+ ThreadResponseView.prototype.className = 'forum-response';
ThreadResponseView.prototype.events = {
- "click .discussion-submit-comment": "submitComment",
- "focus .wmd-input": "showEditorChrome"
+ 'click .discussion-submit-comment': 'submitComment',
+ 'focus .wmd-input': 'showEditorChrome'
};
ThreadResponseView.prototype.$ = function(selector) {
@@ -67,26 +66,26 @@
ThreadResponseView.prototype.renderTemplate = function() {
var container, templateData, _ref;
- this.template = _.template($("#thread-response-template").html());
- container = $("#discussion-container");
+ this.template = _.template($('#thread-response-template').html());
+ container = $('#discussion-container');
if (!container.length) {
- container = $(".discussion-module");
+ container = $('.discussion-module');
}
templateData = _.extend(this.model.toJSON(), {
wmdId: (_ref = this.model.id) !== null ? _ref : (new Date()).getTime(),
- create_sub_comment: container.data("user-create-subcomment"),
+ create_sub_comment: container.data('user-create-subcomment'),
readOnly: this.readOnly
});
return this.template(templateData);
};
ThreadResponseView.prototype.render = function() {
- this.$el.addClass("response_" + this.model.get("id"));
+ this.$el.addClass('response_' + this.model.get('id'));
this.$el.html(this.renderTemplate());
this.delegateEvents();
this.renderShowView();
this.renderAttrs();
- if (this.model.get("thread").get("closed")) {
+ if (this.model.get('thread').get('closed')) {
this.hideCommentForm();
}
this.renderComments();
@@ -94,7 +93,7 @@
};
ThreadResponseView.prototype.afterInsert = function() {
- this.makeWmdEditor("comment-body");
+ this.makeWmdEditor('comment-body');
return this.hideEditorChrome();
};
@@ -140,14 +139,14 @@
return self.renderComment(comment, false, null);
});
if (this.collapseComments && comments.length) {
- this.$(".comments").hide();
- return this.$(".action-show-comments").on("click", function(event) {
+ this.$('.comments').hide();
+ return this.$('.action-show-comments').on('click', function(event) {
event.preventDefault();
- self.$(".action-show-comments").hide();
- return self.$(".comments").show();
+ self.$('.action-show-comments').hide();
+ return self.$('.comments').show();
});
} else {
- return this.$(".action-show-comments").hide();
+ return this.$('.action-show-comments').hide();
}
};
@@ -162,16 +161,16 @@
if (this.readOnly) {
this.$el.find('.comments').append(view.el);
} else {
- this.$el.find(".comments .new-comment").before(view.el);
+ this.$el.find('.comments .new-comment').before(view.el);
}
- view.bind("comment:edit", function(event) {
+ view.bind('comment:edit', function(event) {
if (self.editView) {
self.cancelEdit(event);
}
self.cancelCommentEdits();
return self.hideCommentForm();
});
- view.bind("comment:cancel_edit", function() {
+ view.bind('comment:cancel_edit', function() {
return self.showCommentForm();
});
this.commentViews.push(view);
@@ -182,26 +181,26 @@
var body, comment, url, view;
event.preventDefault();
url = this.model.urlFor('reply');
- body = this.getWmdContent("comment-body");
+ body = this.getWmdContent('comment-body');
if (!body.trim().length) {
return;
}
- this.setWmdContent("comment-body", "");
+ this.setWmdContent('comment-body', '');
comment = new Comment({
body: body,
created_at: (new Date()).toISOString(),
- username: window.user.get("username"),
+ username: window.user.get('username'),
abuse_flaggers: [],
- user_id: window.user.get("id"),
- id: "unsaved"
+ user_id: window.user.get('id'),
+ id: 'unsaved'
});
view = this.renderComment(comment);
this.hideEditorChrome();
- this.trigger("comment:add", comment);
+ this.trigger('comment:add', comment);
return DiscussionUtil.safeAjax({
$elem: $(event.target),
url: url,
- type: "POST",
+ type: 'POST',
dataType: 'json',
data: {
body: body
@@ -220,7 +219,7 @@
if (!this.model.can('can_delete')) {
return;
}
- if (!confirm(gettext("Are you sure you want to delete this response?"))) {
+ if (!confirm(gettext('Are you sure you want to delete this response?'))) {
return;
}
url = this.model.urlFor('_delete');
@@ -230,7 +229,7 @@
return DiscussionUtil.safeAjax({
$elem: $elem,
url: url,
- type: "POST"
+ type: 'POST'
});
};
@@ -244,8 +243,8 @@
this.editView = new ThreadResponseEditView({
model: this.model
});
- this.editView.bind("response:update", this.update);
- return this.editView.bind("response:cancel_edit", this.cancelEdit);
+ this.editView.bind('response:update', this.update);
+ return this.editView.bind('response:cancel_edit', this.cancelEdit);
}
};
@@ -285,10 +284,10 @@
this.showView = new ThreadResponseShowView({
model: this.model
});
- this.showView.bind("response:_delete", this._delete);
- this.showView.bind("response:edit", this.edit);
- return this.showView.on("comment:endorse", function() {
- return self.trigger("comment:endorse");
+ this.showView.bind('response:_delete', this._delete);
+ this.showView.bind('response:edit', this.edit);
+ return this.showView.on('comment:endorse', function() {
+ return self.trigger('comment:endorse');
});
}
};
@@ -314,21 +313,21 @@
ThreadResponseView.prototype.update = function(event) {
var newBody, url,
self = this;
- newBody = this.editView.$(".edit-post-body textarea").val();
+ newBody = this.editView.$('.edit-post-body textarea').val();
url = DiscussionUtil.urlFor('update_comment', this.model.id);
return DiscussionUtil.safeAjax({
$elem: $(event.target),
$loading: event ? $(event.target) : void 0,
url: url,
- type: "POST",
+ type: 'POST',
dataType: 'json',
data: {
body: newBody
},
- error: DiscussionUtil.formErrorHandler(this.$(".edit-post-form-errors")),
+ error: DiscussionUtil.formErrorHandler(this.$('.edit-post-form-errors')),
success: function() {
- self.editView.$(".edit-post-body textarea").val("").attr("prev-text", "");
- self.editView.$(".wmd-preview p").html("");
+ self.editView.$('.edit-post-body textarea').val('').attr('prev-text', '');
+ self.editView.$('.wmd-preview p').html('');
self.model.set({
body: newBody
});
@@ -340,8 +339,6 @@
};
return ThreadResponseView;
-
})(DiscussionContentView);
}
-
}).call(window);
diff --git a/common/static/common/js/jasmine.common.conf.js b/common/static/common/js/jasmine.common.conf.js
index e5b7a84927..9688e1de86 100644
--- a/common/static/common/js/jasmine.common.conf.js
+++ b/common/static/common/js/jasmine.common.conf.js
@@ -7,5 +7,5 @@ jasmine.getFixtures().fixturesPath = '/base/';
// https://github.com/edx/js-test-tool/blob/master/js_test_tool/templates/jasmine_test_runner.html#L10
// Stub out modal dialog alerts, which will prevent
// us from accessing the test results in the DOM
-window.confirm = function(){return true;};
-window.alert = function(){return;};
+window.confirm = function() { return true; };
+window.alert = function() { return; };
diff --git a/common/static/common/js/jasmine_stack_trace.js b/common/static/common/js/jasmine_stack_trace.js
index 7728fcfe09..98318e4cb0 100644
--- a/common/static/common/js/jasmine_stack_trace.js
+++ b/common/static/common/js/jasmine_stack_trace.js
@@ -1,7 +1,7 @@
/* This file overrides ExceptionFormatter of jasmine before it's initialization in karma-jasmine's
boot.js. It's important because ExceptionFormatter returns a constructor function. Once the method has been
initialized we can't override the ExceptionFormatter as Jasmine then uses the stored reference to the function */
-(function () {
+(function() {
/* globals jasmineRequire */
'use strict';
@@ -9,10 +9,10 @@
oldExceptionFormatter = new OldExceptionFormatter(),
MAX_STACK_TRACE_LINES = 10;
- jasmineRequire.ExceptionFormatter = function () {
+ jasmineRequire.ExceptionFormatter = function() {
function ExceptionFormatter() {
this.message = oldExceptionFormatter.message;
- this.stack = function (error) {
+ this.stack = function(error) {
var errorMsg = null;
if (error) {
diff --git a/common/static/common/js/karma.common.conf.js b/common/static/common/js/karma.common.conf.js
index c4539221c4..ee9359fcd5 100644
--- a/common/static/common/js/karma.common.conf.js
+++ b/common/static/common/js/karma.common.conf.js
@@ -167,7 +167,7 @@ function junitSettings(config) {
* @param {String} pattern
* @return {String}
*/
-var defaultNormalizeFunc = function (appRoot, pattern) {
+var defaultNormalizeFunc = function(appRoot, pattern) {
if (pattern.match(/^common\/js/)) {
pattern = path.join(appRoot, '/common/static/' + pattern);
} else if (pattern.match(/^xmodule_js\/common_static/)) {
@@ -181,7 +181,7 @@ var normalizePathsForCoverage = function(files, normalizeFunc) {
var normalizeFn = normalizeFunc || defaultNormalizeFunc,
filesForCoverage = {};
- files.forEach(function (file) {
+ files.forEach(function(file) {
if (!file.ignoreCoverage) {
filesForCoverage[normalizeFn(appRoot, file.pattern)] = ['coverage'];
}
@@ -196,8 +196,8 @@ var normalizePathsForCoverage = function(files, normalizeFunc) {
* @param {Bool} enable
* @return {Object}
*/
-var setNocache = function (files, enable) {
- files.forEach(function (f) {
+var setNocache = function(files, enable) {
+ files.forEach(function(f) {
if (_.isObject(f)) {
f.nocache = enable;
}
@@ -210,8 +210,8 @@ var setNocache = function (files, enable) {
* @param {Object} files
* @return {Object}
*/
-var setDefaults = function (files) {
- return files.map(function (f) {
+var setDefaults = function(files) {
+ return files.map(function(f) {
var file = _.isObject(f) ? f : {pattern: f};
if (!file.included) {
f.included = false;
@@ -220,9 +220,8 @@ var setDefaults = function (files) {
});
};
-var getBaseConfig = function (config, useRequireJs) {
-
- var getFrameworkFiles = function () {
+var getBaseConfig = function(config, useRequireJs) {
+ var getFrameworkFiles = function() {
var files = [
'node_modules/jquery/dist/jquery.js',
'node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
@@ -248,8 +247,8 @@ var getBaseConfig = function (config, useRequireJs) {
// which isn't a karma plugin. Though a karma framework for jasmine-jquery is available
// but it's not actively maintained. In future we also wanna add jQuery at the top when
// we upgrade to jQuery 2
- var initFrameworks = function (files) {
- getFrameworkFiles().reverse().forEach(function (f) {
+ var initFrameworks = function(files) {
+ getFrameworkFiles().reverse().forEach(function(f) {
files.unshift({
pattern: path.join(appRoot, f),
included: true,
@@ -359,7 +358,7 @@ var configure = function(config, options) {
baseConfig = getBaseConfig(config, useRequireJs);
if (options.includeCommonFiles) {
- _.forEach(['libraryFiles', 'sourceFiles', 'specFiles', 'fixtureFiles'], function (collectionName) {
+ _.forEach(['libraryFiles', 'sourceFiles', 'specFiles', 'fixtureFiles'], function(collectionName) {
options[collectionName] = _.flatten([commonFiles[collectionName], options[collectionName]]);
});
}
diff --git a/common/static/common/js/spec/components/feedback_spec.js b/common/static/common/js/spec/components/feedback_spec.js
index 9f61a36d7d..e3c0139dbb 100644
--- a/common/static/common/js/spec/components/feedback_spec.js
+++ b/common/static/common/js/spec/components/feedback_spec.js
@@ -1,399 +1,398 @@
// Generated by CoffeeScript 1.6.1
(function() {
- 'use strict';
- define(["jquery", "common/js/components/views/feedback", "common/js/components/views/feedback_notification",
- "common/js/components/views/feedback_alert", "common/js/components/views/feedback_prompt",
- 'common/js/spec_helpers/view_helpers', "sinon", "jquery.simulate"],
+ 'use strict';
+ define(['jquery', 'common/js/components/views/feedback', 'common/js/components/views/feedback_notification',
+ 'common/js/components/views/feedback_alert', 'common/js/components/views/feedback_prompt',
+ 'common/js/spec_helpers/view_helpers', 'sinon', 'jquery.simulate'],
function($, SystemFeedback, NotificationView, AlertView, PromptView, ViewHelpers, sinon) {
- var tpl;
- tpl = readFixtures('common/templates/components/system-feedback.underscore');
+ var tpl;
+ tpl = readFixtures('common/templates/components/system-feedback.underscore');
- var isFocused = function(actual) {
- return $(actual)[0] === $(actual)[0].ownerDocument.activeElement;
- };
+ var isFocused = function(actual) {
+ return $(actual)[0] === $(actual)[0].ownerDocument.activeElement;
+ };
- beforeEach(function() {
- setFixtures(sandbox({
- id: "page-alert"
- }));
- appendSetFixtures(sandbox({
- id: "page-notification"
- }));
- appendSetFixtures(sandbox({
- id: "page-prompt"
- }));
- appendSetFixtures($(""); // eslint-disable-line max-len
this.threads = [
DiscussionViewSpecHelper.makeThreadWithProps({
- id: "1",
- title: "Thread1",
+ id: '1',
+ title: 'Thread1',
votes: {
up_count: '20'
},
@@ -24,24 +24,24 @@
comments_count: 1,
created_at: '2013-04-03T20:08:39Z'
}), DiscussionViewSpecHelper.makeThreadWithProps({
- id: "2",
- title: "Thread2",
+ id: '2',
+ title: 'Thread2',
votes: {
up_count: '42'
},
comments_count: 2,
created_at: '2013-04-03T20:07:39Z'
}), DiscussionViewSpecHelper.makeThreadWithProps({
- id: "3",
- title: "Thread3",
+ id: '3',
+ title: 'Thread3',
votes: {
up_count: '12'
},
comments_count: 3,
created_at: '2013-04-03T20:06:39Z'
}), DiscussionViewSpecHelper.makeThreadWithProps({
- id: "4",
- title: "Thread4",
+ id: '4',
+ title: 'Thread4',
votes: {
up_count: '25'
},
@@ -51,11 +51,11 @@
})
];
deferred = $.Deferred();
- spyOn($, "ajax").and.returnValue(deferred);
+ spyOn($, 'ajax').and.returnValue(deferred);
this.discussion = new Discussion([]);
this.view = new DiscussionThreadListView({
collection: this.discussion,
- el: $("#fixture-element"),
+ el: $('#fixture-element'),
courseSettings: new DiscussionCourseSettings({
is_cohorted: true
})
@@ -83,7 +83,7 @@
};
makeView = function(discussion) {
return new DiscussionThreadListView({
- el: $("#fixture-element"),
+ el: $('#fixture-element'),
collection: discussion,
courseSettings: new DiscussionCourseSettings({
is_cohorted: true
@@ -92,7 +92,7 @@
};
expectFilter = function(filterVal) {
return $.ajax.and.callFake(function(params) {
- _.each(["unread", "unanswered", "flagged"], function(paramName) {
+ _.each(['unread', 'unanswered', 'flagged'], function(paramName) {
if (paramName === filterVal) {
return expect(params.data[paramName]).toEqual(true);
} else {
@@ -106,21 +106,21 @@
});
};
- describe("should filter correctly", function() {
- return _.each(["all", "unread", "unanswered", "flagged"], function(filterVal) {
- it("for " + filterVal, function() {
+ describe('should filter correctly', function() {
+ return _.each(['all', 'unread', 'unanswered', 'flagged'], function(filterVal) {
+ it('for ' + filterVal, function() {
expectFilter(filterVal);
- this.view.$(".forum-nav-filter-main-control").val(filterVal).change();
+ this.view.$('.forum-nav-filter-main-control').val(filterVal).change();
return expect($.ajax).toHaveBeenCalled();
});
});
});
- describe("cohort selector", function() {
- it("should not be visible to students", function() {
- return expect(this.view.$(".forum-nav-filter-cohort-control:visible")).not.toExist();
+ describe('cohort selector', function() {
+ it('should not be visible to students', function() {
+ return expect(this.view.$('.forum-nav-filter-cohort-control:visible')).not.toExist();
});
- it("should allow moderators to select visibility", function() {
+ it('should allow moderators to select visibility', function() {
var expectedGroupId,
self = this;
DiscussionSpecHelper.makeModerator();
@@ -131,45 +131,45 @@
});
return _.each([
{
- val: "",
+ val: '',
expectedGroupId: void 0
}, {
- val: "1",
- expectedGroupId: "1"
+ val: '1',
+ expectedGroupId: '1'
}, {
- val: "2",
- expectedGroupId: "2"
+ val: '2',
+ expectedGroupId: '2'
}
], function(optionInfo) {
expectedGroupId = optionInfo.expectedGroupId;
- self.view.$(".forum-nav-filter-cohort-control").val(optionInfo.val).change();
+ self.view.$('.forum-nav-filter-cohort-control').val(optionInfo.val).change();
expect($.ajax).toHaveBeenCalled();
return $.ajax.calls.reset();
});
});
});
- it("search should clear filter", function() {
+ it('search should clear filter', function() {
expectFilter(null);
- this.view.$(".forum-nav-filter-main-control").val("flagged");
- this.view.searchFor("foobar");
- return expect(this.view.$(".forum-nav-filter-main-control").val()).toEqual("all");
+ this.view.$('.forum-nav-filter-main-control').val('flagged');
+ this.view.searchFor('foobar');
+ return expect(this.view.$('.forum-nav-filter-main-control').val()).toEqual('all');
});
checkThreadsOrdering = function(view, sort_order, type) {
- expect(view.$el.find(".forum-nav-thread").children().length).toEqual(4);
- expect(view.$el.find(".forum-nav-thread:nth-child(1) .forum-nav-thread-title").text())
+ expect(view.$el.find('.forum-nav-thread').children().length).toEqual(4);
+ expect(view.$el.find('.forum-nav-thread:nth-child(1) .forum-nav-thread-title').text())
.toEqual(sort_order[0]);
- expect(view.$el.find(".forum-nav-thread:nth-child(2) .forum-nav-thread-title").text())
+ expect(view.$el.find('.forum-nav-thread:nth-child(2) .forum-nav-thread-title').text())
.toEqual(sort_order[1]);
- expect(view.$el.find(".forum-nav-thread:nth-child(3) .forum-nav-thread-title").text())
+ expect(view.$el.find('.forum-nav-thread:nth-child(3) .forum-nav-thread-title').text())
.toEqual(sort_order[2]);
- expect(view.$el.find(".forum-nav-thread:nth-child(4) .forum-nav-thread-title").text())
+ expect(view.$el.find('.forum-nav-thread:nth-child(4) .forum-nav-thread-title').text())
.toEqual(sort_order[3]);
- return expect(view.$el.find(".forum-nav-sort-control").val()).toEqual(type);
+ return expect(view.$el.find('.forum-nav-sort-control').val()).toEqual(type);
};
- describe("thread rendering should be correct", function() {
+ describe('thread rendering should be correct', function() {
var checkRender;
checkRender = function(threads, type, sort_order) {
var discussion, view;
@@ -182,31 +182,31 @@
view = makeView(discussion);
view.render();
checkThreadsOrdering(view, sort_order, type);
- expect(view.$el.find(".forum-nav-thread-comments-count:visible").length)
- .toEqual(type === "votes" ? 0 : 4);
- expect(view.$el.find(".forum-nav-thread-votes-count:visible").length)
- .toEqual(type === "votes" ? 4 : 0);
- if (type === "votes") {
- return expect(_.map(view.$el.find(".forum-nav-thread-votes-count"), function(element) {
+ expect(view.$el.find('.forum-nav-thread-comments-count:visible').length)
+ .toEqual(type === 'votes' ? 0 : 4);
+ expect(view.$el.find('.forum-nav-thread-votes-count:visible').length)
+ .toEqual(type === 'votes' ? 4 : 0);
+ if (type === 'votes') {
+ return expect(_.map(view.$el.find('.forum-nav-thread-votes-count'), function(element) {
return $(element).text().trim();
- })).toEqual(["+25 votes", "+20 votes", "+42 votes", "+12 votes"]);
+ })).toEqual(['+25 votes', '+20 votes', '+42 votes', '+12 votes']);
}
};
- it("with sort preference activity", function() {
- return checkRender(this.threads, "activity", ["Thread1", "Thread2", "Thread3", "Thread4"]);
+ it('with sort preference activity', function() {
+ return checkRender(this.threads, 'activity', ['Thread1', 'Thread2', 'Thread3', 'Thread4']);
});
- it("with sort preference votes", function() {
- return checkRender(this.threads, "votes", ["Thread4", "Thread1", "Thread2", "Thread3"]);
+ it('with sort preference votes', function() {
+ return checkRender(this.threads, 'votes', ['Thread4', 'Thread1', 'Thread2', 'Thread3']);
});
- it("with sort preference comments", function() {
- return checkRender(this.threads, "comments", ["Thread1", "Thread4", "Thread3", "Thread2"]);
+ it('with sort preference comments', function() {
+ return checkRender(this.threads, 'comments', ['Thread1', 'Thread4', 'Thread3', 'Thread2']);
});
});
- describe("Sort change should be correct", function() {
+ describe('Sort change should be correct', function() {
var changeSorting;
changeSorting = function(threads, selected_type, new_type, sort_order) {
var discussion, sortControl, sorted_threads, view;
@@ -218,7 +218,7 @@
});
view = makeView(discussion);
view.render();
- sortControl = view.$el.find(".forum-nav-sort-control");
+ sortControl = view.$el.find('.forum-nav-sort-control');
expect(sortControl.val()).toEqual(selected_type);
sorted_threads = [];
if (new_type === 'activity') {
@@ -230,7 +230,7 @@
}
$.ajax.and.callFake(function(params) {
params.success({
- "discussion_data": sorted_threads,
+ 'discussion_data': sorted_threads,
page: 1,
num_pages: 1
});
@@ -244,31 +244,31 @@
checkThreadsOrdering(view, sort_order, new_type);
};
- it("with sort preference activity", function() {
+ it('with sort preference activity', function() {
changeSorting(
- this.threads, "comments", "activity", ["Thread1", "Thread4", "Thread3", "Thread2"]
+ this.threads, 'comments', 'activity', ['Thread1', 'Thread4', 'Thread3', 'Thread2']
);
});
- it("with sort preference votes", function() {
- changeSorting(this.threads, "activity", "votes", ["Thread4", "Thread1", "Thread2", "Thread3"]);
+ it('with sort preference votes', function() {
+ changeSorting(this.threads, 'activity', 'votes', ['Thread4', 'Thread1', 'Thread2', 'Thread3']);
});
- it("with sort preference comments", function() {
- changeSorting(this.threads, "votes", "comments", ["Thread1", "Thread4", "Thread3", "Thread2"]);
+ it('with sort preference comments', function() {
+ changeSorting(this.threads, 'votes', 'comments', ['Thread1', 'Thread4', 'Thread3', 'Thread2']);
});
});
- describe("search alerts", function() {
+ describe('search alerts', function() {
var testAlertMessages, getAlertMessagesAndClasses;
testAlertMessages = function(expectedMessages) {
- return expect($(".search-alert .message").map(function() {
+ return expect($('.search-alert .message').map(function() {
return $(this).html();
}).get()).toEqual(expectedMessages);
};
getAlertMessagesAndClasses = function() {
- return $(".search-alert").map(function() {
+ return $('.search-alert').map(function() {
return {
text: $('.message', this).html(),
css_class: $(this).attr('class')
@@ -276,59 +276,59 @@
}).get();
};
- it("renders and removes search alerts", function() {
+ it('renders and removes search alerts', function() {
var bar, foo;
testAlertMessages([]);
- foo = this.view.addSearchAlert("foo");
- testAlertMessages(["foo"]);
- bar = this.view.addSearchAlert("bar");
- testAlertMessages(["foo", "bar"]);
+ foo = this.view.addSearchAlert('foo');
+ testAlertMessages(['foo']);
+ bar = this.view.addSearchAlert('bar');
+ testAlertMessages(['foo', 'bar']);
this.view.removeSearchAlert(foo.cid);
- testAlertMessages(["bar"]);
+ testAlertMessages(['bar']);
this.view.removeSearchAlert(bar.cid);
return testAlertMessages([]);
});
- it("renders search alert with custom class", function() {
+ it('renders search alert with custom class', function() {
var foo, messages;
testAlertMessages([]);
- this.view.addSearchAlert("foo", "custom-class");
+ this.view.addSearchAlert('foo', 'custom-class');
messages = getAlertMessagesAndClasses();
expect(messages.length).toEqual(1);
- expect(messages[0].text).toEqual("foo");
- expect(messages[0].css_class).toEqual("search-alert custom-class");
+ expect(messages[0].text).toEqual('foo');
+ expect(messages[0].css_class).toEqual('search-alert custom-class');
- foo = this.view.addSearchAlert("bar", "other-class");
+ foo = this.view.addSearchAlert('bar', 'other-class');
messages = getAlertMessagesAndClasses();
expect(messages.length).toEqual(2);
- expect(messages[0].text).toEqual("foo");
- expect(messages[0].css_class).toEqual("search-alert custom-class");
- expect(messages[1].text).toEqual("bar");
- expect(messages[1].css_class).toEqual("search-alert other-class");
+ expect(messages[0].text).toEqual('foo');
+ expect(messages[0].css_class).toEqual('search-alert custom-class');
+ expect(messages[1].text).toEqual('bar');
+ expect(messages[1].css_class).toEqual('search-alert other-class');
});
- it("clears all search alerts", function() {
- this.view.addSearchAlert("foo");
- this.view.addSearchAlert("bar");
- this.view.addSearchAlert("baz");
- testAlertMessages(["foo", "bar", "baz"]);
+ it('clears all search alerts', function() {
+ this.view.addSearchAlert('foo');
+ this.view.addSearchAlert('bar');
+ this.view.addSearchAlert('baz');
+ testAlertMessages(['foo', 'bar', 'baz']);
this.view.clearSearchAlerts();
return testAlertMessages([]);
});
});
- describe("search spell correction", function() {
+ describe('search spell correction', function() {
var testCorrection;
beforeEach(function() {
- return spyOn(this.view, "searchForUser");
+ return spyOn(this.view, 'searchForUser');
});
testCorrection = function(view, correctedText) {
- spyOn(view, "addSearchAlert");
+ spyOn(view, 'addSearchAlert');
$.ajax.and.callFake(function(params) {
params.success({
discussion_data: [],
@@ -341,64 +341,64 @@
}
};
});
- view.searchFor("dummy");
+ view.searchFor('dummy');
return expect($.ajax).toHaveBeenCalled();
};
- it("adds a search alert when an alternate term was searched", function() {
- testCorrection(this.view, "foo");
+ it('adds a search alert when an alternate term was searched', function() {
+ testCorrection(this.view, 'foo');
expect(this.view.addSearchAlert.calls.count()).toEqual(1);
return expect(this.view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/foo/);
});
- it("does not add a search alert when no alternate term was searched", function() {
+ it('does not add a search alert when no alternate term was searched', function() {
testCorrection(this.view, null);
expect(this.view.addSearchAlert.calls.count()).toEqual(1);
return expect(this.view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/no threads matched/i);
});
- it("clears search alerts when a new search is performed", function() {
- spyOn(this.view, "clearSearchAlerts");
- spyOn(DiscussionUtil, "safeAjax");
- this.view.searchFor("dummy");
+ it('clears search alerts when a new search is performed', function() {
+ spyOn(this.view, 'clearSearchAlerts');
+ spyOn(DiscussionUtil, 'safeAjax');
+ this.view.searchFor('dummy');
return expect(this.view.clearSearchAlerts).toHaveBeenCalled();
});
- it("clears search alerts when the underlying collection changes", function() {
- spyOn(this.view, "clearSearchAlerts");
- spyOn(this.view, "renderThread");
- this.view.collection.trigger("change", new Thread({
+ it('clears search alerts when the underlying collection changes', function() {
+ spyOn(this.view, 'clearSearchAlerts');
+ spyOn(this.view, 'renderThread');
+ this.view.collection.trigger('change', new Thread({
id: 1
}));
return expect(this.view.clearSearchAlerts).toHaveBeenCalled();
});
});
- describe("Search events", function() {
- it("perform search when enter pressed inside search textfield", function() {
+ describe('Search events', function() {
+ it('perform search when enter pressed inside search textfield', function() {
setupAjax();
- spyOn(this.view, "searchFor");
- this.view.$el.find(".forum-nav-search-input").trigger($.Event("keydown", {
+ spyOn(this.view, 'searchFor');
+ this.view.$el.find('.forum-nav-search-input').trigger($.Event('keydown', {
which: 13
}));
return expect(this.view.searchFor).toHaveBeenCalled();
});
- it("perform search when search icon is clicked", function() {
+ it('perform search when search icon is clicked', function() {
setupAjax();
- spyOn(this.view, "searchFor");
- this.view.$el.find(".fa-search").click();
+ spyOn(this.view, 'searchFor');
+ this.view.$el.find('.fa-search').click();
return expect(this.view.searchFor).toHaveBeenCalled();
});
});
- describe("username search", function() {
+ describe('username search', function() {
var setAjaxResults;
- it("makes correct ajax calls", function() {
+ it('makes correct ajax calls', function() {
$.ajax.and.callFake(function(params) {
- expect(params.data.username).toEqual("testing-username");
- expect(params.url.path()).toEqual(DiscussionUtil.urlFor("users"));
+ expect(params.data.username).toEqual('testing-username');
+ expect(params.url.path()).toEqual(DiscussionUtil.urlFor('users'));
params.success({
users: []
}, 'success');
@@ -407,7 +407,7 @@
}
};
});
- this.view.searchForUser("testing-username");
+ this.view.searchForUser('testing-username');
return expect($.ajax).toHaveBeenCalled();
});
@@ -418,12 +418,12 @@
discussion_data: [],
page: 42,
num_pages: 99,
- corrected_text: "dummy"
- }, "success");
+ corrected_text: 'dummy'
+ }, 'success');
} else if (params.data.username) {
params.success({
users: userResult
- }, "success");
+ }, 'success');
}
return {
always: function() {
@@ -432,289 +432,289 @@
});
};
- it("gets called after a thread search succeeds", function() {
- spyOn(this.view, "searchForUser").and.callThrough();
+ it('gets called after a thread search succeeds', function() {
+ spyOn(this.view, 'searchForUser').and.callThrough();
setAjaxResults(true, []);
- this.view.searchFor("gizmo");
+ this.view.searchFor('gizmo');
expect(this.view.searchForUser).toHaveBeenCalled();
- return expect($.ajax.calls.mostRecent().args[0].data.username).toEqual("gizmo");
+ return expect($.ajax.calls.mostRecent().args[0].data.username).toEqual('gizmo');
});
- it("does not get called after a thread search fails", function() {
- spyOn(this.view, "searchForUser").and.callThrough();
+ it('does not get called after a thread search fails', function() {
+ spyOn(this.view, 'searchForUser').and.callThrough();
setAjaxResults(false, []);
- this.view.searchFor("gizmo");
+ this.view.searchFor('gizmo');
return expect(this.view.searchForUser).not.toHaveBeenCalled();
});
- it("adds a search alert when an username was matched", function() {
- spyOn(this.view, "addSearchAlert");
+ it('adds a search alert when an username was matched', function() {
+ spyOn(this.view, 'addSearchAlert');
setAjaxResults(true, [
{
- username: "gizmo",
- id: "1"
+ username: 'gizmo',
+ id: '1'
}
]);
- this.view.searchForUser("dummy");
+ this.view.searchForUser('dummy');
expect($.ajax).toHaveBeenCalled();
expect(this.view.addSearchAlert).toHaveBeenCalled();
return expect(this.view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/gizmo/);
});
- it("does not add a search alert when no username was matched", function() {
- spyOn(this.view, "addSearchAlert");
+ it('does not add a search alert when no username was matched', function() {
+ spyOn(this.view, 'addSearchAlert');
setAjaxResults(true, []);
- this.view.searchForUser("dummy");
+ this.view.searchForUser('dummy');
expect($.ajax).toHaveBeenCalled();
return expect(this.view.addSearchAlert).not.toHaveBeenCalled();
});
});
- describe("post type renders correctly", function() {
- it("for discussion", function() {
+ describe('post type renders correctly', function() {
+ it('for discussion', function() {
renderSingleThreadWithProps({
- thread_type: "discussion"
+ thread_type: 'discussion'
});
- expect($(".forum-nav-thread-wrapper-0 .icon")).toHaveClass("fa-comments");
- return expect($(".forum-nav-thread-wrapper-0 .sr")).toHaveText("discussion");
+ expect($('.forum-nav-thread-wrapper-0 .icon')).toHaveClass('fa-comments');
+ return expect($('.forum-nav-thread-wrapper-0 .sr')).toHaveText('discussion');
});
- it("for answered question", function() {
+ it('for answered question', function() {
renderSingleThreadWithProps({
- thread_type: "question",
+ thread_type: 'question',
endorsed: true
});
- expect($(".forum-nav-thread-wrapper-0 .icon")).toHaveClass("fa-check-square-o");
- return expect($(".forum-nav-thread-wrapper-0 .sr")).toHaveText("answered question");
+ expect($('.forum-nav-thread-wrapper-0 .icon')).toHaveClass('fa-check-square-o');
+ return expect($('.forum-nav-thread-wrapper-0 .sr')).toHaveText('answered question');
});
- it("for unanswered question", function() {
+ it('for unanswered question', function() {
renderSingleThreadWithProps({
- thread_type: "question",
+ thread_type: 'question',
endorsed: false
});
- expect($(".forum-nav-thread-wrapper-0 .icon")).toHaveClass("fa-question");
- return expect($(".forum-nav-thread-wrapper-0 .sr")).toHaveText("unanswered question");
+ expect($('.forum-nav-thread-wrapper-0 .icon')).toHaveClass('fa-question');
+ return expect($('.forum-nav-thread-wrapper-0 .sr')).toHaveText('unanswered question');
});
});
- describe("post labels render correctly", function() {
+ describe('post labels render correctly', function() {
beforeEach(function() {
- this.moderatorId = "42";
- this.administratorId = "43";
- this.communityTaId = "44";
+ this.moderatorId = '42';
+ this.administratorId = '43';
+ this.communityTaId = '44';
return DiscussionUtil.loadRoles({
- "Moderator": [parseInt(this.moderatorId)],
- "Administrator": [parseInt(this.administratorId)],
- "Community TA": [parseInt(this.communityTaId)]
+ 'Moderator': [parseInt(this.moderatorId)],
+ 'Administrator': [parseInt(this.administratorId)],
+ 'Community TA': [parseInt(this.communityTaId)]
});
});
- it("for pinned", function() {
+ it('for pinned', function() {
renderSingleThreadWithProps({
pinned: true
});
- return expect($(".post-label-pinned").length).toEqual(1);
+ return expect($('.post-label-pinned').length).toEqual(1);
});
- it("for following", function() {
+ it('for following', function() {
renderSingleThreadWithProps({
subscribed: true
});
- return expect($(".post-label-following").length).toEqual(1);
+ return expect($('.post-label-following').length).toEqual(1);
});
- it("for moderator", function() {
+ it('for moderator', function() {
renderSingleThreadWithProps({
user_id: this.moderatorId
});
- return expect($(".post-label-by-staff").length).toEqual(1);
+ return expect($('.post-label-by-staff').length).toEqual(1);
});
- it("for administrator", function() {
+ it('for administrator', function() {
renderSingleThreadWithProps({
user_id: this.administratorId
});
- return expect($(".post-label-by-staff").length).toEqual(1);
+ return expect($('.post-label-by-staff').length).toEqual(1);
});
- it("for community TA", function() {
+ it('for community TA', function() {
renderSingleThreadWithProps({
user_id: this.communityTaId
});
- return expect($(".post-label-by-community-ta").length).toEqual(1);
+ return expect($('.post-label-by-community-ta').length).toEqual(1);
});
- it("when none should be present", function() {
+ it('when none should be present', function() {
renderSingleThreadWithProps({});
- return expect($(".forum-nav-thread-labels").length).toEqual(0);
+ return expect($('.forum-nav-thread-labels').length).toEqual(0);
});
});
- describe("browse menu", function() {
+ describe('browse menu', function() {
var expectBrowseMenuVisible;
afterEach(function() {
- return $("body").unbind("click");
+ return $('body').unbind('click');
});
expectBrowseMenuVisible = function(isVisible) {
- expect($(".forum-nav-browse-menu:visible").length).toEqual(isVisible ? 1 : 0);
- return expect($(".forum-nav-thread-list-wrapper:visible").length).toEqual(isVisible ? 0 : 1);
+ expect($('.forum-nav-browse-menu:visible').length).toEqual(isVisible ? 1 : 0);
+ return expect($('.forum-nav-thread-list-wrapper:visible').length).toEqual(isVisible ? 0 : 1);
};
- it("should not be visible by default", function() {
+ it('should not be visible by default', function() {
return expectBrowseMenuVisible(false);
});
- it("should show when header button is clicked", function() {
- $(".forum-nav-browse").click();
+ it('should show when header button is clicked', function() {
+ $('.forum-nav-browse').click();
return expectBrowseMenuVisible(true);
});
- describe("when shown", function() {
+ describe('when shown', function() {
beforeEach(function() {
- return $(".forum-nav-browse").click();
+ return $('.forum-nav-browse').click();
});
- it("should hide when header button is clicked", function() {
- $(".forum-nav-browse").click();
+ it('should hide when header button is clicked', function() {
+ $('.forum-nav-browse').click();
return expectBrowseMenuVisible(false);
});
- it("should hide when a click outside the menu occurs", function() {
- $(".forum-nav-search-input").click();
+ it('should hide when a click outside the menu occurs', function() {
+ $('.forum-nav-search-input').click();
return expectBrowseMenuVisible(false);
});
- it("should hide when a search is executed", function() {
+ it('should hide when a search is executed', function() {
setupAjax();
- $(".forum-nav-search-input").trigger($.Event("keydown", {
+ $('.forum-nav-search-input').trigger($.Event('keydown', {
which: 13
}));
return expectBrowseMenuVisible(false);
});
- it("should hide when a category is clicked", function() {
- $(".forum-nav-browse-title")[0].click();
+ it('should hide when a category is clicked', function() {
+ $('.forum-nav-browse-title')[0].click();
return expectBrowseMenuVisible(false);
});
- it("should still be shown when filter input is clicked", function() {
- $(".forum-nav-browse-filter-input").click();
+ it('should still be shown when filter input is clicked', function() {
+ $('.forum-nav-browse-filter-input').click();
return expectBrowseMenuVisible(true);
});
- describe("filtering", function() {
+ describe('filtering', function() {
var checkFilter;
checkFilter = function(filterText, expectedItems) {
var visibleItems;
- $(".forum-nav-browse-filter-input").val(filterText).keyup();
- visibleItems = $(".forum-nav-browse-title:visible").map(function(i, elem) {
+ $('.forum-nav-browse-filter-input').val(filterText).keyup();
+ visibleItems = $('.forum-nav-browse-title:visible').map(function(i, elem) {
return $(elem).text();
}).get();
return expect(visibleItems).toEqual(expectedItems);
};
- it("should be case-insensitive", function() {
- return checkFilter("other", ["Other Category"]);
+ it('should be case-insensitive', function() {
+ return checkFilter('other', ['Other Category']);
});
- it("should match partial words", function() {
- return checkFilter("ateg", ["Other Category"]);
+ it('should match partial words', function() {
+ return checkFilter('ateg', ['Other Category']);
});
- it("should show ancestors and descendants of matches", function() {
- return checkFilter("Target", ["Parent", "Target", "Child"]);
+ it('should show ancestors and descendants of matches', function() {
+ return checkFilter('Target', ['Parent', 'Target', 'Child']);
});
- it("should handle multiple words regardless of order", function() {
- return checkFilter("Following Posts", ["Posts I'm Following"]);
+ it('should handle multiple words regardless of order', function() {
+ return checkFilter('Following Posts', ["Posts I'm Following"]);
});
- it("should handle multiple words in different depths", function() {
- return checkFilter("Parent Child", ["Parent", "Target", "Child"]);
+ it('should handle multiple words in different depths', function() {
+ return checkFilter('Parent Child', ['Parent', 'Target', 'Child']);
});
});
});
- describe("selecting an item", function() {
+ describe('selecting an item', function() {
var testSelectionRequest;
- it("should clear the search box", function() {
+ it('should clear the search box', function() {
setupAjax();
- $(".forum-nav-search-input").val("foobar");
- $(".forum-nav-browse-menu-following .forum-nav-browse-title").click();
- return expect($(".forum-nav-search-input").val()).toEqual("");
+ $('.forum-nav-search-input').val('foobar');
+ $('.forum-nav-browse-menu-following .forum-nav-browse-title').click();
+ return expect($('.forum-nav-search-input').val()).toEqual('');
});
- it("should change the button text", function() {
+ it('should change the button text', function() {
setupAjax();
- $(".forum-nav-browse-menu-following .forum-nav-browse-title").click();
- return expect($(".forum-nav-browse-current").text()).toEqual("Posts I'm Following");
+ $('.forum-nav-browse-menu-following .forum-nav-browse-title').click();
+ return expect($('.forum-nav-browse-current').text()).toEqual("Posts I'm Following");
});
- it("should show/hide the cohort selector", function() {
+ it('should show/hide the cohort selector', function() {
var self = this;
DiscussionSpecHelper.makeModerator();
this.view.render();
setupAjax();
return _.each([
{
- selector: ".forum-nav-browse-menu-all",
+ selector: '.forum-nav-browse-menu-all',
cohortVisibility: true
}, {
- selector: ".forum-nav-browse-menu-following",
+ selector: '.forum-nav-browse-menu-following',
cohortVisibility: false
}, {
- selector: ".forum-nav-browse-menu-item:" +
- "has(.forum-nav-browse-menu-item .forum-nav-browse-menu-item)",
+ selector: '.forum-nav-browse-menu-item:' +
+ 'has(.forum-nav-browse-menu-item .forum-nav-browse-menu-item)',
cohortVisibility: false
}, {
- selector: "[data-discussion-id=child]",
+ selector: '[data-discussion-id=child]',
cohortVisibility: false
}, {
- selector: "[data-discussion-id=other]",
+ selector: '[data-discussion-id=other]',
cohortVisibility: true
}
], function(itemInfo) {
- self.view.$("" + itemInfo.selector + " > .forum-nav-browse-title").click();
- return expect(self.view.$(".forum-nav-filter-cohort").is(":visible"))
+ self.view.$('' + itemInfo.selector + ' > .forum-nav-browse-title').click();
+ return expect(self.view.$('.forum-nav-filter-cohort').is(':visible'))
.toEqual(itemInfo.cohortVisibility);
});
});
testSelectionRequest = function(callback, itemText) {
setupAjax(callback);
- $(".forum-nav-browse-title:contains(" + itemText + ")").click();
+ $('.forum-nav-browse-title:contains(' + itemText + ')').click();
return expect($.ajax).toHaveBeenCalled();
};
- it("should get all discussions", function() {
+ it('should get all discussions', function() {
return testSelectionRequest(function(params) {
- return expect(params.url.path()).toEqual(DiscussionUtil.urlFor("threads"));
- }, "All");
+ return expect(params.url.path()).toEqual(DiscussionUtil.urlFor('threads'));
+ }, 'All');
});
- it("should get followed threads", function() {
+ it('should get followed threads', function() {
testSelectionRequest(function(params) {
return expect(params.url.path())
- .toEqual(DiscussionUtil.urlFor("followed_threads", window.user.id));
- }, "Following");
+ .toEqual(DiscussionUtil.urlFor('followed_threads', window.user.id));
+ }, 'Following');
return expect($.ajax.calls.mostRecent().args[0].data.group_id).toBeUndefined();
});
- it("should get threads for the selected leaf", function() {
+ it('should get threads for the selected leaf', function() {
return testSelectionRequest(function(params) {
- expect(params.url.path()).toEqual(DiscussionUtil.urlFor("search"));
- return expect(params.data.commentable_ids).toEqual("child");
- }, "Child");
+ expect(params.url.path()).toEqual(DiscussionUtil.urlFor('search'));
+ return expect(params.data.commentable_ids).toEqual('child');
+ }, 'Child');
});
- it("should get threads for children of the selected intermediate node", function() {
+ it('should get threads for children of the selected intermediate node', function() {
return testSelectionRequest(function(params) {
- expect(params.url.path()).toEqual(DiscussionUtil.urlFor("search"));
- return expect(params.data.commentable_ids).toEqual("child,sibling");
- }, "Parent");
+ expect(params.url.path()).toEqual(DiscussionUtil.urlFor('search'));
+ return expect(params.data.commentable_ids).toEqual('child,sibling');
+ }, 'Parent');
});
});
});
diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js
index 12b9c5f0bb..14eebbc1cd 100644
--- a/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js
+++ b/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js
@@ -1,21 +1,21 @@
/* globals Discussion, DiscussionSpecHelper, DiscussionThreadProfileView, Thread */
(function() {
'use strict';
- describe("DiscussionThreadProfileView", function() {
+ describe('DiscussionThreadProfileView', function() {
var checkBody, checkPostWithImages, makeThread, makeView, spyConvertMath;
beforeEach(function() {
DiscussionSpecHelper.setUpGlobals();
DiscussionSpecHelper.setUnderscoreFixtures();
this.threadData = {
- id: "1",
- body: "dummy body",
+ id: '1',
+ body: 'dummy body',
discussion: new Discussion(),
abuse_flaggers: [],
commentable_id: 'dummy_discussion',
votes: {
- up_count: "42"
+ up_count: '42'
},
- created_at: "2014-09-09T20:11:08Z"
+ created_at: '2014-09-09T20:11:08Z'
};
this.imageTag = ' ';
window.MathJax = {
@@ -40,7 +40,7 @@
return thread;
};
spyConvertMath = function(view) {
- return spyOn(view, "convertMath").and.callFake(function() {
+ return spyOn(view, 'convertMath').and.callFake(function() {
return this.model.set('markdownBody', this.model.get('body'));
});
};
@@ -79,49 +79,49 @@
}
view = makeView(makeThread(threadData));
view.render();
- return expect(view.$el.find(".post-body").html()).toEqual(expectedHtml);
+ return expect(view.$el.find('.post-body').html()).toEqual(expectedHtml);
};
checkBody = function(truncated, view, threadData) {
var expectedOutput, inputHtmlStripped, outputHtmlStripped;
view.render();
if (!truncated) {
- expect(view.model.get("body")).toEqual(view.model.get("abbreviatedBody"));
- return expect(view.$el.find(".post-body").html()).toEqual(threadData.body);
+ expect(view.model.get('body')).toEqual(view.model.get('abbreviatedBody'));
+ return expect(view.$el.find('.post-body').html()).toEqual(threadData.body);
} else {
- expect(view.model.get("body")).not.toEqual(view.model.get("abbreviatedBody"));
- expect(view.$el.find(".post-body").html()).not.toEqual(threadData.body);
- outputHtmlStripped = view.$el.find(".post-body").html().replace(/(<([^>]+)>)/ig, "");
- outputHtmlStripped = outputHtmlStripped.replace("Some images in this post have been omitted", "");
- outputHtmlStripped = outputHtmlStripped.replace("image omitted", "");
- inputHtmlStripped = threadData.body.replace(/(<([^>]+)>)/ig, "");
+ expect(view.model.get('body')).not.toEqual(view.model.get('abbreviatedBody'));
+ expect(view.$el.find('.post-body').html()).not.toEqual(threadData.body);
+ outputHtmlStripped = view.$el.find('.post-body').html().replace(/(<([^>]+)>)/ig, '');
+ outputHtmlStripped = outputHtmlStripped.replace('Some images in this post have been omitted', '');
+ outputHtmlStripped = outputHtmlStripped.replace('image omitted', '');
+ inputHtmlStripped = threadData.body.replace(/(<([^>]+)>)/ig, '');
expectedOutput = inputHtmlStripped.substring(0, 139) + '…';
expect(outputHtmlStripped).toEqual(expectedOutput);
- return expect(view.$el.find(".post-body").html().indexOf("…")).toBeGreaterThan(0);
+ return expect(view.$el.find('.post-body').html().indexOf('…')).toBeGreaterThan(0);
}
};
- describe("Body markdown should be correct", function() {
+ describe('Body markdown should be correct', function() {
var numImages, truncatedText, _i, _j, _len, _len1, _ref, _ref1;
- it("untruncated text without markdown body", function() {
+ it('untruncated text without markdown body', function() {
var view;
- this.threadData.body = "Test body";
+ this.threadData.body = 'Test body';
view = makeView(makeThread(this.threadData));
return checkBody(false, view, this.threadData);
});
- it("truncated text without markdown body", function() {
+ it('truncated text without markdown body', function() {
var view;
- this.threadData.body = new Array(100).join("test ");
+ this.threadData.body = new Array(100).join('test ');
view = makeView(makeThread(this.threadData));
return checkBody(true, view, this.threadData);
});
- it("untruncated text with markdown body", function() {
+ it('untruncated text with markdown body', function() {
var view;
this.threadData.body = '' + this.imageTag + 'Google top search engine
';
view = makeView(makeThread(this.threadData));
return checkBody(false, view, this.threadData);
});
- it("truncated text with markdown body", function() {
+ it('truncated text with markdown body', function() {
var testText, view;
- testText = new Array(100).join("test ");
+ testText = new Array(100).join('test ');
this.threadData.body = '' + this.imageTag + this.imageTag + '' + testText + '
';
view = makeView(makeThread(this.threadData));
return checkBody(true, view, this.threadData);
@@ -133,8 +133,8 @@
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
truncatedText = _ref1[_j];
it(
- "body with " + numImages + " images and " + (truncatedText ? "truncated" : "untruncated") +
- " text",
+ 'body with ' + numImages + ' images and ' + (truncatedText ? 'truncated' : 'untruncated') +
+ ' text',
// eslint-disable no-loop-func
function() {
return checkPostWithImages(numImages, truncatedText, this.threadData, this.imageTag);
@@ -143,7 +143,7 @@
);
}
}
- it("check the thread retrieve url", function() {
+ it('check the thread retrieve url', function() {
var thread;
thread = makeThread(this.threadData);
return expect(thread.urlFor('retrieve'))
@@ -151,5 +151,4 @@
});
});
});
-
}).call(this);
diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_show_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_show_view_spec.js
index 7e9df2b269..71fd7df95b 100644
--- a/common/static/common/js/spec/discussion/view/discussion_thread_show_view_spec.js
+++ b/common/static/common/js/spec/discussion/view/discussion_thread_show_view_spec.js
@@ -2,67 +2,67 @@
(function() {
'use strict';
- var $$course_id = "$$course_id";
- describe("DiscussionThreadShowView", function() {
+ var $$course_id = '$$course_id';
+ describe('DiscussionThreadShowView', function() {
beforeEach(function() {
DiscussionSpecHelper.setUpGlobals();
DiscussionSpecHelper.setUnderscoreFixtures();
this.user = DiscussionUtil.getUser();
this.threadData = {
- id: "dummy",
+ id: 'dummy',
user_id: this.user.id,
username: this.user.get('username'),
course_id: $$course_id,
- title: "dummy title",
- body: "this is a thread",
- created_at: "2013-04-03T20:08:39Z",
+ title: 'dummy title',
+ body: 'this is a thread',
+ created_at: '2013-04-03T20:08:39Z',
abuse_flaggers: [],
votes: {
up_count: 42
},
- thread_type: "discussion",
+ thread_type: 'discussion',
closed: false,
pinned: false,
- type: "thread"
+ type: 'thread'
};
this.thread = new Thread(this.threadData);
this.view = new DiscussionThreadShowView({
model: this.thread
});
- this.view.setElement($("#fixture-element"));
- return spyOn(this.view, "convertMath");
+ this.view.setElement($('#fixture-element'));
+ return spyOn(this.view, 'convertMath');
});
- describe("voting", function() {
- it("renders the vote state correctly", function() {
+ describe('voting', function() {
+ it('renders the vote state correctly', function() {
return DiscussionViewSpecHelper.checkRenderVote(this.view, this.thread);
});
- it("votes correctly via click", function() {
- return DiscussionViewSpecHelper.checkUpvote(this.view, this.thread, this.user, $.Event("click"));
+ it('votes correctly via click', function() {
+ return DiscussionViewSpecHelper.checkUpvote(this.view, this.thread, this.user, $.Event('click'));
});
- it("votes correctly via spacebar", function() {
- return DiscussionViewSpecHelper.checkUpvote(this.view, this.thread, this.user, $.Event("keydown", {
+ it('votes correctly via spacebar', function() {
+ return DiscussionViewSpecHelper.checkUpvote(this.view, this.thread, this.user, $.Event('keydown', {
which: 32
}));
});
- it("unvotes correctly via click", function() {
- return DiscussionViewSpecHelper.checkUnvote(this.view, this.thread, this.user, $.Event("click"));
+ it('unvotes correctly via click', function() {
+ return DiscussionViewSpecHelper.checkUnvote(this.view, this.thread, this.user, $.Event('click'));
});
- it("unvotes correctly via spacebar", function() {
- return DiscussionViewSpecHelper.checkUnvote(this.view, this.thread, this.user, $.Event("keydown", {
+ it('unvotes correctly via spacebar', function() {
+ return DiscussionViewSpecHelper.checkUnvote(this.view, this.thread, this.user, $.Event('keydown', {
which: 32
}));
});
});
- describe("pinning", function() {
+ describe('pinning', function() {
var expectPinnedRendered;
expectPinnedRendered = function(view, model) {
var button, pinned;
pinned = model.get('pinned');
- button = view.$el.find(".action-pin");
- expect(button.hasClass("is-checked")).toBe(pinned);
- return expect(button.attr("aria-checked")).toEqual(pinned.toString());
+ button = view.$el.find('.action-pin');
+ expect(button.hasClass('is-checked')).toBe(pinned);
+ return expect(button.attr('aria-checked')).toEqual(pinned.toString());
};
- it("renders the pinned state correctly", function() {
+ it('renders the pinned state correctly', function() {
this.view.render();
expectPinnedRendered(this.view, this.thread);
this.thread.set('pinned', false);
@@ -72,41 +72,41 @@
this.view.render();
return expectPinnedRendered(this.view, this.thread);
});
- it("exposes the pinning control only to authorized users", function() {
+ it('exposes the pinning control only to authorized users', function() {
this.thread.updateInfo({
ability: {
can_openclose: false
}
});
this.view.render();
- expect(this.view.$el.find(".action-pin").closest(".is-hidden")).toExist();
+ expect(this.view.$el.find('.action-pin').closest('.is-hidden')).toExist();
this.thread.updateInfo({
ability: {
can_openclose: true
}
});
this.view.render();
- return expect(this.view.$el.find(".action-pin").closest(".is-hidden")).not.toExist();
+ return expect(this.view.$el.find('.action-pin').closest('.is-hidden')).not.toExist();
});
- it("handles events correctly", function() {
+ it('handles events correctly', function() {
this.view.render();
- return DiscussionViewSpecHelper.checkButtonEvents(this.view, "togglePin", ".action-pin");
+ return DiscussionViewSpecHelper.checkButtonEvents(this.view, 'togglePin', '.action-pin');
});
});
- describe("labels", function() {
+ describe('labels', function() {
var expectOneElement;
expectOneElement = function(view, selector, visible) {
var elements;
- if (typeof visible === "undefined" || visible === null) {
+ if (typeof visible === 'undefined' || visible === null) {
visible = true;
}
view.render();
elements = view.$el.find(selector);
expect(elements.length).toEqual(1);
if (visible) {
- return expect(elements).not.toHaveClass("is-hidden");
+ return expect(elements).not.toHaveClass('is-hidden');
} else {
- return expect(elements).toHaveClass("is-hidden");
+ return expect(elements).toHaveClass('is-hidden');
}
};
it('displays the closed label when appropriate', function() {
@@ -135,7 +135,7 @@
return expectOneElement(this.view, '.post-label-reported');
});
});
- describe("author display", function() {
+ describe('author display', function() {
var checkUserLink;
beforeEach(function() {
return this.thread.set('user_url', 'test_user_url');
@@ -147,24 +147,24 @@
expect(element.find('.user-label-community-ta').length).toEqual(is_ta ? 1 : 0);
return expect(element.find('.user-label-staff').length).toEqual(is_staff ? 1 : 0);
};
- it("renders correctly for a student-authored thread", function() {
+ it('renders correctly for a student-authored thread', function() {
var $el;
$el = $('#fixture-element').html(this.view.getAuthorDisplay());
return checkUserLink($el, false, false);
});
- it("renders correctly for a community TA-authored thread", function() {
+ it('renders correctly for a community TA-authored thread', function() {
var $el;
this.thread.set('community_ta_authored', true);
$el = $('#fixture-element').html(this.view.getAuthorDisplay());
return checkUserLink($el, true, false);
});
- it("renders correctly for a staff-authored thread", function() {
+ it('renders correctly for a staff-authored thread', function() {
var $el;
this.thread.set('staff_authored', true);
$el = $('#fixture-element').html(this.view.getAuthorDisplay());
return checkUserLink($el, false, true);
});
- it("renders correctly for an anonymously-authored thread", function() {
+ it('renders correctly for an anonymously-authored thread', function() {
var $el;
this.thread.set('username', null);
$el = $('#fixture-element').html(this.view.getAuthorDisplay());
@@ -172,13 +172,13 @@
return expect($el.text()).toMatch(/^(\s*)anonymous(\s*)$/);
});
});
- describe("cohorting", function() {
- it("renders correctly for an uncohorted thread", function() {
+ describe('cohorting', function() {
+ it('renders correctly for an uncohorted thread', function() {
this.view.render();
return expect(this.view.$('.group-visibility-label').text().trim())
.toEqual('This post is visible to everyone.');
});
- it("renders correctly for a cohorted thread", function() {
+ it('renders correctly for a cohorted thread', function() {
this.thread.set('group_id', '1');
this.thread.set('group_name', 'Mock Cohort');
this.view.render();
@@ -187,5 +187,4 @@
});
});
});
-
}).call(this);
diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js
index 167c79dd79..9b39017d54 100644
--- a/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js
+++ b/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js
@@ -4,7 +4,7 @@
*/
(function() {
'use strict';
- describe("DiscussionThreadView", function() {
+ describe('DiscussionThreadView', function() {
var assertContentVisible, assertExpandedContentVisible, assertResponseCountAndPaginationCorrect,
createAjaxResponseJson, createTestResponseJson, postResponse, renderWithContent, renderWithTestResponses;
beforeEach(function() {
@@ -16,12 +16,12 @@
this.thread = new Thread(this.threadData);
this.discussion = new Discussion(this.thread);
deferred = $.Deferred();
- spyOn($, "ajax").and.returnValue(deferred);
- spyOn(DiscussionThreadShowView.prototype, "convertMath");
- spyOn(DiscussionContentView.prototype, "makeWmdEditor");
- spyOn(DiscussionUtil, "makeWmdEditor");
- spyOn(DiscussionUtil, "setWmdContent");
- return spyOn(ThreadResponseShowView.prototype, "convertMath");
+ spyOn($, 'ajax').and.returnValue(deferred);
+ spyOn(DiscussionThreadShowView.prototype, 'convertMath');
+ spyOn(DiscussionContentView.prototype, 'makeWmdEditor');
+ spyOn(DiscussionUtil, 'makeWmdEditor');
+ spyOn(DiscussionUtil, 'setWmdContent');
+ return spyOn(ThreadResponseShowView.prototype, 'convertMath');
});
afterEach(function() {
$.ajax.calls.reset();
@@ -55,9 +55,9 @@
createTestResponseJson = function(index) {
return {
user_id: window.user.id,
- body: "Response " + index,
- id: "id_" + index,
- created_at: "2015-01-01T22:20:28Z"
+ body: 'Response ' + index,
+ id: 'id_' + index,
+ created_at: '2015-01-01T22:20:28Z'
};
};
assertContentVisible = function(view, selector, visible) {
@@ -65,26 +65,26 @@
content = view.$el.find(selector);
expect(content.length).toBeGreaterThan(0);
return content.each(function(i, elem) {
- return expect($(elem).is(":visible")).toEqual(visible);
+ return expect($(elem).is(':visible')).toEqual(visible);
});
};
assertExpandedContentVisible = function(view, expanded) {
- expect(view.$el.hasClass("expanded")).toEqual(expanded);
- assertContentVisible(view, ".post-extended-content", expanded);
- assertContentVisible(view, ".forum-thread-expand", !expanded);
- return assertContentVisible(view, ".forum-thread-collapse", expanded);
+ expect(view.$el.hasClass('expanded')).toEqual(expanded);
+ assertContentVisible(view, '.post-extended-content', expanded);
+ assertContentVisible(view, '.forum-thread-expand', !expanded);
+ return assertContentVisible(view, '.forum-thread-collapse', expanded);
};
assertResponseCountAndPaginationCorrect = function(view, countText, displayCountText, buttonText) {
- expect(view.$el.find(".response-count").text()).toEqual(countText);
+ expect(view.$el.find('.response-count').text()).toEqual(countText);
if (displayCountText) {
- expect(view.$el.find(".response-display-count").text()).toEqual(displayCountText);
+ expect(view.$el.find('.response-display-count').text()).toEqual(displayCountText);
} else {
- expect(view.$el.find(".response-display-count").length).toEqual(0);
+ expect(view.$el.find('.response-display-count').length).toEqual(0);
}
if (buttonText) {
- return expect(view.$el.find(".load-response-button").text()).toEqual(buttonText);
+ return expect(view.$el.find('.load-response-button').text()).toEqual(buttonText);
} else {
- return expect(view.$el.find(".load-response-button").length).toEqual(0);
+ return expect(view.$el.find('.load-response-button').length).toEqual(0);
}
};
createAjaxResponseJson = function(content, can_act) {
@@ -104,9 +104,9 @@
var responseText, testResponseJson;
testResponseJson = createTestResponseJson(index);
responseText = testResponseJson.body;
- spyOn(view, "getWmdContent").and.returnValue(responseText);
+ spyOn(view, 'getWmdContent').and.returnValue(responseText);
$.ajax.and.callFake(function(params) {
- expect(params.type).toEqual("POST");
+ expect(params.type).toEqual('POST');
expect(params.data.body).toEqual(responseText);
params.success(createAjaxResponseJson(testResponseJson, true), 'success');
return {
@@ -114,9 +114,9 @@
}
};
});
- return view.$(".discussion-submit-post").click();
+ return view.$('.discussion-submit-post').click();
};
- describe("closed and open Threads", function() {
+ describe('closed and open Threads', function() {
var checkCommentForm, checkVoteDisplay, createDiscussionThreadView;
createDiscussionThreadView = function(originallyClosed, mode) {
var discussion, thread, threadData, view;
@@ -127,15 +127,15 @@
discussion = new Discussion(thread);
view = new DiscussionThreadView({
model: thread,
- el: $("#fixture-element"),
+ el: $('#fixture-element'),
mode: mode,
course_settings: DiscussionSpecHelper.makeCourseSettings()
});
renderWithTestResponses(view, 1);
- if (mode === "inline") {
+ if (mode === 'inline') {
view.expand();
}
- spyOn(DiscussionUtil, "updateWithUndo").and.callFake(function(model, updates) {
+ spyOn(DiscussionUtil, 'updateWithUndo').and.callFake(function(model, updates) {
return model.set(updates);
});
return view;
@@ -143,161 +143,161 @@
checkCommentForm = function(originallyClosed, mode) {
var view;
view = createDiscussionThreadView(originallyClosed, mode);
- expect(view.$('.comment-form').closest('li').is(":visible")).toBe(!originallyClosed);
- expect(view.$(".discussion-reply-new").is(":visible")).toBe(!originallyClosed);
- view.$(".action-close").click();
- expect(view.$('.comment-form').closest('li').is(":visible")).toBe(originallyClosed);
- return expect(view.$(".discussion-reply-new").is(":visible")).toBe(originallyClosed);
+ expect(view.$('.comment-form').closest('li').is(':visible')).toBe(!originallyClosed);
+ expect(view.$('.discussion-reply-new').is(':visible')).toBe(!originallyClosed);
+ view.$('.action-close').click();
+ expect(view.$('.comment-form').closest('li').is(':visible')).toBe(originallyClosed);
+ return expect(view.$('.discussion-reply-new').is(':visible')).toBe(originallyClosed);
};
checkVoteDisplay = function(originallyClosed, mode) {
var view;
view = createDiscussionThreadView(originallyClosed, mode);
- expect(view.$('.thread-main-wrapper .action-vote').is(":visible")).toBe(!originallyClosed);
- expect(view.$('.thread-main-wrapper .display-vote').is(":visible")).toBe(originallyClosed);
- view.$(".action-close").click();
- expect(view.$('.action-vote').is(":visible")).toBe(originallyClosed);
- return expect(view.$('.display-vote').is(":visible")).toBe(!originallyClosed);
+ expect(view.$('.thread-main-wrapper .action-vote').is(':visible')).toBe(!originallyClosed);
+ expect(view.$('.thread-main-wrapper .display-vote').is(':visible')).toBe(originallyClosed);
+ view.$('.action-close').click();
+ expect(view.$('.action-vote').is(':visible')).toBe(originallyClosed);
+ return expect(view.$('.display-vote').is(':visible')).toBe(!originallyClosed);
};
- return _.each(["tab", "inline"], function(mode) {
+ return _.each(['tab', 'inline'], function(mode) {
it(
- "Test that in " + mode + " mode when a closed thread is opened the comment form is displayed",
+ 'Test that in ' + mode + ' mode when a closed thread is opened the comment form is displayed',
function() { return checkCommentForm(true, mode); }
);
it(
- "Test that in " + mode + " mode when a open thread is closed the comment form is hidden",
+ 'Test that in ' + mode + ' mode when a open thread is closed the comment form is hidden',
function() { return checkCommentForm(false, mode); }
);
it(
- "Test that in " + mode + " mode when a closed thread is opened the vote button is displayed and " +
- "vote count is hidden",
+ 'Test that in ' + mode + ' mode when a closed thread is opened the vote button is displayed and ' +
+ 'vote count is hidden',
function() { return checkVoteDisplay(true, mode); }
);
it(
- "Test that in " + mode + " mode when a open thread is closed the vote button is hidden and " +
- "vote count is displayed",
+ 'Test that in ' + mode + ' mode when a open thread is closed the vote button is hidden and ' +
+ 'vote count is displayed',
function() { return checkVoteDisplay(false, mode); }
);
});
});
- describe("tab mode", function() {
+ describe('tab mode', function() {
beforeEach(function() {
this.view = new DiscussionThreadView({
model: this.thread,
- el: $("#fixture-element"),
- mode: "tab",
+ el: $('#fixture-element'),
+ mode: 'tab',
course_settings: DiscussionSpecHelper.makeCourseSettings()
});
});
- describe("responses", function() {
- it("can post a first response", function() {
+ describe('responses', function() {
+ it('can post a first response', function() {
renderWithTestResponses(this.view, 0);
postResponse(this.view, 1);
- expect(this.view.$(".forum-response").length).toBe(1);
- expect(this.view.$(".post-actions-list").find(".action-edit").parent(".is-hidden").length).toBe(1);
- return expect(this.view.$(".response-actions-list").find(".action-edit")
- .parent().not(".is-hidden").length).toBe(1);
+ expect(this.view.$('.forum-response').length).toBe(1);
+ expect(this.view.$('.post-actions-list').find('.action-edit').parent('.is-hidden').length).toBe(1);
+ return expect(this.view.$('.response-actions-list').find('.action-edit')
+ .parent().not('.is-hidden').length).toBe(1);
});
- it("can post a second response", function() {
+ it('can post a second response', function() {
renderWithTestResponses(this.view, 1);
- expect(this.view.$(".forum-response").length).toBe(1);
- expect(this.view.$(".post-actions-list").find(".action-edit").parent(".is-hidden").length).toBe(1);
- expect(this.view.$(".response-actions-list").find(".action-edit").parent()
- .not(".is-hidden").length).toBe(1);
+ expect(this.view.$('.forum-response').length).toBe(1);
+ expect(this.view.$('.post-actions-list').find('.action-edit').parent('.is-hidden').length).toBe(1);
+ expect(this.view.$('.response-actions-list').find('.action-edit').parent()
+ .not('.is-hidden').length).toBe(1);
postResponse(this.view, 2);
- expect(this.view.$(".forum-response").length).toBe(2);
- expect(this.view.$(".post-actions-list").find(".action-edit").parent(".is-hidden").length).toBe(1);
- return expect(this.view.$(".response-actions-list").find(".action-edit").parent()
- .not(".is-hidden").length).toBe(2);
+ expect(this.view.$('.forum-response').length).toBe(2);
+ expect(this.view.$('.post-actions-list').find('.action-edit').parent('.is-hidden').length).toBe(1);
+ return expect(this.view.$('.response-actions-list').find('.action-edit').parent()
+ .not('.is-hidden').length).toBe(2);
});
});
- describe("response count and pagination", function() {
- it("correctly render for a thread with no responses", function() {
+ describe('response count and pagination', function() {
+ it('correctly render for a thread with no responses', function() {
renderWithTestResponses(this.view, 0);
- return assertResponseCountAndPaginationCorrect(this.view, "0 responses", null, null);
+ return assertResponseCountAndPaginationCorrect(this.view, '0 responses', null, null);
});
- it("correctly render for a thread with one response", function() {
+ it('correctly render for a thread with one response', function() {
renderWithTestResponses(this.view, 1);
return assertResponseCountAndPaginationCorrect(
- this.view, "1 response", "Showing all responses", null
+ this.view, '1 response', 'Showing all responses', null
);
});
- it("correctly render for a thread with one additional page", function() {
+ it('correctly render for a thread with one additional page', function() {
renderWithTestResponses(this.view, 1, {
resp_total: 2
});
return assertResponseCountAndPaginationCorrect(
- this.view, "2 responses", "Showing first response", "Load all responses"
+ this.view, '2 responses', 'Showing first response', 'Load all responses'
);
});
- it("correctly render for a thread with multiple additional pages", function() {
+ it('correctly render for a thread with multiple additional pages', function() {
renderWithTestResponses(this.view, 2, {
resp_total: 111
});
return assertResponseCountAndPaginationCorrect(
- this.view, "111 responses", "Showing first 2 responses", "Load next 100 responses"
+ this.view, '111 responses', 'Showing first 2 responses', 'Load next 100 responses'
);
});
- describe("on clicking the load more button", function() {
+ describe('on clicking the load more button', function() {
beforeEach(function() {
renderWithTestResponses(this.view, 1, {
resp_total: 5
});
return assertResponseCountAndPaginationCorrect(
- this.view, "5 responses", "Showing first response", "Load all responses"
+ this.view, '5 responses', 'Showing first response', 'Load all responses'
);
});
- it("correctly re-render when all threads have loaded", function() {
+ it('correctly re-render when all threads have loaded', function() {
renderWithTestResponses(this.view, 5, {
resp_total: 5
});
- this.view.$el.find(".load-response-button").click();
+ this.view.$el.find('.load-response-button').click();
return assertResponseCountAndPaginationCorrect(
- this.view, "5 responses", "Showing all responses", null
+ this.view, '5 responses', 'Showing all responses', null
);
});
- it("correctly re-render when one page remains", function() {
+ it('correctly re-render when one page remains', function() {
renderWithTestResponses(this.view, 3, {
resp_total: 42
});
- this.view.$el.find(".load-response-button").click();
+ this.view.$el.find('.load-response-button').click();
return assertResponseCountAndPaginationCorrect(
- this.view, "42 responses", "Showing first 3 responses", "Load all responses"
+ this.view, '42 responses', 'Showing first 3 responses', 'Load all responses'
);
});
- it("correctly re-render when multiple pages remain", function() {
+ it('correctly re-render when multiple pages remain', function() {
renderWithTestResponses(this.view, 3, {
resp_total: 111
});
- this.view.$el.find(".load-response-button").click();
+ this.view.$el.find('.load-response-button').click();
return assertResponseCountAndPaginationCorrect(
- this.view, "111 responses", "Showing first 3 responses", "Load next 100 responses"
+ this.view, '111 responses', 'Showing first 3 responses', 'Load next 100 responses'
);
});
});
});
});
- describe("inline mode", function() {
+ describe('inline mode', function() {
beforeEach(function() {
this.view = new DiscussionThreadView({
model: this.thread,
- el: $("#fixture-element"),
- mode: "inline",
+ el: $('#fixture-element'),
+ mode: 'inline',
course_settings: DiscussionSpecHelper.makeCourseSettings()
});
});
- describe("render", function() {
- it("shows content that should be visible when collapsed", function() {
+ describe('render', function() {
+ it('shows content that should be visible when collapsed', function() {
this.view.render();
return assertExpandedContentVisible(this.view, false);
});
- it("does not render any responses by default", function() {
+ it('does not render any responses by default', function() {
this.view.render();
expect($.ajax).not.toHaveBeenCalled();
- return expect(this.view.$el.find(".responses li").length).toEqual(0);
+ return expect(this.view.$el.find('.responses li').length).toEqual(0);
});
});
- describe("focus", function() {
- it("sends focus to the conversation when opened", function(done) {
+ describe('focus', function() {
+ it('sends focus to the conversation when opened', function(done) {
var self;
DiscussionViewSpecHelper.setNextResponseContent({
resp_total: 0,
@@ -315,8 +315,8 @@
});
});
});
- describe("expand/collapse", function() {
- it("shows/hides appropriate content", function() {
+ describe('expand/collapse', function() {
+ it('shows/hides appropriate content', function() {
DiscussionViewSpecHelper.setNextResponseContent({
resp_total: 0,
children: []
@@ -327,28 +327,28 @@
this.view.collapse();
return assertExpandedContentVisible(this.view, false);
});
- it("switches between the abbreviated and full body", function() {
+ it('switches between the abbreviated and full body', function() {
var expectedAbbreviation, longBody;
DiscussionViewSpecHelper.setNextResponseContent({
resp_total: 0,
children: []
});
- longBody = new Array(100).join("test ");
+ longBody = new Array(100).join('test ');
expectedAbbreviation = DiscussionUtil.abbreviateString(longBody, 140);
- this.thread.set("body", longBody);
+ this.thread.set('body', longBody);
this.view.render();
- expect($(".post-body").text()).toEqual(expectedAbbreviation);
+ expect($('.post-body').text()).toEqual(expectedAbbreviation);
expect(DiscussionThreadShowView.prototype.convertMath).toHaveBeenCalled();
DiscussionThreadShowView.prototype.convertMath.calls.reset();
this.view.expand();
- expect($(".post-body").text()).toEqual(longBody);
+ expect($('.post-body').text()).toEqual(longBody);
expect(DiscussionThreadShowView.prototype.convertMath).toHaveBeenCalled();
DiscussionThreadShowView.prototype.convertMath.calls.reset();
this.view.collapse();
- expect($(".post-body").text()).toEqual(expectedAbbreviation);
+ expect($('.post-body').text()).toEqual(expectedAbbreviation);
return expect(DiscussionThreadShowView.prototype.convertMath).toHaveBeenCalled();
});
- it("strips script tags appropriately", function() {
+ it('strips script tags appropriately', function() {
var longMaliciousBody, maliciousAbbreviation;
DiscussionViewSpecHelper.setNextResponseContent({
resp_total: 0,
@@ -357,22 +357,22 @@
longMaliciousBody = new Array(100).join(
"\n"
);
- this.thread.set("body", longMaliciousBody);
+ this.thread.set('body', longMaliciousBody);
maliciousAbbreviation = DiscussionUtil.abbreviateString(this.thread.get('body'), 140);
this.view.render();
- expect($(".post-body").html()).not.toEqual(maliciousAbbreviation);
- expect($(".post-body").text()).toEqual(maliciousAbbreviation);
- expect($(".post-body").html()).not.toContain(""
+ ''
);
schedule_template = _.template($('#schedule_template').html());
save_url = 'save_ccx';
@@ -19,30 +19,30 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
};
data = [{
- "category": "chapter",
- "display_name": "Introduction",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b",
- "hidden": true,
- "children": [
+ 'category': 'chapter',
+ 'display_name': 'Introduction',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b',
+ 'hidden': true,
+ 'children': [
{
- "category": "sequential",
- "display_name": "Demo Course Overview",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/sequential/edx_introduction",
- "hidden": true,
- "children": [
- {
- "category": "vertical",
- "display_name": "Introduction: Video and Sequences",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/vertical/vertical_0270f6de40fc",
- "hidden": true
- }
- ]
+ 'category': 'sequential',
+ 'display_name': 'Demo Course Overview',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/sequential/edx_introduction',
+ 'hidden': true,
+ 'children': [
+ {
+ 'category': 'vertical',
+ 'display_name': 'Introduction: Video and Sequences',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc',
+ 'hidden': true
+ }
+ ]
}
]
}];
@@ -51,39 +51,39 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
view.render();
});
- it("verifies correct view setup", function() {
+ it('verifies correct view setup', function() {
expect(view.dirty).toBe(false);
expect(view.showing).toEqual([]);
expect(view.hidden).toEqual(data);
expect(view.schedule).toEqual(data);
});
- it("finds a unit", function() {
+ it('finds a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
expect(unit).toEqual(data[0]);
});
- it("hides a unit", function() {
+ it('hides a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
unit.hidden = false;
view.hide(unit);
expect(unit.hidden).toBe(true);
});
- it("shows a unit", function() {
+ it('shows a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
view.show(unit);
expect(unit.hidden).toBe(false);
});
- it("applies function to schedule nodes", function() {
+ it('applies function to schedule nodes', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
expect(unit.hidden).toBe(true);
- view.schedule_apply(view.schedule, view.show)
+ view.schedule_apply(view.schedule, view.show);
expect(unit.hidden).toBe(false);
});
- it("adds all units to schedule", function() {
+ it('adds all units to schedule', function() {
expect(view.showing).toEqual([]);
expect(view.hidden.length).toEqual(1);
$('#add-all').click();
@@ -91,7 +91,7 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.hidden).toEqual([]);
});
- it("selects a chapter and adds units to dropdown", function() {
+ it('selects a chapter and adds units to dropdown', function() {
expect(view.sequential_select.children('option').length).toEqual(0);
view.chapter_select.change();
expect(view.sequential_select.prop('disabled')).toEqual(true);
@@ -103,14 +103,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.sequential_select.children('option').length).toEqual(2);
});
- it("selects a unit and adds sections to dropdown", function() {
+ it('selects a unit and adds sections to dropdown', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
expect(view.vertical_select.children('option').length).toEqual(0);
view.sequential_select.change();
expect(view.vertical_select.prop('disabled')).toEqual(true);
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
expect(view.sequential_select.val()).toEqual(val);
@@ -118,27 +118,27 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.vertical_select.children('option').length).toEqual(2);
});
- it("selects a section", function() {
+ it('selects a section', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
expect(view.vertical_select.val()).toEqual(val);
});
- it("adds a unit", function() {
+ it('adds a unit', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc",
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc',
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -149,14 +149,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(false);
});
- it("add unit when start date is greater the due date", function() {
+ it('add unit when start date is greater the due date', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -169,14 +169,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(true);
});
- it("add unit when start date is missing", function() {
+ it('add unit when start date is missing', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -189,39 +189,38 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(true);
});
- it("gets a datetime string from date and time fields", function() {
+ it('gets a datetime string from date and time fields', function() {
view.set_datetime('start', '2015-12-12 10:45');
expect($('form#add-unit input[name=start_date]')).toHaveValue('2015-12-12');
expect($('form#add-unit input[name=start_time]')).toHaveValue('10:45');
});
- it("sets date and time fields from datetime string", function() {
+ it('sets date and time fields from datetime string', function() {
$('form#add-unit input[name=start_date]').val('2015-12-12');
$('form#add-unit input[name=start_time]').val('10:45');
var datetime = view.get_datetime('start');
expect(datetime).toBe('2015-12-12 10:45');
});
- it("saves schedule changes", function() {
- requests = AjaxHelpers["requests"](this)
+ it('saves schedule changes', function() {
+ requests = AjaxHelpers['requests'](this);
view.save();
- expect(requests.length).toEqual(1)
+ expect(requests.length).toEqual(1);
AjaxHelpers.expectJsonRequest(requests, 'POST', 'save_ccx', view.schedule);
- expect($('#dirty-schedule #save-changes').text()).toEqual("Saving");
+ expect($('#dirty-schedule #save-changes').text()).toEqual('Saving');
AjaxHelpers.respondWithJson(requests, {
data: view.schedule
});
- expect($('#dirty-schedule #save-changes').text()).toEqual("Save changes");
+ expect($('#dirty-schedule #save-changes').text()).toEqual('Save changes');
expect($('#ajax-error')).toHaveCss({display: 'none'});
});
- it("displays an error if the sync fails", function() {
- requests = AjaxHelpers["requests"](this)
+ it('displays an error if the sync fails', function() {
+ requests = AjaxHelpers['requests'](this);
view.save();
requests[0].respond(500);
expect($('#ajax-error')).toHaveCss({display: 'block'});
});
-
});
}
);
diff --git a/lms/static/js/spec/commerce/receipt_view_spec.js b/lms/static/js/spec/commerce/receipt_view_spec.js
index b30570e6f1..ff42f05fc0 100644
--- a/lms/static/js/spec/commerce/receipt_view_spec.js
+++ b/lms/static/js/spec/commerce/receipt_view_spec.js
@@ -1,10 +1,10 @@
define([
- 'jquery',
- 'jquery.ajax-retry',
- 'js/commerce/views/receipt_view',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
- ],
- function ($, AjaxRetry, ReceiptView, AjaxHelpers) {
+ 'jquery',
+ 'jquery.ajax-retry',
+ 'js/commerce/views/receipt_view',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
+],
+ function($, AjaxRetry, ReceiptView, AjaxHelpers) {
'use strict';
describe('edx.commerce.ReceiptView', function() {
var data, courseResponseData, providerResponseData, mockRequests, mockRender, createReceiptView,
@@ -15,17 +15,17 @@ define([
};
mockRequests = function(requests, method, apiUrl, responseData) {
- AjaxHelpers.expectRequest(requests, method, apiUrl);
- AjaxHelpers.respondWithJson(requests, responseData);
+ AjaxHelpers.expectRequest(requests, method, apiUrl);
+ AjaxHelpers.respondWithJson(requests, responseData);
};
mockRender = function(useEcommerceOrderNumber, isVerified) {
var requests, view, orderUrlFormat;
requests = AjaxHelpers.requests(this);
- $("#receipt-container").data("verified", isVerified);
+ $('#receipt-container').data('verified', isVerified);
view = createReceiptView();
view.useEcommerceApi = true;
- if (useEcommerceOrderNumber){
+ if (useEcommerceOrderNumber) {
view.ecommerceOrderNumber = 'EDX-123456';
orderUrlFormat = '/api/commerce/v1/orders/EDX-123456/';
}
@@ -68,92 +68,92 @@ define([
);
data = {
- "status": "Open",
- "billed_to": {
- "city": "dummy city",
- "first_name": "john",
- "last_name": "doe",
- "country": "AL",
- "line2": "line2",
- "line1": "line1",
- "state": "",
- "postcode": "12345"
+ 'status': 'Open',
+ 'billed_to': {
+ 'city': 'dummy city',
+ 'first_name': 'john',
+ 'last_name': 'doe',
+ 'country': 'AL',
+ 'line2': 'line2',
+ 'line1': 'line1',
+ 'state': '',
+ 'postcode': '12345'
},
- "lines": [
+ 'lines': [
{
- "status": "Open",
- "unit_price_excl_tax": "10.00",
- "product": {
- "attribute_values": [
+ 'status': 'Open',
+ 'unit_price_excl_tax': '10.00',
+ 'product': {
+ 'attribute_values': [
{
- "name": "certificate_type",
- "value": "verified"
+ 'name': 'certificate_type',
+ 'value': 'verified'
},
{
- "name": "course_key",
- "code": "course_key",
- "value": "course-v1:edx+dummy+2015_T3"
+ 'name': 'course_key',
+ 'code': 'course_key',
+ 'value': 'course-v1:edx+dummy+2015_T3'
},
{
- "name": "credit_provider",
- "value": "edx"
+ 'name': 'credit_provider',
+ 'value': 'edx'
}
],
- "stockrecords": [
+ 'stockrecords': [
{
- "price_currency": "USD",
- "product": 123,
- "partner_sku": "1234ABC",
- "partner": 1,
- "price_excl_tax": "10.00",
- "id": 123
+ 'price_currency': 'USD',
+ 'product': 123,
+ 'partner_sku': '1234ABC',
+ 'partner': 1,
+ 'price_excl_tax': '10.00',
+ 'id': 123
}
],
- "product_class": "Seat",
- "title": "Dummy title",
- "url": "https://ecom.edx.org/api/v2/products/123/",
- "price": "10.00",
- "expires": null,
- "is_available_to_buy": true,
- "id": 123,
- "structure": "child"
+ 'product_class': 'Seat',
+ 'title': 'Dummy title',
+ 'url': 'https://ecom.edx.org/api/v2/products/123/',
+ 'price': '10.00',
+ 'expires': null,
+ 'is_available_to_buy': true,
+ 'id': 123,
+ 'structure': 'child'
},
- "line_price_excl_tax": "10.00",
- "description": "dummy description",
- "title": "dummy title",
- "quantity": 1
+ 'line_price_excl_tax': '10.00',
+ 'description': 'dummy description',
+ 'title': 'dummy title',
+ 'quantity': 1
}
],
- "number": "EDX-123456",
- "date_placed": "2016-01-01T01:01:01Z",
- "currency": "USD",
- "total_excl_tax": "10.00"
+ 'number': 'EDX-123456',
+ 'date_placed': '2016-01-01T01:01:01Z',
+ 'currency': 'USD',
+ 'total_excl_tax': '10.00'
};
providerResponseData = {
- "id": "edx",
- "display_name": "edX",
- "url": "http://www.edx.org",
- "status_url": "http://www.edx.org/status",
- "description": "Nothing",
- "enable_integration": false,
- "fulfillment_instructions": "",
- "thumbnail_url": "http://edx.org/thumbnail.png"
+ 'id': 'edx',
+ 'display_name': 'edX',
+ 'url': 'http://www.edx.org',
+ 'status_url': 'http://www.edx.org/status',
+ 'description': 'Nothing',
+ 'enable_integration': false,
+ 'fulfillment_instructions': '',
+ 'thumbnail_url': 'http://edx.org/thumbnail.png'
};
courseResponseData = {
- "id": "course-v1:edx+dummy+2015_T3",
- "name": "receipt test",
- "category": "course",
- "org": "edx",
- "run": "2015_T2",
- "course": "CS420",
- "uri": "http://test.com/api/courses/v1/courses/course-v1:edx+dummy+2015_T3/",
- "image_url": "/test.jpg",
- "start": "2030-01-01T00:00:00Z",
- "end": null
+ 'id': 'course-v1:edx+dummy+2015_T3',
+ 'name': 'receipt test',
+ 'category': 'course',
+ 'org': 'edx',
+ 'run': '2015_T2',
+ 'course': 'CS420',
+ 'uri': 'http://test.com/api/courses/v1/courses/course-v1:edx+dummy+2015_T3/',
+ 'image_url': '/test.jpg',
+ 'start': '2030-01-01T00:00:00Z',
+ 'end': null
};
userResponseData = {
- "username": "user-1",
- "name": "full name"
+ 'username': 'user-1',
+ 'name': 'full name'
};
});
@@ -167,7 +167,6 @@ define([
currency: 'USD'
}
);
-
});
it('sends analytic event when non verified receipt is rendered', function() {
@@ -180,7 +179,6 @@ define([
currency: 'USD'
}
);
-
});
it('renders a receipt correctly with Ecommerce Order Number', function() {
@@ -196,7 +194,6 @@ define([
view = mockRender(false, 'True');
expect(view.$('.course_name_placeholder').text()).toContain('receipt test');
});
-
});
}
);
diff --git a/lms/static/js/spec/components/card/card_spec.js b/lms/static/js/spec/components/card/card_spec.js
index 4145f9ee83..284138dc50 100644
--- a/lms/static/js/spec/components/card/card_spec.js
+++ b/lms/static/js/spec/components/card/card_spec.js
@@ -1,4 +1,4 @@
-(function (define) {
+(function(define) {
'use strict';
define(['jquery',
@@ -7,43 +7,42 @@
'js/components/card/views/card'
],
function($, _, Backbone, CardView) {
-
- describe('card component view', function () {
- it('can render itself as a square card', function () {
- var view = new CardView({ configuration: 'square_card' });
+ describe('card component view', function() {
+ it('can render itself as a square card', function() {
+ var view = new CardView({configuration: 'square_card'});
expect(view.$el).toHaveClass('square-card');
expect(view.$el.find('.wrapper-card-meta .action').length).toBe(1);
});
- it('can render itself as a list card', function () {
- var view = new CardView({ configuration: 'list_card' });
+ it('can render itself as a list card', function() {
+ var view = new CardView({configuration: 'list_card'});
expect(view.$el).toHaveClass('list-card');
expect(view.$el.find('.wrapper-card-core .action').length).toBe(1);
});
- it('renders a pennant only if the pennant value is truthy', function () {
- var view = new (CardView.extend({ pennant: '' }))();
+ it('renders a pennant only if the pennant value is truthy', function() {
+ var view = new (CardView.extend({pennant: ''}))();
expect(view.$el.find('.card-type').length).toBe(0);
- view = new (CardView.extend({ pennant: 'Test Pennant' }))();
+ view = new (CardView.extend({pennant: 'Test Pennant'}))();
expect(view.$el.find('.card-type').length).toBe(1);
});
- it('can render child views', function () {
- var testChildView = new (Backbone.View.extend({ className: 'test-view' }))();
+ it('can render child views', function() {
+ var testChildView = new (Backbone.View.extend({className: 'test-view'}))();
spyOn(testChildView, 'render');
- var view = new (CardView.extend({ details: [testChildView] }))();
+ var view = new (CardView.extend({details: [testChildView]}))();
expect(testChildView.render).toHaveBeenCalled();
expect(view.$el.find('.test-view')).toHaveClass('meta-detail');
});
- it('calls action when clicked', function () {
+ it('calls action when clicked', function() {
spyOn(CardView.prototype, 'action');
- var view = new CardView({ configuration: 'square_card' });
+ var view = new CardView({configuration: 'square_card'});
view.$el.find('.action').trigger('click');
expect(view.action).toHaveBeenCalled();
});
- var verifyContent = function (view) {
+ var verifyContent = function(view) {
expect(view.$el).toHaveClass('test-card');
expect(view.$el.find('.card-type').text()).toContain('Pennant');
expect(view.$el.find('.card-title').text()).toContain('A test title');
@@ -53,7 +52,7 @@
expect(view.$el.find('.action').text()).toContain('A test action');
};
- it('can have strings for cardClass, pennant, title, description, and action', function () {
+ it('can have strings for cardClass, pennant, title, description, and action', function() {
var view = new (CardView.extend({
cardClass: 'test-card',
pennant: 'Pennant',
@@ -66,15 +65,15 @@
verifyContent(view);
});
- it('can have functions for cardClass, pennant, title, description, and action', function () {
+ it('can have functions for cardClass, pennant, title, description, and action', function() {
var view = new (CardView.extend({
- cardClass: function () { return 'test-card'; },
- pennant: function () { return 'Pennant'; },
- title: function () { return 'A test title'; },
- description: function () { return 'A test description'; },
- actionClass: function () { return 'test-action'; },
- actionUrl: function () { return 'www.example.com'; },
- actionContent: function () { return 'A test action'; }
+ cardClass: function() { return 'test-card'; },
+ pennant: function() { return 'Pennant'; },
+ title: function() { return 'A test title'; },
+ description: function() { return 'A test description'; },
+ actionClass: function() { return 'test-action'; },
+ actionUrl: function() { return 'www.example.com'; },
+ actionContent: function() { return 'A test action'; }
}));
verifyContent(view);
});
diff --git a/lms/static/js/spec/components/header/header_spec.js b/lms/static/js/spec/components/header/header_spec.js
index 7df8ce8ba6..d66a78b58d 100644
--- a/lms/static/js/spec/components/header/header_spec.js
+++ b/lms/static/js/spec/components/header/header_spec.js
@@ -1,4 +1,4 @@
-(function (define) {
+(function(define) {
'use strict';
define(['jquery',
@@ -7,20 +7,19 @@
'js/components/header/models/header'
],
function($, _, HeaderView, HeaderModel) {
-
- describe('header component view', function () {
+ describe('header component view', function() {
var model, view;
- var testBreadcrumbs = function (breadcrumbs) {
+ var testBreadcrumbs = function(breadcrumbs) {
model.set('breadcrumbs', breadcrumbs);
expect(view.$('nav.breadcrumbs').length).toBe(1);
- _.each(view.$('.nav-item'), function (el, index) {
+ _.each(view.$('.nav-item'), function(el, index) {
expect($(el).attr('href')).toEqual(breadcrumbs[index].url);
expect($(el).text()).toEqual(breadcrumbs[index].title);
});
};
- beforeEach(function () {
+ beforeEach(function() {
model = new HeaderModel({
title: 'Test title',
description: 'Test description'
@@ -30,16 +29,16 @@
});
});
- it('can render itself', function () {
+ it('can render itself', function() {
expect(view.$el.text()).toContain('Test title');
expect(view.$el.text()).toContain('Test description');
});
- it('does not show breadcrumbs by default', function () {
+ it('does not show breadcrumbs by default', function() {
expect(view.$el.html()).not.toContain('');
});
- it('shows breadcrumbs if they are supplied', function () {
+ it('shows breadcrumbs if they are supplied', function() {
testBreadcrumbs([
{url: 'url1', title: 'Crumb 1'},
{url: 'url2', title: 'Crumb 2'}
@@ -47,7 +46,7 @@
testBreadcrumbs([{url: 'url1', title: 'Crumb 1'}]);
});
- it('renders itself when its model changes', function () {
+ it('renders itself when its model changes', function() {
expect(view.$el.text()).toContain('Test title');
model.set('title', 'Changed title');
expect(view.$el.text()).toContain('Changed title');
diff --git a/lms/static/js/spec/courseware/bookmark_button_view_spec.js b/lms/static/js/spec/courseware/bookmark_button_view_spec.js
index 33681057c6..69248b937a 100644
--- a/lms/static/js/spec/courseware/bookmark_button_view_spec.js
+++ b/lms/static/js/spec/courseware/bookmark_button_view_spec.js
@@ -1,15 +1,15 @@
define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers', 'js/bookmarks/views/bookmark_button'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, BookmarkButtonView) {
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, BookmarkButtonView) {
'use strict';
- describe("bookmarks.button", function () {
+ describe('bookmarks.button', function() {
var timerCallback;
var API_URL = 'bookmarks/api/v1/bookmarks/';
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/bookmarks/bookmark_button.html');
TemplateHelpers.installTemplates(
[
@@ -35,7 +35,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
};
- var verifyBookmarkButtonState = function (view, bookmarked) {
+ var verifyBookmarkButtonState = function(view, bookmarked) {
if (bookmarked) {
expect(view.$el).toHaveAttr('aria-pressed', 'true');
expect(view.$el).toHaveClass('bookmarked');
@@ -48,7 +48,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$el.data('bookmarkId')).toBe('bilbo,usage_1');
};
- it("rendered correctly ", function () {
+ it('rendered correctly ', function() {
var view = createBookmarkButtonView(false);
verifyBookmarkButtonState(view, false);
@@ -57,7 +57,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
verifyBookmarkButtonState(view, true);
});
- it("bookmark/un-bookmark the block correctly", function () {
+ it('bookmark/un-bookmark the block correctly', function() {
var addBookmarkedData = {
bookmarked: true,
handler: 'removeBookmark',
@@ -79,7 +79,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
var bookmarkedData = [[addBookmarkedData, removeBookmarkData], [removeBookmarkData, addBookmarkedData]];
_.each(bookmarkedData, function(actionsData) {
var firstActionData = actionsData[0];
- var secondActionData = actionsData[1];
+ var secondActionData = actionsData[1];
var bookmarkButtonView = createBookmarkButtonView(firstActionData.bookmarked);
verifyBookmarkButtonState(bookmarkButtonView, firstActionData.bookmarked);
@@ -126,10 +126,9 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
verifyBookmarkButtonState(bookmarkButtonView, firstActionData.bookmarked);
bookmarkButtonView.undelegateEvents();
});
-
});
- it("shows an error message for HTTP 500", function () {
+ it('shows an error message for HTTP 500', function() {
var requests = AjaxHelpers.requests(this),
$messageBanner = $('.message-banner'),
bookmarkButtonView = createBookmarkButtonView(false);
@@ -148,7 +147,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect($messageBanner.text().trim()).toBe(bookmarkButtonView.errorMessage);
});
- it('removes error message after 5 seconds', function () {
+ it('removes error message after 5 seconds', function() {
var requests = AjaxHelpers.requests(this),
$messageBanner = $('.message-banner'),
bookmarkButtonView = createBookmarkButtonView(false);
diff --git a/lms/static/js/spec/courseware/bookmarks_list_view_spec.js b/lms/static/js/spec/courseware/bookmarks_list_view_spec.js
index 7ddb1774da..095c96637a 100644
--- a/lms/static/js/spec/courseware/bookmarks_list_view_spec.js
+++ b/lms/static/js/spec/courseware/bookmarks_list_view_spec.js
@@ -8,15 +8,14 @@ define(['backbone',
'js/bookmarks/views/bookmarks_list_button',
'js/bookmarks/views/bookmarks_list',
'js/bookmarks/collections/bookmarks'],
- function (Backbone, $, _, Logger, URI, AjaxHelpers, TemplateHelpers, BookmarksListButtonView, BookmarksListView,
+ function(Backbone, $, _, Logger, URI, AjaxHelpers, TemplateHelpers, BookmarksListButtonView, BookmarksListView,
BookmarksCollection) {
'use strict';
- describe("lms.courseware.bookmarks", function () {
-
+ describe('lms.courseware.bookmarks', function() {
var bookmarksButtonView;
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/bookmarks/bookmarks.html');
TemplateHelpers.installTemplates(
[
@@ -26,28 +25,28 @@ define(['backbone',
);
spyOn(Logger, 'log').and.returnValue($.Deferred().resolve());
jasmine.addMatchers({
- toHaveBeenCalledWithUrl: function () {
- return {
- compare: function (actual, expectedUrl) {
- return {
- pass: expectedUrl === actual.calls.mostRecent().args[0].currentTarget.pathname
- };
- }
- };
- }
+ toHaveBeenCalledWithUrl: function() {
+ return {
+ compare: function(actual, expectedUrl) {
+ return {
+ pass: expectedUrl === actual.calls.mostRecent().args[0].currentTarget.pathname
+ };
+ }
+ };
+ }
});
bookmarksButtonView = new BookmarksListButtonView();
});
- var verifyRequestParams = function (requests, params) {
+ var verifyRequestParams = function(requests, params) {
var urlParams = (new URI(requests[requests.length - 1].url)).query(true);
- _.each(params, function (value, key) {
+ _.each(params, function(value, key) {
expect(urlParams[key]).toBe(value);
});
};
- var createBookmarksData = function (options) {
+ var createBookmarksData = function(options) {
var data = {
count: options.count || 0,
num_pages: options.num_pages || 1,
@@ -56,7 +55,7 @@ define(['backbone',
results: []
};
- for(var i = 0; i < options.numBookmarksToCreate; i++) {
+ for (var i = 0; i < options.numBookmarksToCreate; i++) {
var bookmarkInfo = {
id: i,
display_name: 'UNIT_DISPLAY_NAME_' + i,
@@ -76,24 +75,24 @@ define(['backbone',
return data;
};
- var createBookmarkUrl = function (courseId, usageId) {
+ var createBookmarkUrl = function(courseId, usageId) {
return '/courses/' + courseId + '/jump_to/' + usageId;
};
- var breadcrumbTrail = function (path, unitDisplayName) {
+ var breadcrumbTrail = function(path, unitDisplayName) {
return _.pluck(path, 'display_name').
concat([unitDisplayName]).
join(' - ');
};
- var verifyBookmarkedData = function (view, expectedData) {
+ var verifyBookmarkedData = function(view, expectedData) {
var courseId, usageId;
var bookmarks = view.$('.bookmarks-results-list-item');
var results = expectedData.results;
expect(bookmarks.length, results.length);
- for(var bookmark_index = 0; bookmark_index < results.length; bookmark_index++) {
+ for (var bookmark_index = 0; bookmark_index < results.length; bookmark_index++) {
courseId = results[bookmark_index].course_id;
usageId = results[bookmark_index].usage_id;
@@ -111,7 +110,7 @@ define(['backbone',
}
};
- var verifyPaginationInfo = function (requests, expectedData, currentPage, headerMessage) {
+ var verifyPaginationInfo = function(requests, expectedData, currentPage, headerMessage) {
AjaxHelpers.respondWithJson(requests, expectedData);
verifyBookmarkedData(bookmarksButtonView.bookmarksListView, expectedData);
expect(bookmarksButtonView.bookmarksListView.$('.paging-footer span.current-page').text().trim()).
@@ -120,7 +119,7 @@ define(['backbone',
toBe(headerMessage);
};
- it("has correct behavior for bookmarks button", function () {
+ it('has correct behavior for bookmarks button', function() {
var requests = AjaxHelpers.requests(this);
spyOn(bookmarksButtonView, 'toggleBookmarksListView').and.callThrough();
@@ -141,7 +140,7 @@ define(['backbone',
expect(bookmarksButtonView.$('.bookmarks-list-button')).toHaveClass('is-inactive');
});
- it("can correctly render an empty bookmarks list", function () {
+ it('can correctly render an empty bookmarks list', function() {
var requests = AjaxHelpers.requests(this);
var expectedData = createBookmarksData({numBookmarksToCreate: 0});
@@ -151,10 +150,10 @@ define(['backbone',
expect(bookmarksButtonView.bookmarksListView.$('.bookmarks-empty-header').text().trim()).
toBe('You have not bookmarked any courseware pages yet.');
- var emptyListText = "Use bookmarks to help you easily return to courseware pages. " +
- "To bookmark a page, select Bookmark in the upper right corner of that page. " +
- "To see a list of all your bookmarks, select Bookmarks in the upper left " +
- "corner of any courseware page.";
+ var emptyListText = 'Use bookmarks to help you easily return to courseware pages. ' +
+ 'To bookmark a page, select Bookmark in the upper right corner of that page. ' +
+ 'To see a list of all your bookmarks, select Bookmarks in the upper left ' +
+ 'corner of any courseware page.';
expect(bookmarksButtonView.bookmarksListView.$('.bookmarks-empty-detail-title').text().trim()).
toBe(emptyListText);
@@ -163,7 +162,7 @@ define(['backbone',
expect(bookmarksButtonView.bookmarksListView.$('.paging-footer').length).toBe(0);
});
- it("has rendered bookmarked list correctly", function () {
+ it('has rendered bookmarked list correctly', function() {
var requests = AjaxHelpers.requests(this);
var expectedData = createBookmarksData({numBookmarksToCreate: 3});
@@ -184,7 +183,7 @@ define(['backbone',
expect(bookmarksButtonView.bookmarksListView.$('.paging-footer').length).toBe(1);
});
- it("calls bookmarks list render on page_changed event", function () {
+ it('calls bookmarks list render on page_changed event', function() {
var renderSpy = spyOn(BookmarksListView.prototype, 'render');
var listView = new BookmarksListView({
collection: new BookmarksCollection([], {
@@ -196,7 +195,7 @@ define(['backbone',
expect(renderSpy).toHaveBeenCalled();
});
- it("can go to a page number", function () {
+ it('can go to a page number', function() {
var requests = AjaxHelpers.requests(this);
var expectedData = createBookmarksData(
{
@@ -233,7 +232,7 @@ define(['backbone',
toBe('Showing 11-12 out of 12 total');
});
- it("can navigate forward and backward", function () {
+ it('can navigate forward and backward', function() {
var requests = AjaxHelpers.requests(this);
var expectedData = createBookmarksData(
{
@@ -285,7 +284,7 @@ define(['backbone',
);
});
- it("can navigate to correct url", function () {
+ it('can navigate to correct url', function() {
var requests = AjaxHelpers.requests(this);
spyOn(bookmarksButtonView.bookmarksListView, 'visitBookmark');
@@ -297,7 +296,7 @@ define(['backbone',
expect(bookmarksButtonView.bookmarksListView.visitBookmark).toHaveBeenCalledWithUrl(url);
});
- it("shows an error message for HTTP 500", function () {
+ it('shows an error message for HTTP 500', function() {
var requests = AjaxHelpers.requests(this);
bookmarksButtonView.$('.bookmarks-list-button').click();
diff --git a/lms/static/js/spec/courseware/course_home_events_spec.js b/lms/static/js/spec/courseware/course_home_events_spec.js
index 6702577627..749e0c13aa 100644
--- a/lms/static/js/spec/courseware/course_home_events_spec.js
+++ b/lms/static/js/spec/courseware/course_home_events_spec.js
@@ -1,23 +1,23 @@
-define(['jquery', 'logger', 'js/courseware/course_home_events'], function ($, Logger, courseHomeEvents) {
+define(['jquery', 'logger', 'js/courseware/course_home_events'], function($, Logger, courseHomeEvents) {
'use strict';
- describe('Course home page eventing', function () {
- beforeEach(function () {
+ describe('Course home page eventing', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/courseware/course_home_events.html');
courseHomeEvents();
spyOn(Logger, 'log');
});
- it('sends an event when "Resume Course" is clicked', function () {
+ it('sends an event when "Resume Course" is clicked', function() {
$('.last-accessed-link').click();
expect(Logger.log).toHaveBeenCalledWith('edx.course.home.resume_course.clicked', {
- url: "http://" +
+ url: 'http://' +
window.location.host +
- "/courses/course-v1:edX+DemoX+Demo_Course/courseware/19a30717eff543078a5d94ae9d6c18a5/"
+ '/courses/course-v1:edX+DemoX+Demo_Course/courseware/19a30717eff543078a5d94ae9d6c18a5/'
});
});
- it('sends an event when "Upgrade to Verified" is clicked', function () {
+ it('sends an event when "Upgrade to Verified" is clicked', function() {
$('.date-summary-link').click();
expect(Logger.log).toHaveBeenCalledWith('edx.course.home.upgrade_verified.clicked', {});
});
diff --git a/lms/static/js/spec/courseware/link_clicked_events_spec.js b/lms/static/js/spec/courseware/link_clicked_events_spec.js
index bec1181d5c..7e4ee220fb 100644
--- a/lms/static/js/spec/courseware/link_clicked_events_spec.js
+++ b/lms/static/js/spec/courseware/link_clicked_events_spec.js
@@ -1,30 +1,30 @@
-define(['jquery', 'logger', 'js/courseware/courseware_factory'], function ($, Logger, coursewareFactory) {
+define(['jquery', 'logger', 'js/courseware/courseware_factory'], function($, Logger, coursewareFactory) {
'use strict';
- describe('Courseware link click eventing', function () {
- beforeEach(function () {
+ describe('Courseware link click eventing', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/courseware/link_clicked_events.html');
coursewareFactory();
spyOn(Logger, 'log');
});
- it('sends an event when an external link is clicked', function () {
+ it('sends an event when an external link is clicked', function() {
$('.external-link').click();
expect(Logger.log).toHaveBeenCalledWith('edx.ui.lms.link_clicked', {
- target_url: "http://example.com/",
- current_url: "http://" + window.location.host + "/context.html"
+ target_url: 'http://example.com/',
+ current_url: 'http://' + window.location.host + '/context.html'
});
});
- it('sends an event when an internal link is clicked', function () {
+ it('sends an event when an internal link is clicked', function() {
$('.internal-link').click();
expect(Logger.log).toHaveBeenCalledWith('edx.ui.lms.link_clicked', {
- target_url: "http://" + window.location.host + "/some/internal/link",
- current_url: "http://" + window.location.host + "/context.html"
+ target_url: 'http://' + window.location.host + '/some/internal/link',
+ current_url: 'http://' + window.location.host + '/context.html'
});
});
- it('does not send an event when a page navigation link is clicked', function () {
+ it('does not send an event when a page navigation link is clicked', function() {
$('.page-nav').click();
expect(Logger.log).not.toHaveBeenCalledWith('edx.ui.lms.link_clicked');
});
diff --git a/lms/static/js/spec/courseware/updates_visibility_spec.js b/lms/static/js/spec/courseware/updates_visibility_spec.js
index df10a9ccf8..7efcbf0f85 100644
--- a/lms/static/js/spec/courseware/updates_visibility_spec.js
+++ b/lms/static/js/spec/courseware/updates_visibility_spec.js
@@ -1,16 +1,15 @@
define(['jquery', 'logger', 'js/courseware/toggle_element_visibility', 'moment'],
- function ($, Logger, ToggleElementVisibility, moment) {
+ function($, Logger, ToggleElementVisibility, moment) {
'use strict';
- describe('show/hide with mouse click', function () {
-
+ describe('show/hide with mouse click', function() {
beforeEach(function() {
loadFixtures('js/fixtures/courseware/course_updates.html');
ToggleElementVisibility();
spyOn(Logger, 'log');
});
- it('ensures update will hide on hide button click', function () {
+ it('ensures update will hide on hide button click', function() {
var $shownUpdate = $('.toggle-visibility-element:not(.hidden)').first(),
$updateButton = $shownUpdate.siblings('.toggle-visibility-button');
$updateButton.trigger('click');
@@ -18,7 +17,7 @@ define(['jquery', 'logger', 'js/courseware/toggle_element_visibility', 'moment']
expect($updateButton.text()).toEqual('Show');
});
- it('ensures update will show on show button click', function () {
+ it('ensures update will show on show button click', function() {
var $hiddenUpdate = $('.toggle-visibility-element.hidden').first(),
$updateButton = $hiddenUpdate.siblings('.toggle-visibility-button');
$updateButton.trigger('click');
@@ -26,7 +25,7 @@ define(['jquery', 'logger', 'js/courseware/toggle_element_visibility', 'moment']
expect($updateButton.text()).toEqual('Hide');
});
- it('ensures old updates will show on button click', function () {
+ it('ensures old updates will show on button click', function() {
// on page load old updates will be hidden
var $oldUpdates = $('.toggle-visibility-element.old-updates');
expect($oldUpdates).toHaveClass('hidden');
@@ -36,7 +35,7 @@ define(['jquery', 'logger', 'js/courseware/toggle_element_visibility', 'moment']
expect($oldUpdates).not.toHaveClass('hidden');
});
- it('sends a tracking event on hide and show', function () {
+ it('sends a tracking event on hide and show', function() {
var $update = $('.toggle-visibility-element:not(.hidden)').first();
$update.siblings('.toggle-visibility-button').trigger('click');
expect(Logger.log).toHaveBeenCalledWith('edx.course.home.course_update.toggled', {
diff --git a/lms/static/js/spec/dashboard/donation.js b/lms/static/js/spec/dashboard/donation.js
index ab921c90c5..753d4c20b7 100644
--- a/lms/static/js/spec/dashboard/donation.js
+++ b/lms/static/js/spec/dashboard/donation.js
@@ -4,25 +4,24 @@ define(['common/js/spec_helpers/template_helpers',
function(TemplateHelpers, AjaxHelpers) {
'use strict';
- describe("edx.dashboard.donation.DonationView", function() {
-
- var PAYMENT_URL = "https://fake.processor.com/pay/";
+ describe('edx.dashboard.donation.DonationView', function() {
+ var PAYMENT_URL = 'https://fake.processor.com/pay/';
var PAYMENT_PARAMS = {
- orderId: "test-order",
- signature: "abcd1234"
+ orderId: 'test-order',
+ signature: 'abcd1234'
};
- var AMOUNT = "45.67";
- var COURSE_ID = "edx/DemoX/Demo";
+ var AMOUNT = '45.67';
+ var COURSE_ID = 'edx/DemoX/Demo';
var view = null;
var requests = null;
beforeEach(function() {
- setFixtures("
");
+ setFixtures('
');
TemplateHelpers.installTemplate('templates/dashboard/donation');
view = new edx.dashboard.donation.DonationView({
- el: $("#jasmine-fixtures"),
+ el: $('#jasmine-fixtures'),
course: COURSE_ID
}).render();
@@ -37,7 +36,7 @@ define(['common/js/spec_helpers/template_helpers',
window.analytics = jasmine.createSpyObj('analytics', ['track']);
});
- it("processes a donation for a course", function() {
+ it('processes a donation for a course', function() {
// Spy on AJAX requests
requests = AjaxHelpers.requests(this);
@@ -49,15 +48,15 @@ define(['common/js/spec_helpers/template_helpers',
// the donation item in the shopping cart and receive
// the signed payment params.
AjaxHelpers.expectRequest(
- requests, "POST", "/shoppingcart/donation/",
- $.param({ amount: AMOUNT, course_id: COURSE_ID })
+ requests, 'POST', '/shoppingcart/donation/',
+ $.param({amount: AMOUNT, course_id: COURSE_ID})
);
// Simulate a response from the server containing the signed
// parameters to send to the payment processor
AjaxHelpers.respondWithJson(requests, {
payment_url: PAYMENT_URL,
- payment_params: PAYMENT_PARAMS,
+ payment_params: PAYMENT_PARAMS
});
// Verify that the payment form has the payment parameters
@@ -68,58 +67,58 @@ define(['common/js/spec_helpers/template_helpers',
expect(view.submitPaymentForm).toHaveBeenCalled();
var form = view.submitPaymentForm.calls.mostRecent().args[0];
expect(form.serialize()).toEqual($.param(PAYMENT_PARAMS));
- expect(form.attr('method')).toEqual("post");
+ expect(form.attr('method')).toEqual('post');
expect(form.attr('action')).toEqual(PAYMENT_URL);
});
- it("validates the donation amount", function() {
+ it('validates the donation amount', function() {
var assertValidAmount = function(amount, isValid) {
expect(view.validateAmount(amount)).toBe(isValid);
};
- assertValidAmount("", false);
- assertValidAmount(" ", false);
- assertValidAmount("abc", false);
- assertValidAmount("14.", false);
- assertValidAmount(".1", false);
- assertValidAmount("-1", false);
- assertValidAmount("-1.00", false);
- assertValidAmount("-", false);
- assertValidAmount("0", false);
- assertValidAmount("0.00", false);
- assertValidAmount("00.00", false);
- assertValidAmount("3", true);
- assertValidAmount("12.34", true);
- assertValidAmount("278", true);
- assertValidAmount("278.91", true);
- assertValidAmount("0.14", true);
+ assertValidAmount('', false);
+ assertValidAmount(' ', false);
+ assertValidAmount('abc', false);
+ assertValidAmount('14.', false);
+ assertValidAmount('.1', false);
+ assertValidAmount('-1', false);
+ assertValidAmount('-1.00', false);
+ assertValidAmount('-', false);
+ assertValidAmount('0', false);
+ assertValidAmount('0.00', false);
+ assertValidAmount('00.00', false);
+ assertValidAmount('3', true);
+ assertValidAmount('12.34', true);
+ assertValidAmount('278', true);
+ assertValidAmount('278.91', true);
+ assertValidAmount('0.14', true);
});
- it("displays validation errors", function() {
+ it('displays validation errors', function() {
// Attempt to submit an invalid donation amount
- view.$amount.val("");
+ view.$amount.val('');
view.donate();
// Verify that the amount field is marked as having a validation error
- expect(view.$amount).toHaveClass("validation-error");
+ expect(view.$amount).toHaveClass('validation-error');
// Verify that the error message appears
- expect(view.$errorMsg.text()).toEqual("Please enter a valid donation amount.");
+ expect(view.$errorMsg.text()).toEqual('Please enter a valid donation amount.');
// Expect that the submit button is re-enabled to allow users to submit again
- expect(view.$submit).not.toHaveClass("disabled");
+ expect(view.$submit).not.toHaveClass('disabled');
// Try again, this time submitting a valid amount
view.$amount.val(AMOUNT);
view.donate();
// Expect that the errors are cleared
- expect(view.$errorMsg.text()).toEqual("");
+ expect(view.$errorMsg.text()).toEqual('');
// Expect that the submit button is disabled
- expect(view.$submit).toHaveClass("disabled");
+ expect(view.$submit).toHaveClass('disabled');
});
- it("displays an error when the server cannot be contacted", function() {
+ it('displays an error when the server cannot be contacted', function() {
// Spy on AJAX requests
requests = AjaxHelpers.requests(this);
@@ -128,16 +127,16 @@ define(['common/js/spec_helpers/template_helpers',
AjaxHelpers.respondWithError(requests);
// Expect that the error is displayed
- expect(view.$errorMsg.text()).toEqual("Your donation could not be submitted.");
+ expect(view.$errorMsg.text()).toEqual('Your donation could not be submitted.');
// Verify that the submit button is re-enabled
// so users can try again.
- expect(view.$submit).not.toHaveClass("disabled");
+ expect(view.$submit).not.toHaveClass('disabled');
});
- it("disables the submit button once the user donates", function() {
+ it('disables the submit button once the user donates', function() {
// Before we submit, the button should be enabled
- expect(view.$submit).not.toHaveClass("disabled");
+ expect(view.$submit).not.toHaveClass('disabled');
// Simulate starting a donation
// Since we're not simulating the AJAX response, this will block
@@ -145,10 +144,10 @@ define(['common/js/spec_helpers/template_helpers',
view.donate();
// Verify that the submit button is disabled
- expect(view.$submit).toHaveClass("disabled");
+ expect(view.$submit).toHaveClass('disabled');
});
- it("sends an analytics event when the user submits a donation", function() {
+ it('sends an analytics event when the user submits a donation', function() {
// Simulate the submission to the payment processor
// We skip the intermediary steps here by passing in
// the payment url and parameters,
@@ -160,13 +159,13 @@ define(['common/js/spec_helpers/template_helpers',
// Verify that the analytics event was fired
expect(window.analytics.track).toHaveBeenCalledWith(
- "edx.bi.user.payment_processor.visited",
+ 'edx.bi.user.payment_processor.visited',
{
- category: "donations",
+ category: 'donations',
label: COURSE_ID
}
);
});
});
}
-);
\ No newline at end of file
+);
diff --git a/lms/static/js/spec/dashboard/dropdown_spec.js b/lms/static/js/spec/dashboard/dropdown_spec.js
index b3b63a3a5a..1eeaf388b4 100644
--- a/lms/static/js/spec/dashboard/dropdown_spec.js
+++ b/lms/static/js/spec/dashboard/dropdown_spec.js
@@ -15,7 +15,7 @@ define(['js/dashboard/dropdown', 'jquery.simulate'],
expect($(dropdownSelector)).not.toBeVisible();
},
waitForElementToBeFocused = function(element, done) {
- jasmine.waitUntil(function () {
+ jasmine.waitUntil(function() {
return element === document.activeElement;
}).always(done);
},
@@ -25,55 +25,54 @@ define(['js/dashboard/dropdown', 'jquery.simulate'],
verifyDropdownVisible();
},
keydown = function(keyInfo) {
- $(document.activeElement).simulate("keydown", keyInfo);
+ $(document.activeElement).simulate('keydown', keyInfo);
};
- describe("edx.dashboard.dropdown.toggleCourseActionsDropdownMenu", function() {
-
+ describe('edx.dashboard.dropdown.toggleCourseActionsDropdownMenu', function() {
beforeEach(function() {
loadFixtures('js/fixtures/dashboard/dashboard.html');
window.edx.dashboard.dropdown.bindToggleButtons();
});
- it("Clicking the .action-more button toggles the menu", function() {
+ it('Clicking the .action-more button toggles the menu', function() {
verifyDropdownNotVisible();
clickToggleButton();
verifyDropdownVisible();
clickToggleButton();
verifyDropdownNotVisible();
});
- it("ESCAPE will close dropdown and return focus to the button", function(done) {
+ it('ESCAPE will close dropdown and return focus to the button', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.ESCAPE });
+ keydown({keyCode: keys.ESCAPE});
verifyDropdownNotVisible();
waitForElementToBeFocused($(toggleButtonSelector)[0], done);
});
- it("SPACE will close dropdown and return focus to the button", function(done) {
+ it('SPACE will close dropdown and return focus to the button', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.SPACE });
+ keydown({keyCode: keys.SPACE});
verifyDropdownNotVisible();
waitForElementToBeFocused($(toggleButtonSelector)[0], done);
});
- describe("Focus is trapped when navigating with", function() {
- it("TAB key", function(done) {
+ describe('Focus is trapped when navigating with', function() {
+ it('TAB key', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.TAB });
+ keydown({keyCode: keys.TAB});
waitForElementToBeFocused($(dropdownItemSelector)[0], done);
});
- it("DOWN key", function(done) {
+ it('DOWN key', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.DOWN });
+ keydown({keyCode: keys.DOWN});
waitForElementToBeFocused($(dropdownItemSelector)[0], done);
});
- it("TAB key + SHIFT key", function(done) {
+ it('TAB key + SHIFT key', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.TAB, shiftKey: true });
+ keydown({keyCode: keys.TAB, shiftKey: true});
waitForElementToBeFocused($(dropdownItemSelector)[1], done);
});
- it("UP key", function(done) {
+ it('UP key', function(done) {
openDropDownMenu();
- keydown({ keyCode: keys.UP });
+ keydown({keyCode: keys.UP});
waitForElementToBeFocused($(dropdownItemSelector)[1], done);
});
});
diff --git a/lms/static/js/spec/dashboard/track_events_spec.js b/lms/static/js/spec/dashboard/track_events_spec.js
index f1732eb5e3..72df81a5a9 100644
--- a/lms/static/js/spec/dashboard/track_events_spec.js
+++ b/lms/static/js/spec/dashboard/track_events_spec.js
@@ -1,11 +1,10 @@
-(function (define) {
+(function(define) {
'use strict';
define([
'jquery',
'js/dashboard/track_events'
],
function($) {
-
describe('edx.dashboard.trackEvents', function() {
beforeEach(function() {
// Stub the analytics event tracker
@@ -71,7 +70,7 @@
window.edx.dashboard.trackLearnVerifiedLinkClicked(
$learnVerified,
window.edx.dashboard.generateTrackProperties);
- //Verify that analytics events fire when the 'Learned about verified track' link is clicked.
+ // Verify that analytics events fire when the 'Learned about verified track' link is clicked.
expect(window.analytics.trackLink).toHaveBeenCalledWith(
$learnVerified,
'edx.bi.dashboard.verified_info_link.clicked',
@@ -93,31 +92,6 @@
property
);
});
-
- it('sends an analytics event when the user clicks the \'View XSeries Details\' button', function() {
- var $xseries = $('.xseries-action .btn');
- window.edx.dashboard.trackXseriesBtnClicked(
- $xseries,
- window.edx.dashboard.generateProgramProperties);
-
- expect(window.analytics.trackLink).toHaveBeenCalledWith(
- $xseries,
- 'edx.bi.dashboard.xseries_cta_message.clicked',
- window.edx.dashboard.generateProgramProperties
- );
- });
-
- it('sends an analytics event when xseries messages are present in the DOM on page load', function() {
- window.edx.dashboard.xseriesTrackMessages();
- expect(window.analytics.track).toHaveBeenCalledWith(
- 'edx.bi.dashboard.xseries_cta_message.viewed',
- {
- category: 'dashboard',
- course_id: 'CTB3365DWx',
- program_id: 'xseries007'
- }
- );
- });
});
});
}).call(this, window.define);
diff --git a/lms/static/js/spec/discovery/collections/filters_spec.js b/lms/static/js/spec/discovery/collections/filters_spec.js
index c13ec2c867..af7aa1b210 100644
--- a/lms/static/js/spec/discovery/collections/filters_spec.js
+++ b/lms/static/js/spec/discovery/collections/filters_spec.js
@@ -1,22 +1,19 @@
define(['js/discovery/collections/filters'], function(Filters) {
'use strict';
- describe('discovery.collections.Filters', function () {
-
- beforeEach(function () {
+ describe('discovery.collections.Filters', function() {
+ beforeEach(function() {
this.filters = new Filters([
- { type: 'org', query: 'edX', name: 'edX'},
- { type: 'language', query: 'en', name: 'English'}
+ {type: 'org', query: 'edX', name: 'edX'},
+ {type: 'language', query: 'en', name: 'English'}
]);
});
- it('converts to a dictionary', function () {
+ it('converts to a dictionary', function() {
expect(this.filters.getTerms()).toEqual({
org: 'edX',
language: 'en'
});
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/discovery_factory_spec.js b/lms/static/js/spec/discovery/discovery_factory_spec.js
index 2c84cb2397..7432e27500 100644
--- a/lms/static/js/spec/discovery/discovery_factory_spec.js
+++ b/lms/static/js/spec/discovery/discovery_factory_spec.js
@@ -1,5 +1,5 @@
define([
- 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers','common/js/spec_helpers/template_helpers',
+ 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'common/js/spec_helpers/template_helpers',
'js/discovery/discovery_factory'
], function($, AjaxHelpers, TemplateHelpers, DiscoveryFactory) {
'use strict';
@@ -9,7 +9,7 @@ define([
org: {
name: 'Organization',
terms: {
- edX1: "edX_1"
+ edX1: 'edX_1'
}
},
modes: {
@@ -29,75 +29,74 @@ define([
var JSON_RESPONSE = {
- "total": 365,
- "results": [
+ 'total': 365,
+ 'results': [
{
- "data": {
- "modes": [
- "honor"
+ 'data': {
+ 'modes': [
+ 'honor'
],
- "course": "edX/DemoX/Demo_Course",
- "enrollment_start": "2015-04-21T00:00:00+00:00",
- "number": "DemoX",
- "content": {
- "overview": " About This Course Include your long course description here.",
- "display_name": "edX Demonstration Course",
- "number": "DemoX"
+ 'course': 'edX/DemoX/Demo_Course',
+ 'enrollment_start': '2015-04-21T00:00:00+00:00',
+ 'number': 'DemoX',
+ 'content': {
+ 'overview': ' About This Course Include your long course description here.',
+ 'display_name': 'edX Demonstration Course',
+ 'number': 'DemoX'
},
- "start": "1970-01-01T05:00:00+00:00",
- "image_url": "/c4x/edX/DemoX/asset/images_course_image.jpg",
- "org": "edX",
- "id": "edX/DemoX/Demo_Course"
+ 'start': '1970-01-01T05:00:00+00:00',
+ 'image_url': '/c4x/edX/DemoX/asset/images_course_image.jpg',
+ 'org': 'edX',
+ 'id': 'edX/DemoX/Demo_Course'
}
}
],
- "facets": {
- "org": {
- "total": 26,
- "terms": {
- "edX1": 1,
- "edX2": 1,
- "edX3": 1,
- "edX4": 1,
- "edX5": 1,
- "edX6": 1,
- "edX7": 1,
- "edX8": 1,
- "edX9": 1,
- "edX10": 1,
- "edX11": 1,
- "edX12": 1,
- "edX13": 1,
- "edX14": 1,
- "edX15": 1,
- "edX16": 1,
- "edX17": 1,
- "edX18": 1,
- "edX19": 1,
- "edX20": 1,
- "edX21": 1,
- "edX22": 1,
- "edX23": 1,
- "edX24": 1,
- "edX25": 1,
- "edX26": 1
+ 'facets': {
+ 'org': {
+ 'total': 26,
+ 'terms': {
+ 'edX1': 1,
+ 'edX2': 1,
+ 'edX3': 1,
+ 'edX4': 1,
+ 'edX5': 1,
+ 'edX6': 1,
+ 'edX7': 1,
+ 'edX8': 1,
+ 'edX9': 1,
+ 'edX10': 1,
+ 'edX11': 1,
+ 'edX12': 1,
+ 'edX13': 1,
+ 'edX14': 1,
+ 'edX15': 1,
+ 'edX16': 1,
+ 'edX17': 1,
+ 'edX18': 1,
+ 'edX19': 1,
+ 'edX20': 1,
+ 'edX21': 1,
+ 'edX22': 1,
+ 'edX23': 1,
+ 'edX24': 1,
+ 'edX25': 1,
+ 'edX26': 1
},
- "other": 0
+ 'other': 0
},
- "modes": {
- "total": 1,
- "terms": {
- "honor": 1
+ 'modes': {
+ 'total': 1,
+ 'terms': {
+ 'honor': 1
},
- "other": 0
+ 'other': 0
}
}
};
- describe('discovery.DiscoveryFactory', function () {
-
- beforeEach(function () {
+ describe('discovery.DiscoveryFactory', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/discovery.html');
TemplateHelpers.installTemplates([
'templates/discovery/course_card',
@@ -111,11 +110,11 @@ define([
jasmine.clock().install();
});
- afterEach(function () {
+ afterEach(function() {
jasmine.clock().uninstall();
});
- it('does search', function () {
+ it('does search', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('test');
$('.discovery-submit').trigger('click');
@@ -125,7 +124,7 @@ define([
expect($('.active-filter').length).toBe(1);
});
- it('loads more', function () {
+ it('loads more', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('test');
@@ -143,7 +142,7 @@ define([
expect($('.courses-listing article').length).toEqual(2);
});
- it('displays not found message', function () {
+ it('displays not found message', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('asdfasdf');
$('.discovery-submit').trigger('click');
@@ -153,7 +152,7 @@ define([
expect($('.courses-listing')).toBeEmpty();
});
- it('displays error message', function () {
+ it('displays error message', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('asdfasdf');
$('.discovery-submit').trigger('click');
@@ -162,7 +161,7 @@ define([
expect($('.courses-listing')).toBeEmpty();
});
- it('check filters and bar removed on clear all', function () {
+ it('check filters and bar removed on clear all', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('test');
$('.discovery-submit').trigger('click');
@@ -174,7 +173,7 @@ define([
expect($('#filter-bar')).toHaveClass('is-collapsed');
});
- it('check filters and bar removed on last filter cleared', function () {
+ it('check filters and bar removed on last filter cleared', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('test');
$('.discovery-submit').trigger('click');
@@ -185,7 +184,7 @@ define([
expect($('.active-filter').length).toBe(0);
});
- it('filter results by named facet', function () {
+ it('filter results by named facet', function() {
var requests = AjaxHelpers.requests(this);
$('.discovery-input').val('test');
$('.discovery-submit').trigger('click');
@@ -197,8 +196,5 @@ define([
$('.search-facets li [data-value="edX1"]').trigger('click');
expect($('.active-filter [data-value="edX1"]').length).toBe(0);
});
-
});
-
-
});
diff --git a/lms/static/js/spec/discovery/models/course_card_spec.js b/lms/static/js/spec/discovery/models/course_card_spec.js
index 6af3281e27..c1b80a28c4 100644
--- a/lms/static/js/spec/discovery/models/course_card_spec.js
+++ b/lms/static/js/spec/discovery/models/course_card_spec.js
@@ -1,13 +1,12 @@
define(['js/discovery/models/course_card'], function(CourseCard) {
'use strict';
- describe('discovery.models.CourseCard', function () {
-
- beforeEach(function () {
+ describe('discovery.models.CourseCard', function() {
+ beforeEach(function() {
this.card = new CourseCard();
});
- it('has properties', function () {
+ it('has properties', function() {
expect(this.card.get('modes')).toBeDefined();
expect(this.card.get('course')).toBeDefined();
expect(this.card.get('enrollment_start')).toBeDefined();
@@ -22,7 +21,5 @@ define(['js/discovery/models/course_card'], function(CourseCard) {
expect(this.card.get('org')).toBeDefined();
expect(this.card.get('id')).toBeDefined();
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/models/course_directory_spec.js b/lms/static/js/spec/discovery/models/course_directory_spec.js
index 9867529eac..ad7368ed68 100644
--- a/lms/static/js/spec/discovery/models/course_directory_spec.js
+++ b/lms/static/js/spec/discovery/models/course_directory_spec.js
@@ -5,97 +5,94 @@ define([
var JSON_RESPONSE = {
- "total": 365,
- "results": [
+ 'total': 365,
+ 'results': [
{
- "data": {
- "modes": [
- "honor"
+ 'data': {
+ 'modes': [
+ 'honor'
],
- "course": "edX/DemoX/Demo_Course",
- "enrollment_start": "2015-04-21T00:00:00+00:00",
- "number": "DemoX",
- "content": {
- "overview": " About This Course Include your long course description here.",
- "display_name": "edX Demonstration Course",
- "number": "DemoX"
+ 'course': 'edX/DemoX/Demo_Course',
+ 'enrollment_start': '2015-04-21T00:00:00+00:00',
+ 'number': 'DemoX',
+ 'content': {
+ 'overview': ' About This Course Include your long course description here.',
+ 'display_name': 'edX Demonstration Course',
+ 'number': 'DemoX'
},
- "start": "1970-01-01T05:00:00+00:00",
- "image_url": "/c4x/edX/DemoX/asset/images_course_image.jpg",
- "org": "edX",
- "id": "edX/DemoX/Demo_Course"
+ 'start': '1970-01-01T05:00:00+00:00',
+ 'image_url': '/c4x/edX/DemoX/asset/images_course_image.jpg',
+ 'org': 'edX',
+ 'id': 'edX/DemoX/Demo_Course'
}
}
],
- "facets": {
- "org": {
- "total": 26,
- "terms": {
- "edX1": 1,
- "edX2": 1,
- "edX3": 1,
- "edX4": 1,
- "edX5": 1,
- "edX6": 1,
- "edX7": 1,
- "edX8": 1,
- "edX9": 1,
- "edX10": 1,
- "edX11": 1,
- "edX12": 1,
- "edX13": 1,
- "edX14": 1,
- "edX15": 1,
- "edX16": 1,
- "edX17": 1,
- "edX18": 1,
- "edX19": 1,
- "edX20": 1,
- "edX21": 1,
- "edX22": 1,
- "edX23": 1,
- "edX24": 1,
- "edX25": 1,
- "edX26": 1
+ 'facets': {
+ 'org': {
+ 'total': 26,
+ 'terms': {
+ 'edX1': 1,
+ 'edX2': 1,
+ 'edX3': 1,
+ 'edX4': 1,
+ 'edX5': 1,
+ 'edX6': 1,
+ 'edX7': 1,
+ 'edX8': 1,
+ 'edX9': 1,
+ 'edX10': 1,
+ 'edX11': 1,
+ 'edX12': 1,
+ 'edX13': 1,
+ 'edX14': 1,
+ 'edX15': 1,
+ 'edX16': 1,
+ 'edX17': 1,
+ 'edX18': 1,
+ 'edX19': 1,
+ 'edX20': 1,
+ 'edX21': 1,
+ 'edX22': 1,
+ 'edX23': 1,
+ 'edX24': 1,
+ 'edX25': 1,
+ 'edX26': 1
},
- "other": 0
+ 'other': 0
},
- "modes": {
- "total": 1,
- "terms": {
- "honor": 1
+ 'modes': {
+ 'total': 1,
+ 'terms': {
+ 'honor': 1
},
- "other": 0
+ 'other': 0
}
}
};
- describe('discovery.models.CourseDiscovery', function () {
-
- beforeEach(function () {
+ describe('discovery.models.CourseDiscovery', function() {
+ beforeEach(function() {
var requests = AjaxHelpers.requests(this);
this.discovery = new CourseDiscovery();
this.discovery.fetch();
AjaxHelpers.respondWithJson(requests, JSON_RESPONSE);
});
- it('parses server response', function () {
+ it('parses server response', function() {
expect(this.discovery.courseCards.length).toBe(1);
expect(this.discovery.facetOptions.length).toBe(27);
});
- it('resets collections', function () {
+ it('resets collections', function() {
this.discovery.reset();
expect(this.discovery.courseCards.length).toBe(0);
expect(this.discovery.facetOptions.length).toBe(0);
});
- it('returns latest course cards', function () {
+ it('returns latest course cards', function() {
var latest = this.discovery.latest();
expect(latest.length).toBe(1);
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/models/facet_option_spec.js b/lms/static/js/spec/discovery/models/facet_option_spec.js
index 45ddef797b..1f7785dfb0 100644
--- a/lms/static/js/spec/discovery/models/facet_option_spec.js
+++ b/lms/static/js/spec/discovery/models/facet_option_spec.js
@@ -1,19 +1,16 @@
define(['js/discovery/models/facet_option'], function(FacetOption) {
'use strict';
- describe('discovery.models.FacetOption', function () {
-
- beforeEach(function () {
+ describe('discovery.models.FacetOption', function() {
+ beforeEach(function() {
this.filter = new FacetOption();
});
- it('has properties', function () {
+ it('has properties', function() {
expect(this.filter.get('facet')).toBeDefined();
expect(this.filter.get('term')).toBeDefined();
expect(this.filter.get('count')).toBeDefined();
expect(this.filter.get('selected')).toBeDefined();
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/models/filter_spec.js b/lms/static/js/spec/discovery/models/filter_spec.js
index b21683766b..a0958844d4 100644
--- a/lms/static/js/spec/discovery/models/filter_spec.js
+++ b/lms/static/js/spec/discovery/models/filter_spec.js
@@ -1,16 +1,15 @@
define(['js/discovery/models/filter'], function(Filter) {
'use strict';
- describe('discovery.models.Filter', function () {
- beforeEach(function () {
+ describe('discovery.models.Filter', function() {
+ beforeEach(function() {
this.filter = new Filter();
});
- it('has properties', function () {
+ it('has properties', function() {
expect(this.filter.get('type')).toBeDefined();
expect(this.filter.get('query')).toBeDefined();
expect(this.filter.get('name')).toBeDefined();
});
});
-
});
diff --git a/lms/static/js/spec/discovery/models/search_state_spec.js b/lms/static/js/spec/discovery/models/search_state_spec.js
index 12c9cdcd79..92f4e8f31b 100644
--- a/lms/static/js/spec/discovery/models/search_state_spec.js
+++ b/lms/static/js/spec/discovery/models/search_state_spec.js
@@ -5,33 +5,32 @@ define([
var JSON_RESPONSE = {
- "total": 365,
- "results": [
+ 'total': 365,
+ 'results': [
{
- "data": {
- "modes": [
- "honor"
+ 'data': {
+ 'modes': [
+ 'honor'
],
- "course": "edX/DemoX/Demo_Course",
- "enrollment_start": "2015-04-21T00:00:00+00:00",
- "number": "DemoX",
- "content": {
- "overview": " About This Course Include your long course description here.",
- "display_name": "edX Demonstration Course",
- "number": "DemoX"
+ 'course': 'edX/DemoX/Demo_Course',
+ 'enrollment_start': '2015-04-21T00:00:00+00:00',
+ 'number': 'DemoX',
+ 'content': {
+ 'overview': ' About This Course Include your long course description here.',
+ 'display_name': 'edX Demonstration Course',
+ 'number': 'DemoX'
},
- "start": "1970-01-01T05:00:00+00:00",
- "image_url": "/c4x/edX/DemoX/asset/images_course_image.jpg",
- "org": "edX",
- "id": "edX/DemoX/Demo_Course"
+ 'start': '1970-01-01T05:00:00+00:00',
+ 'image_url': '/c4x/edX/DemoX/asset/images_course_image.jpg',
+ 'org': 'edX',
+ 'id': 'edX/DemoX/Demo_Course'
}
}
]
};
- describe('discovery.models.SearchState', function () {
-
- beforeEach(function () {
+ describe('discovery.models.SearchState', function() {
+ beforeEach(function() {
this.search = new SearchState();
this.onSearch = jasmine.createSpy('onSearch');
this.onNext = jasmine.createSpy('onNext');
@@ -41,25 +40,25 @@ define([
this.search.on('error', this.onError);
});
- it('perform search', function () {
+ it('perform search', function() {
var requests = AjaxHelpers.requests(this);
this.search.performSearch('dummy');
AjaxHelpers.respondWithJson(requests, JSON_RESPONSE);
expect(this.onSearch).toHaveBeenCalledWith('dummy', 365);
expect(this.search.discovery.courseCards.length).toBe(1);
- this.search.refineSearch({ modes: 'honor' });
+ this.search.refineSearch({modes: 'honor'});
AjaxHelpers.respondWithJson(requests, JSON_RESPONSE);
expect(this.onSearch).toHaveBeenCalledWith('dummy', 365);
});
- it('returns an error', function () {
+ it('returns an error', function() {
var requests = AjaxHelpers.requests(this);
this.search.performSearch('');
AjaxHelpers.respondWithError(requests, 500);
expect(this.onError).toHaveBeenCalled();
});
- it('loads next page', function () {
+ it('loads next page', function() {
var requests = AjaxHelpers.requests(this);
this.search.performSearch('dummy');
AjaxHelpers.respondWithJson(requests, JSON_RESPONSE);
@@ -68,11 +67,11 @@ define([
expect(this.onNext).toHaveBeenCalled();
});
- it('shows all results when there are none', function () {
+ it('shows all results when there are none', function() {
var requests = AjaxHelpers.requests(this);
- this.search.performSearch('dummy', { modes: 'SomeOption' });
+ this.search.performSearch('dummy', {modes: 'SomeOption'});
// no results
- AjaxHelpers.respondWithJson(requests, { total: 0 });
+ AjaxHelpers.respondWithJson(requests, {total: 0});
expect(this.onSearch).not.toHaveBeenCalled();
// there should be another Ajax call to fetch all courses
AjaxHelpers.respondWithJson(requests, JSON_RESPONSE);
@@ -80,11 +79,9 @@ define([
// new search
this.search.performSearch('something');
// no results
- AjaxHelpers.respondWithJson(requests, { total: 0 });
+ AjaxHelpers.respondWithJson(requests, {total: 0});
// should load cached results
expect(this.onSearch).toHaveBeenCalledWith('dummy', 0);
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/course_card_spec.js b/lms/static/js/spec/discovery/views/course_card_spec.js
index 97f49a09c2..ab093672ec 100644
--- a/lms/static/js/spec/discovery/views/course_card_spec.js
+++ b/lms/static/js/spec/discovery/views/course_card_spec.js
@@ -6,33 +6,32 @@ define([
var JSON_RESPONSE = {
- "total": 365,
- "results": [
+ 'total': 365,
+ 'results': [
{
- "data": {
- "modes": [
- "honor"
+ 'data': {
+ 'modes': [
+ 'honor'
],
- "course": "edX/DemoX/Demo_Course",
- "enrollment_start": "2015-04-21T00:00:00+00:00",
- "number": "DemoX",
- "content": {
- "overview": " About This Course Include your long course description here.",
- "display_name": "edX Demonstration Course",
- "number": "DemoX"
+ 'course': 'edX/DemoX/Demo_Course',
+ 'enrollment_start': '2015-04-21T00:00:00+00:00',
+ 'number': 'DemoX',
+ 'content': {
+ 'overview': ' About This Course Include your long course description here.',
+ 'display_name': 'edX Demonstration Course',
+ 'number': 'DemoX'
},
- "start": "1970-01-01T05:00:00+00:00",
- "image_url": "/c4x/edX/DemoX/asset/images_course_image.jpg",
- "org": "edX",
- "id": "edX/DemoX/Demo_Course"
+ 'start': '1970-01-01T05:00:00+00:00',
+ 'image_url': '/c4x/edX/DemoX/asset/images_course_image.jpg',
+ 'org': 'edX',
+ 'id': 'edX/DemoX/Demo_Course'
}
}
]
};
- describe('discovery.views.CourseCard', function () {
-
- beforeEach(function () {
+ describe('discovery.views.CourseCard', function() {
+ beforeEach(function() {
TemplateHelpers.installTemplate('templates/discovery/course_card');
this.view = new CourseCardView({
model: new CourseCard(JSON_RESPONSE.results[0].data)
@@ -40,7 +39,7 @@ define([
this.view.render();
});
- it('renders', function () {
+ it('renders', function() {
var data = this.view.model.attributes;
expect(this.view.$el).toContainHtml(data.content.display_name);
expect(this.view.$el).toContainElement('a[href="/courses/' + data.course + '/about"]');
@@ -50,7 +49,5 @@ define([
expect(this.view.$el.find('.course-name')).toContainHtml(data.content.display_name);
expect(this.view.$el.find('.course-date')).toContainHtml('Jan 01, 1970');
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/courses_listing_spec.js b/lms/static/js/spec/discovery/views/courses_listing_spec.js
index 0001561773..269d831a6f 100644
--- a/lms/static/js/spec/discovery/views/courses_listing_spec.js
+++ b/lms/static/js/spec/discovery/views/courses_listing_spec.js
@@ -6,53 +6,52 @@ define([
var JSON_RESPONSE = {
- "total": 365,
- "results": [
+ 'total': 365,
+ 'results': [
{
- "data": {
- "modes": [
- "honor"
+ 'data': {
+ 'modes': [
+ 'honor'
],
- "course": "edX/DemoX/Demo_Course",
- "enrollment_start": "2015-04-21T00:00:00+00:00",
- "number": "DemoX",
- "content": {
- "overview": " About This Course Include your long course description here.",
- "display_name": "edX Demonstration Course",
- "number": "DemoX"
+ 'course': 'edX/DemoX/Demo_Course',
+ 'enrollment_start': '2015-04-21T00:00:00+00:00',
+ 'number': 'DemoX',
+ 'content': {
+ 'overview': ' About This Course Include your long course description here.',
+ 'display_name': 'edX Demonstration Course',
+ 'number': 'DemoX'
},
- "start": "1970-01-01T05:00:00+00:00",
- "image_url": "/c4x/edX/DemoX/asset/images_course_image.jpg",
- "org": "edX",
- "id": "edX/DemoX/Demo_Course"
+ 'start': '1970-01-01T05:00:00+00:00',
+ 'image_url': '/c4x/edX/DemoX/asset/images_course_image.jpg',
+ 'org': 'edX',
+ 'id': 'edX/DemoX/Demo_Course'
}
}
]
};
- describe('discovery.views.CoursesListing', function () {
-
- beforeEach(function () {
+ describe('discovery.views.CoursesListing', function() {
+ beforeEach(function() {
jasmine.clock().install();
loadFixtures('js/fixtures/discovery.html');
TemplateHelpers.installTemplate('templates/discovery/course_card');
var collection = new Backbone.Collection(
[JSON_RESPONSE.results[0].data],
- { model: CourseCard }
+ {model: CourseCard}
);
var mock = {
collection: collection,
- latest: function () { return this.collection.last(20); }
+ latest: function() { return this.collection.last(20); }
};
- this.view = new CoursesListing({ model: mock });
+ this.view = new CoursesListing({model: mock});
});
afterEach(function() {
jasmine.clock().uninstall();
});
- it('renders search results', function () {
+ it('renders search results', function() {
this.view.render();
expect($('.courses-listing article').length).toEqual(1);
expect($('.courses-listing .course-title')).toContainHtml('edX Demonstration Course');
@@ -60,7 +59,7 @@ define([
expect($('.courses-listing article').length).toEqual(2);
});
- it('scrolling triggers an event for next page', function () {
+ it('scrolling triggers an event for next page', function() {
this.onNext = jasmine.createSpy('onNext');
this.view.on('next', this.onNext);
this.view.render();
@@ -74,7 +73,5 @@ define([
jasmine.clock().tick(500);
expect(this.onNext.calls.count()).toEqual(1);
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/filter_bar_spec.js b/lms/static/js/spec/discovery/views/filter_bar_spec.js
index 802569c13c..2818c21d98 100644
--- a/lms/static/js/spec/discovery/views/filter_bar_spec.js
+++ b/lms/static/js/spec/discovery/views/filter_bar_spec.js
@@ -4,16 +4,15 @@ define([
], function($, TemplateHelpers, Filters, FilterBar) {
'use strict';
- describe('discovery.views.FilterBar', function () {
-
- beforeEach(function () {
+ describe('discovery.views.FilterBar', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/discovery.html');
TemplateHelpers.installTemplates([
'templates/discovery/filter',
'templates/discovery/filter_bar'
]);
this.filters = new Filters();
- this.filterBar = new FilterBar({ collection: this.filters });
+ this.filterBar = new FilterBar({collection: this.filters});
this.filters.add({
type: 'org',
query: 'edX',
@@ -21,23 +20,23 @@ define([
});
});
- it('adds filter', function () {
+ it('adds filter', function() {
expect(this.filterBar.$el.find('button')).toHaveData('type', 'org');
});
- it('removes filter', function () {
+ it('removes filter', function() {
this.filters.remove('org');
expect(this.filterBar.$el.find('ul')).toBeEmpty();
expect(this.filterBar.$el).toHaveClass('is-collapsed');
});
- it('resets filters', function () {
+ it('resets filters', function() {
this.filters.reset();
expect(this.filterBar.$el.find('ul')).toBeEmpty();
expect(this.filterBar.$el).toHaveClass('is-collapsed');
});
- it('triggers events', function () {
+ it('triggers events', function() {
this.onClearFilter = jasmine.createSpy('onClearFilter');
this.onClearAll = jasmine.createSpy('onClearAll');
this.filterBar.on('clearFilter', this.onClearFilter);
@@ -47,7 +46,5 @@ define([
this.filterBar.$el.find('#clear-all-filters').click();
expect(this.onClearAll).toHaveBeenCalled();
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/filter_label_spec.js b/lms/static/js/spec/discovery/views/filter_label_spec.js
index bd1238d61f..86f712cafb 100644
--- a/lms/static/js/spec/discovery/views/filter_label_spec.js
+++ b/lms/static/js/spec/discovery/views/filter_label_spec.js
@@ -4,9 +4,8 @@ define([
], function($, TemplateHelpers, Filter, FilterLabel) {
'use strict';
- describe('discovery.views.FilterLabel', function () {
-
- beforeEach(function () {
+ describe('discovery.views.FilterLabel', function() {
+ beforeEach(function() {
TemplateHelpers.installTemplate('templates/discovery/filter');
var filter = new Filter({
type: 'language',
@@ -17,24 +16,22 @@ define([
this.view.render();
});
- it('renders', function () {
+ it('renders', function() {
var data = this.view.model.attributes;
expect(this.view.$el.find('button')).toHaveData('value', 'en');
expect(this.view.$el.find('button')).toHaveData('type', 'language');
expect(this.view.$el).toContainHtml(data.name);
});
- it('renders changes', function () {
+ it('renders changes', function() {
this.view.model.set('query', 'es');
expect(this.view.$el.find('button')).toHaveData('value', 'es');
});
- it('removes itself', function () {
+ it('removes itself', function() {
// simulate removing from collection
this.view.model.trigger('remove');
expect(this.view.$el).not.toExist();
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/refine_sidebar_spec.js b/lms/static/js/spec/discovery/views/refine_sidebar_spec.js
index d20215f3df..fb3cb48c3d 100644
--- a/lms/static/js/spec/discovery/views/refine_sidebar_spec.js
+++ b/lms/static/js/spec/discovery/views/refine_sidebar_spec.js
@@ -8,7 +8,7 @@ define([
org: {
name: 'Organization',
terms: {
- edX1: "edX_1"
+ edX1: 'edX_1'
}
},
modes: {
@@ -27,39 +27,37 @@ define([
};
- describe('discovery.views.RefineSidebar', function () {
-
- beforeEach(function () {
+ describe('discovery.views.RefineSidebar', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/discovery.html');
TemplateHelpers.installTemplates([
'templates/discovery/facet',
'templates/discovery/facet_option'
]);
- this.facetOptions = new Backbone.Collection([], { model: FacetOption });
+ this.facetOptions = new Backbone.Collection([], {model: FacetOption});
this.facetOptions.add([
- { facet: 'language', term: 'es', count: 12 },
- { facet: 'language', term: 'en', count: 10 },
- { facet: 'modes', term: 'honor', count: 2, selected: true }
+ {facet: 'language', term: 'es', count: 12},
+ {facet: 'language', term: 'en', count: 10},
+ {facet: 'modes', term: 'honor', count: 2, selected: true}
]);
- this.sidebar = new RefineSidebar({ collection: this.facetOptions, meanings: MEANINGS });
+ this.sidebar = new RefineSidebar({collection: this.facetOptions, meanings: MEANINGS});
this.sidebar.render();
-
});
- it('styles active filter', function () {
+ it('styles active filter', function() {
expect(this.sidebar.$el.find('button.selected')).toHaveData('facet', 'modes');
});
- it('styles active filter', function () {
+ it('styles active filter', function() {
this.onSelect = jasmine.createSpy('onSelect');
this.sidebar.on('selectOption', this.onSelect);
this.sidebar.$el.find('button[data-value="en"]').click();
expect(this.onSelect).toHaveBeenCalledWith('language', 'en', 'English');
});
- it('expands and collapses facet', function () {
- var options = _.range(20).map(function (number) {
- return { facet: 'org', term: 'test' + number, count: 1 };
+ it('expands and collapses facet', function() {
+ var options = _.range(20).map(function(number) {
+ return {facet: 'org', term: 'test' + number, count: 1};
});
this.facetOptions.reset(options);
this.sidebar.render();
@@ -70,8 +68,6 @@ define([
expect(this.sidebar.$el.find('ul.facet-list')).toHaveClass('collapse');
expect(this.sidebar.$el.find('.show-less')).toHaveClass('hidden');
});
-
});
-
});
diff --git a/lms/static/js/spec/discovery/views/search_form_spec.js b/lms/static/js/spec/discovery/views/search_form_spec.js
index 4d77c44e25..25bdfcbfdb 100644
--- a/lms/static/js/spec/discovery/views/search_form_spec.js
+++ b/lms/static/js/spec/discovery/views/search_form_spec.js
@@ -1,23 +1,22 @@
define(['jquery', 'js/discovery/views/search_form'], function($, SearchForm) {
'use strict';
- describe('discovery.views.SearchForm', function () {
-
- beforeEach(function () {
+ describe('discovery.views.SearchForm', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/discovery.html');
this.form = new SearchForm();
this.onSearch = jasmine.createSpy('onSearch');
this.form.on('search', this.onSearch);
});
- it('trims input string', function () {
+ it('trims input string', function() {
var term = ' search string ';
$('.discovery-input').val(term);
$('form').trigger('submit');
expect(this.onSearch).toHaveBeenCalledWith($.trim(term));
});
- it('handles calls to doSearch', function () {
+ it('handles calls to doSearch', function() {
var term = ' search string ';
$('.discovery-input').val(term);
this.form.doSearch(term);
@@ -26,20 +25,20 @@ define(['jquery', 'js/discovery/views/search_form'], function($, SearchForm) {
expect($('#discovery-message')).toBeEmpty();
});
- it('clears search', function () {
+ it('clears search', function() {
$('.discovery-input').val('somethig');
this.form.clearSearch();
expect($('.discovery-input').val()).toBe('');
});
- it('shows/hides loading indicator', function () {
+ it('shows/hides loading indicator', function() {
this.form.showLoadingIndicator();
expect($('#loading-indicator')).not.toHaveClass('hidden');
this.form.hideLoadingIndicator();
expect($('#loading-indicator')).toHaveClass('hidden');
});
- it('shows messages', function () {
+ it('shows messages', function() {
this.form.showFoundMessage(123);
expect($('#discovery-message')).toContainHtml(123);
this.form.showNotFoundMessage();
@@ -47,7 +46,5 @@ define(['jquery', 'js/discovery/views/search_form'], function($, SearchForm) {
this.form.showErrorMessage();
expect($('#discovery-message')).not.toBeEmpty();
});
-
});
-
});
diff --git a/lms/static/js/spec/edxnotes/collections/notes_spec.js b/lms/static/js/spec/edxnotes/collections/notes_spec.js
index c1d928c10f..1ad84fbe85 100644
--- a/lms/static/js/spec/edxnotes/collections/notes_spec.js
+++ b/lms/static/js/spec/edxnotes/collections/notes_spec.js
@@ -5,11 +5,11 @@ define([
describe('EdxNotes NotesCollection', function() {
var notes = Helpers.getDefaultNotes();
- beforeEach(function () {
+ beforeEach(function() {
this.collection = new NotesCollection(notes, {perPage: 10, parse: true});
});
- it('can return correct course structure', function () {
+ it('can return correct course structure', function() {
var structure = this.collection.getCourseStructure();
expect(structure.chapters).toEqual([
@@ -23,9 +23,9 @@ define([
'i4x://section/2': Helpers.getSection('First Section', 2, [3])
});
- var compareUnits = function (structureUnits, collectionUnits) {
+ var compareUnits = function(structureUnits, collectionUnits) {
expect(structureUnits.length === collectionUnits.length).toBeTruthy();
- for(var i = 0; i < structureUnits.length; i++) {
+ for (var i = 0; i < structureUnits.length; i++) {
expect(structureUnits[i].attributes).toEqual(collectionUnits[i].attributes);
}
};
@@ -37,7 +37,7 @@ define([
'i4x://unit/3': [this.collection.at(4)]
};
- _.each(units, function(value, key){
+ _.each(units, function(value, key) {
compareUnits(structure.units[key], value);
});
});
diff --git a/lms/static/js/spec/edxnotes/helpers.js b/lms/static/js/spec/edxnotes/helpers.js
index f80feede5a..8d8986ec7c 100644
--- a/lms/static/js/spec/edxnotes/helpers.js
+++ b/lms/static/js/spec/edxnotes/helpers.js
@@ -1,6 +1,6 @@
define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'], function(_, URI, AjaxHelpers) {
'use strict';
- var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
+ var B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
LONG_TEXT, PRUNED_TEXT, TRUNCATED_TEXT, SHORT_TEXT,
base64Encode, makeToken, getChapter, getSection, getUnit, getDefaultNotes,
verifyUrl, verifyRequestParams, createNotesData, respondToRequest,
@@ -34,7 +34,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
].join('');
SHORT_TEXT = 'Adipisicing elit, sed do eiusmod tempor incididunt';
- base64Encode = function (data) {
+ base64Encode = function(data) {
var ac, bits, enc, h1, h2, h3, h4, i, o1, o2, o3, r, tmp_arr;
if (btoa) {
// Gecko and Webkit provide native code for this
@@ -44,7 +44,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
// version 1109.2015
i = 0;
ac = 0;
- enc = "";
+ enc = '';
tmp_arr = [];
if (!data) {
return data;
@@ -70,35 +70,35 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
makeToken = function() {
var now = (new Date()).getTime() / 1000,
rawToken = {
- sub: "sub",
+ sub: 'sub',
exp: now + 100,
iat: now
};
return 'header.' + base64Encode(JSON.stringify(rawToken)) + '.signature';
};
- getChapter = function (name, location, index, children) {
+ getChapter = function(name, location, index, children) {
return {
display_name: name,
location: 'i4x://chapter/' + location,
index: index,
- children: _.map(children, function (i) {
+ children: _.map(children, function(i) {
return 'i4x://section/' + i;
})
};
};
- getSection = function (name, location, children) {
+ getSection = function(name, location, children) {
return {
display_name: name,
location: 'i4x://section/' + location,
- children: _.map(children, function (i) {
+ children: _.map(children, function(i) {
return 'i4x://unit/' + i;
})
};
};
- getUnit = function (name, location) {
+ getUnit = function(name, location) {
return {
display_name: name,
location: 'i4x://unit/' + location,
@@ -106,7 +106,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
};
- getDefaultNotes = function () {
+ getDefaultNotes = function() {
// Note that the server returns notes in reverse chronological order (newest first).
return {
'count': 5,
@@ -169,20 +169,19 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
};
- verifyUrl = function (requestUrl, expectedUrl, expectedParams) {
+ verifyUrl = function(requestUrl, expectedUrl, expectedParams) {
expect(requestUrl.slice(0, expectedUrl.length) === expectedUrl).toBeTruthy();
verifyRequestParams(requestUrl, expectedParams);
};
- verifyRequestParams = function (requestUrl, expectedParams) {
+ verifyRequestParams = function(requestUrl, expectedParams) {
var urlParams = (new URI(requestUrl)).query(true);
- _.each(expectedParams, function (value, key) {
+ _.each(expectedParams, function(value, key) {
expect(urlParams[key]).toBe(value);
});
};
- createNotesData = function (options) {
-
+ createNotesData = function(options) {
var data = {
count: options.count || 0,
num_pages: options.num_pages || 1,
@@ -191,7 +190,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
results: []
};
- for(var i = 0; i < options.numNotesToCreate; i++) {
+ for (var i = 0; i < options.numNotesToCreate; i++) {
var notesInfo = {
chapter: getChapter('First Chapter__' + i, 1, 0, [2]),
section: getSection('First Section__' + i, 2, [3]),
@@ -200,7 +199,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
updated: new Date().toISOString(),
text: 'text__' + i,
quote: 'Note__' + i,
- tags: ['tag__' + i, 'tag__' + i+1]
+ tags: ['tag__' + i, 'tag__' + i + 1]
};
data.results.push(notesInfo);
@@ -218,7 +217,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
AjaxHelpers.respondWithJson(requests, responseJson);
};
- verifyPaginationInfo = function (view, headerMessage, footerHidden, currentPage, totalPages) {
+ verifyPaginationInfo = function(view, headerMessage, footerHidden, currentPage, totalPages) {
expect(view.$('.search-count.listing-count').text().trim()).toBe(headerMessage);
expect(view.$('.pagination.bottom').parent().hasClass('hidden')).toBe(footerHidden);
if (!footerHidden) {
@@ -227,7 +226,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
}
};
- verifyPageData = function (view, tabsCollection, tabInfo, tabId, notes) {
+ verifyPageData = function(view, tabsCollection, tabInfo, tabId, notes) {
expect(tabsCollection).toHaveLength(1);
expect(tabsCollection.at(0).toJSON()).toEqual(tabInfo);
expect(view.$(tabId)).toExist();
diff --git a/lms/static/js/spec/edxnotes/models/note_spec.js b/lms/static/js/spec/edxnotes/models/note_spec.js
index 3a79f32596..a2e19aa440 100644
--- a/lms/static/js/spec/edxnotes/models/note_spec.js
+++ b/lms/static/js/spec/edxnotes/models/note_spec.js
@@ -3,7 +3,7 @@ define([
], function(Helpers, NotesCollection) {
'use strict';
describe('EdxNotes NoteModel', function() {
- beforeEach(function () {
+ beforeEach(function() {
this.collection = new NotesCollection(
{
'count': 2,
@@ -23,14 +23,14 @@ define([
);
});
- it('has correct values on initialization', function () {
+ it('has correct values on initialization', function() {
expect(this.collection.at(0).get('is_expanded')).toBeFalsy();
expect(this.collection.at(0).get('show_link')).toBeTruthy();
expect(this.collection.at(1).get('is_expanded')).toBeFalsy();
expect(this.collection.at(1).get('show_link')).toBeFalsy();
});
- it('can return appropriate `quote`', function () {
+ it('can return appropriate `quote`', function() {
var model = this.collection.at(0);
// is_expanded = false, show_link = true
@@ -44,7 +44,7 @@ define([
expect(model.getQuote()).toBe(Helpers.LONG_TEXT);
});
- it('can return appropriate `text`', function () {
+ it('can return appropriate `text`', function() {
var model = this.collection.at(0);
expect(model.get('text')).toBe('text\n with\r\nline\n\rbreaks \r');
});
diff --git a/lms/static/js/spec/edxnotes/models/tab_spec.js b/lms/static/js/spec/edxnotes/models/tab_spec.js
index 00e410b80e..6e019ba5b8 100644
--- a/lms/static/js/spec/edxnotes/models/tab_spec.js
+++ b/lms/static/js/spec/edxnotes/models/tab_spec.js
@@ -3,18 +3,18 @@ define([
], function(TabsCollection) {
'use strict';
describe('EdxNotes TabModel', function() {
- beforeEach(function () {
+ beforeEach(function() {
this.collection = new TabsCollection([{}, {}, {}]);
});
- it('when activate current model, all other models are inactivated', function () {
+ it('when activate current model, all other models are inactivated', function() {
this.collection.at(1).activate();
expect(this.collection.at(1).get('is_active')).toBeTruthy();
expect(this.collection.at(0).get('is_active')).toBeFalsy();
expect(this.collection.at(2).get('is_active')).toBeFalsy();
});
- it('can inactivate current model', function () {
+ it('can inactivate current model', function() {
var model = this.collection.at(0);
model.activate();
expect(model.get('is_active')).toBeTruthy();
@@ -22,7 +22,7 @@ define([
expect(model.get('is_active')).toBeFalsy();
});
- it('can see correct activity status via isActive', function () {
+ it('can see correct activity status via isActive', function() {
var model = this.collection.at(0);
model.activate();
expect(model.isActive()).toBeTruthy();
diff --git a/lms/static/js/spec/edxnotes/plugins/accessibility_spec.js b/lms/static/js/spec/edxnotes/plugins/accessibility_spec.js
index e4abb6122a..f3392a824d 100644
--- a/lms/static/js/spec/edxnotes/plugins/accessibility_spec.js
+++ b/lms/static/js/spec/edxnotes/plugins/accessibility_spec.js
@@ -3,30 +3,30 @@ define([
], function($, _, Annotator, Logger, NotesFactory) {
'use strict';
describe('EdxNotes Accessibility Plugin', function() {
- function keyDownEvent (key) {
+ function keyDownEvent(key) {
return $.Event('keydown', {keyCode: key});
}
- function tabBackwardEvent () {
+ function tabBackwardEvent() {
return $.Event('keydown', {keyCode: $.ui.keyCode.TAB, shiftKey: true});
}
- function tabForwardEvent () {
+ function tabForwardEvent() {
return $.Event('keydown', {keyCode: $.ui.keyCode.TAB, shiftKey: false});
}
- function enterMetaKeyEvent () {
+ function enterMetaKeyEvent() {
return $.Event('keydown', {keyCode: $.ui.keyCode.ENTER, metaKey: true});
}
- function enterControlKeyEvent () {
+ function enterControlKeyEvent() {
return $.Event('keydown', {keyCode: $.ui.keyCode.ENTER, ctrlKey: true});
}
beforeEach(function() {
this.KEY = $.ui.keyCode;
loadFixtures('js/fixtures/edxnotes/edxnotes_wrapper.html');
- this.annotator = NotesFactory.factory(
+ this.annotator = NotesFactory.factory(
$('div#edx-notes-wrapper-123').get(0), {
endpoint: 'http://example.com/'
}
@@ -35,14 +35,14 @@ define([
spyOn(Logger, 'log');
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
});
- describe('destroy', function () {
- it('should unbind all events', function () {
+ describe('destroy', function() {
+ it('should unbind all events', function() {
spyOn($.fn, 'off');
spyOn(this.annotator, 'unsubscribe').and.callThrough();
this.plugin.destroy();
@@ -65,7 +65,7 @@ define([
});
});
- describe('a11y attributes', function () {
+ describe('a11y attributes', function() {
var highlight, annotation, note;
beforeEach(function() {
@@ -77,34 +77,34 @@ define([
};
});
- it('should be added to highlighted text and associated note', function () {
+ it('should be added to highlighted text and associated note', function() {
this.annotator.viewer.load([annotation]);
note = $('.annotator-note');
expect(note).toExist();
- expect(note).toHaveAttr('tabindex', "-1");
+ expect(note).toHaveAttr('tabindex', '-1');
expect(note).toHaveAttr('role', 'note');
expect(note).toHaveAttr('class', 'annotator-note');
});
- it('should create aria-descriptions when annotations are loaded', function () {
+ it('should create aria-descriptions when annotations are loaded', function() {
this.annotator.publish('annotationsLoaded', [[annotation]]);
expect(highlight).toHaveAttr('aria-describedby', 'aria-note-description-01');
expect($('#aria-note-description-01')).toContainText('Test text');
});
- it('should create aria-description when new annotation is created', function () {
+ it('should create aria-description when new annotation is created', function() {
this.annotator.publish('annotationCreated', [annotation]);
expect(highlight).toHaveAttr('aria-describedby', 'aria-note-description-01');
expect($('#aria-note-description-01')).toContainText('Test text');
});
- it('should remove aria-description when the annotation is removed', function () {
+ it('should remove aria-description when the annotation is removed', function() {
this.annotator.publish('annotationDeleted', [annotation]);
expect($('#aria-note-description-01')).not.toExist();
});
});
- describe('keydown events on highlighted text', function () {
+ describe('keydown events on highlighted text', function() {
var highlight, annotation, note;
beforeEach(function() {
@@ -120,24 +120,24 @@ define([
spyOn(this.plugin, 'focusOnGrabber').and.callThrough();
});
- it('should open the viewer on SPACE keydown and focus on note', function () {
+ it('should open the viewer on SPACE keydown and focus on note', function() {
highlight.trigger(keyDownEvent(this.KEY.SPACE));
expect(this.annotator.showViewer).toHaveBeenCalled();
});
- it('should open the viewer on ENTER keydown and focus on note', function () {
+ it('should open the viewer on ENTER keydown and focus on note', function() {
highlight.trigger(keyDownEvent(this.KEY.ENTER));
expect(this.annotator.showViewer).toHaveBeenCalled();
});
// This happens only when coming from notes page
- it('should open focus on viewer on TAB keydown if viewer is opened', function () {
+ it('should open focus on viewer on TAB keydown if viewer is opened', function() {
this.annotator.viewer.load([annotation]);
highlight.trigger(keyDownEvent(this.KEY.TAB));
expect(this.annotator.element.find('.annotator-listing')).toBeFocused();
});
- it('should focus highlighted text after closing', function () {
+ it('should focus highlighted text after closing', function() {
var note;
highlight.trigger(keyDownEvent(this.KEY.ENTER));
note = this.annotator.element.find('.annotator-edit');
@@ -145,51 +145,51 @@ define([
expect(highlight).toBeFocused();
});
- it('should focus on grabber after being deleted', function () {
+ it('should focus on grabber after being deleted', function() {
highlight.trigger(keyDownEvent(this.KEY.ENTER));
this.annotator.publish('annotationDeleted', {});
expect(this.plugin.focusGrabber).toBeFocused();
});
- it('should not focus on grabber when the viewer is hidden', function () {
+ it('should not focus on grabber when the viewer is hidden', function() {
this.annotator.publish('annotationDeleted', {});
expect(this.plugin.focusGrabber).not.toBeFocused();
});
});
- describe('keydown events on viewer', function () {
+ describe('keydown events on viewer', function() {
var highlight, annotation, listing, note, edit, del, close;
beforeEach(function() {
highlight = $(' ').appendTo(this.annotator.element);
annotation = {
id: '01',
- text: "Test text",
+ text: 'Test text',
highlights: [highlight.get(0)]
};
highlight.data('annotation', annotation);
this.annotator.viewer.load([annotation]);
listing = this.annotator.element.find('.annotator-listing').first();
note = this.annotator.element.find('.annotator-note').first();
- edit= this.annotator.element.find('.annotator-edit').first();
+ edit = this.annotator.element.find('.annotator-edit').first();
del = this.annotator.element.find('.annotator-delete').first();
close = this.annotator.element.find('.annotator-close').first();
spyOn(this.annotator.viewer, 'hide').and.callThrough();
});
- it('should give focus to Note on Listing TAB keydown', function () {
+ it('should give focus to Note on Listing TAB keydown', function() {
listing.focus();
listing.trigger(tabForwardEvent());
expect(note).toBeFocused();
});
- it('should give focus to Close on Listing SHIFT + TAB keydown', function () {
+ it('should give focus to Close on Listing SHIFT + TAB keydown', function() {
listing.focus();
listing.trigger(tabBackwardEvent());
expect(close).toBeFocused();
});
- it('should cycle forward through Note, Edit, Delete, and Close on TAB keydown', function () {
+ it('should cycle forward through Note, Edit, Delete, and Close on TAB keydown', function() {
note.focus();
note.trigger(tabForwardEvent());
expect(edit).toBeFocused();
@@ -201,7 +201,7 @@ define([
expect(note).toBeFocused();
});
- it('should cycle backward through Note, Edit, Delete, and Close on SHIFT + TAB keydown', function () {
+ it('should cycle backward through Note, Edit, Delete, and Close on SHIFT + TAB keydown', function() {
note.focus();
note.trigger(tabBackwardEvent());
expect(close).toBeFocused();
@@ -213,10 +213,10 @@ define([
expect(note).toBeFocused();
});
- it('should hide on ESCAPE keydown', function () {
+ it('should hide on ESCAPE keydown', function() {
var tabControls = [listing, note, edit, del, close];
- _.each(tabControls, function (control) {
+ _.each(tabControls, function(control) {
control.focus();
control.trigger(keyDownEvent(this.KEY.ESCAPE));
}, this);
@@ -224,14 +224,14 @@ define([
});
});
- describe('keydown events on editor', function () {
+ describe('keydown events on editor', function() {
var highlight, annotation, form, annotatorItems, textArea, tags, save, cancel;
beforeEach(function() {
highlight = $(' ').appendTo(this.annotator.element);
annotation = {
id: '01',
- text: "Test text",
+ text: 'Test text',
highlights: [highlight.get(0)]
};
highlight.data('annotation', annotation);
@@ -240,25 +240,25 @@ define([
annotatorItems = this.annotator.element.find('.annotator-item');
textArea = annotatorItems.first().children('textarea');
tags = annotatorItems.first().next().children('input');
- save = this.annotator.element.find('.annotator-save');
+ save = this.annotator.element.find('.annotator-save');
cancel = this.annotator.element.find('.annotator-cancel');
spyOn(this.annotator.editor, 'submit').and.callThrough();
spyOn(this.annotator.editor, 'hide').and.callThrough();
});
- it('should give focus to TextArea on Form TAB keydown', function () {
+ it('should give focus to TextArea on Form TAB keydown', function() {
form.focus();
form.trigger(tabForwardEvent());
expect(textArea).toBeFocused();
});
- it('should give focus to Cancel on Form SHIFT + TAB keydown', function () {
+ it('should give focus to Cancel on Form SHIFT + TAB keydown', function() {
form.focus();
form.trigger(tabBackwardEvent());
expect(cancel).toBeFocused();
});
- it('should cycle forward through textarea, tags, save, and cancel on TAB keydown', function () {
+ it('should cycle forward through textarea, tags, save, and cancel on TAB keydown', function() {
textArea.focus();
textArea.trigger(tabForwardEvent());
expect(tags).toBeFocused();
@@ -270,7 +270,7 @@ define([
expect(textArea).toBeFocused();
});
- it('should cycle back through textarea, tags, save, and cancel on SHIFT + TAB keydown', function () {
+ it('should cycle back through textarea, tags, save, and cancel on SHIFT + TAB keydown', function() {
textArea.focus();
textArea.trigger(tabBackwardEvent());
expect(cancel).toBeFocused();
@@ -282,7 +282,7 @@ define([
expect(textArea).toBeFocused();
});
- it('should submit if target is Save on ENTER or SPACE keydown', function () {
+ it('should submit if target is Save on ENTER or SPACE keydown', function() {
save.focus();
save.trigger(keyDownEvent(this.KEY.ENTER));
expect(this.annotator.editor.submit).toHaveBeenCalled();
@@ -292,7 +292,7 @@ define([
expect(this.annotator.editor.submit).toHaveBeenCalled();
});
- it('should submit on META or CONTROL + ENTER keydown', function () {
+ it('should submit on META or CONTROL + ENTER keydown', function() {
textArea.focus();
textArea.trigger(enterMetaKeyEvent());
expect(this.annotator.editor.submit).toHaveBeenCalled();
@@ -302,7 +302,7 @@ define([
expect(this.annotator.editor.submit).toHaveBeenCalled();
});
- it('should hide if target is Cancel on ENTER or SPACE keydown', function () {
+ it('should hide if target is Cancel on ENTER or SPACE keydown', function() {
cancel.focus();
cancel.trigger(keyDownEvent(this.KEY.ENTER));
expect(this.annotator.editor.hide).toHaveBeenCalled();
@@ -312,10 +312,10 @@ define([
expect(this.annotator.editor.hide).toHaveBeenCalled();
});
- it('should hide on ESCAPE keydown', function () {
+ it('should hide on ESCAPE keydown', function() {
var tabControls = [textArea, save, cancel];
- _.each(tabControls, function (control) {
+ _.each(tabControls, function(control) {
control.focus();
control.trigger(keyDownEvent(this.KEY.ESCAPE));
}, this);
diff --git a/lms/static/js/spec/edxnotes/plugins/caret_navigation_spec.js b/lms/static/js/spec/edxnotes/plugins/caret_navigation_spec.js
index 544b6881a3..f0c1db6cee 100644
--- a/lms/static/js/spec/edxnotes/plugins/caret_navigation_spec.js
+++ b/lms/static/js/spec/edxnotes/plugins/caret_navigation_spec.js
@@ -3,10 +3,9 @@ define([
], function($, _, Annotator, Logger, NotesFactory) {
'use strict';
describe('EdxNotes CaretNavigation Plugin', function() {
-
beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes_wrapper.html');
- this.annotator = NotesFactory.factory(
+ this.annotator = NotesFactory.factory(
$('div#edx-notes-wrapper-123').get(0), {
endpoint: 'http://example.com/'
}
@@ -15,22 +14,22 @@ define([
spyOn(Logger, 'log');
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
});
- describe('destroy', function () {
- it('should unbind all events', function () {
+ describe('destroy', function() {
+ it('should unbind all events', function() {
spyOn($.fn, 'off');
this.plugin.destroy();
expect($.fn.off).toHaveBeenCalledWith('keyup', this.plugin.onKeyUp);
});
});
- describe('isShortcut', function () {
- it('should return `true` if it is a shortcut', function () {
+ describe('isShortcut', function() {
+ it('should return `true` if it is a shortcut', function() {
expect(this.plugin.isShortcut($.Event('keyup', {
ctrlKey: true,
shiftKey: true,
@@ -38,7 +37,7 @@ define([
}))).toBeTruthy();
});
- it('should return `false` if it is not a shortcut', function () {
+ it('should return `false` if it is not a shortcut', function() {
expect(this.plugin.isShortcut($.Event('keyup', {
ctrlKey: false,
shiftKey: true,
@@ -53,19 +52,19 @@ define([
});
});
- describe('hasSelection', function () {
- it('should return `true` if has selection', function () {
+ describe('hasSelection', function() {
+ it('should return `true` if has selection', function() {
expect(this.plugin.hasSelection([{}, {}])).toBeTruthy();
});
- it('should return `false` if does not have selection', function () {
+ it('should return `false` if does not have selection', function() {
expect(this.plugin.hasSelection([])).toBeFalsy();
expect(this.plugin.hasSelection()).toBeFalsy();
});
});
- describe('onKeyUp', function () {
- var triggerEvent = function (element, props) {
+ describe('onKeyUp', function() {
+ var triggerEvent = function(element, props) {
var eventProps = $.extend({
ctrlKey: true,
shiftKey: true,
@@ -78,11 +77,11 @@ define([
this.element = $(' ', {'class': 'annotator-hl'}).appendTo(this.annotator.element);
this.annotation = {
- text: "test",
+ text: 'test',
highlights: [this.element.get(0)]
};
- this.mockOffset = {top: 0, left:0};
+ this.mockOffset = {top: 0, left: 0};
this.mockSubscriber = jasmine.createSpy();
this.annotator.subscribe('annotationCreated', this.mockSubscriber);
@@ -98,19 +97,19 @@ define([
spyOn(this.plugin, 'restoreSelection');
});
- it('should create a new annotation', function () {
+ it('should create a new annotation', function() {
triggerEvent(this.element);
expect(this.annotator.createAnnotation.calls.count()).toBe(1);
});
- it('should set up the annotation', function () {
+ it('should set up the annotation', function() {
triggerEvent(this.element);
expect(this.annotator.setupAnnotation).toHaveBeenCalledWith(
this.annotation
);
});
- it('should display the Annotation#editor correctly if the Annotation#adder is hidden', function () {
+ it('should display the Annotation#editor correctly if the Annotation#adder is hidden', function() {
spyOn($.fn, 'is').and.returnValue(false);
triggerEvent(this.element);
expect($('annotator-hl-temporary').position.calls.count()).toBe(1);
@@ -119,7 +118,7 @@ define([
);
});
- it('should display the Annotation#editor in the same place as the Annotation#adder', function () {
+ it('should display the Annotation#editor in the same place as the Annotation#adder', function() {
spyOn($.fn, 'is').and.returnValue(true);
triggerEvent(this.element);
expect(this.annotator.adder.position.calls.count()).toBe(1);
@@ -128,33 +127,33 @@ define([
);
});
- it('should hide the Annotation#adder', function () {
+ it('should hide the Annotation#adder', function() {
spyOn($.fn, 'is').and.returnValue(true);
spyOn($.fn, 'hide');
triggerEvent(this.element);
expect(this.annotator.adder.hide).toHaveBeenCalled();
});
- it('should add temporary highlights to the document to show the user what they selected', function () {
+ it('should add temporary highlights to the document to show the user what they selected', function() {
triggerEvent(this.element);
expect(this.element).toHaveClass('annotator-hl');
expect(this.element).toHaveClass('annotator-hl-temporary');
});
- it('should persist the temporary highlights if the annotation is saved', function () {
+ it('should persist the temporary highlights if the annotation is saved', function() {
triggerEvent(this.element);
this.annotator.publish('annotationEditorSubmit');
expect(this.element).toHaveClass('annotator-hl');
expect(this.element).not.toHaveClass('annotator-hl-temporary');
});
- it('should trigger the `annotationCreated` event if the edit\'s saved', function () {
+ it('should trigger the `annotationCreated` event if the edit\'s saved', function() {
triggerEvent(this.element);
this.annotator.onEditorSubmit(this.annotation);
expect(this.mockSubscriber).toHaveBeenCalledWith(this.annotation);
});
- it('should call Annotator#deleteAnnotation if editing is cancelled', function () {
+ it('should call Annotator#deleteAnnotation if editing is cancelled', function() {
triggerEvent(this.element);
this.annotator.onEditorHide();
expect(this.mockSubscriber).not.toHaveBeenCalledWith('annotationCreated');
@@ -163,7 +162,7 @@ define([
);
});
- it('should restore selection if editing is cancelled', function () {
+ it('should restore selection if editing is cancelled', function() {
triggerEvent(this.element);
this.plugin.savedRange = 'range';
expect(this.plugin.saveSelection).toHaveBeenCalled();
@@ -171,7 +170,7 @@ define([
expect(this.plugin.restoreSelection).toHaveBeenCalled();
});
- it('should do nothing if the edit\'s saved', function () {
+ it('should do nothing if the edit\'s saved', function() {
triggerEvent(this.element);
expect(this.plugin.saveSelection).toHaveBeenCalled();
this.plugin.savedRange = 'range';
@@ -181,18 +180,18 @@ define([
expect(this.plugin.restoreSelection).not.toHaveBeenCalled();
});
- it('should do nothing if it is not a shortcut', function () {
+ it('should do nothing if it is not a shortcut', function() {
triggerEvent(this.element, {ctrlKey: false});
expect(this.annotator.showEditor).not.toHaveBeenCalled();
});
- it('should do nothing if empty selection', function () {
+ it('should do nothing if empty selection', function() {
this.annotator.getSelectedRanges.and.returnValue([]);
triggerEvent(this.element);
expect(this.annotator.showEditor).not.toHaveBeenCalled();
});
- it('should do nothing if selection is in Annotator', function () {
+ it('should do nothing if selection is in Annotator', function() {
spyOn(this.annotator, 'isAnnotator').and.returnValue(true);
triggerEvent(this.element);
expect(this.annotator.showEditor).not.toHaveBeenCalled();
diff --git a/lms/static/js/spec/edxnotes/plugins/events_spec.js b/lms/static/js/spec/edxnotes/plugins/events_spec.js
index f74c84f49d..7602efb729 100644
--- a/lms/static/js/spec/edxnotes/plugins/events_spec.js
+++ b/lms/static/js/spec/edxnotes/plugins/events_spec.js
@@ -10,18 +10,18 @@ define([
text: 'text-123',
quote: 'quote-123',
usage_id: 'usage-123',
- tags: ["tag1", "tag2"]
+ tags: ['tag1', 'tag2']
},
noteWithoutId = {
user: 'user-123',
text: 'text-123',
quote: 'quote-123',
usage_id: 'usage-123',
- tags: ["tag1", "tag2"]
+ tags: ['tag1', 'tag2']
};
beforeEach(function() {
- this.annotator = NotesFactory.factory(
+ this.annotator = NotesFactory.factory(
$('
').get(0), {
endpoint: 'http://example.com/',
eventStringLimit: 300
@@ -30,7 +30,7 @@ define([
spyOn(Logger, 'log');
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
@@ -70,7 +70,7 @@ define([
'edx.course.student_notes.added', {
'note_id': 'note-123',
'note_text': 'text-123',
- 'tags': ["tag1", "tag2"],
+ 'tags': ['tag1', 'tag2'],
'highlighted_content': 'quote-123',
'truncated': [],
'component_usage_id': 'usage-123'
@@ -92,7 +92,7 @@ define([
'note_id': 'note-123',
'old_note_text': 'text-123',
'note_text': 'text-456',
- 'old_tags': ["tag1", "tag2"],
+ 'old_tags': ['tag1', 'tag2'],
'tags': [],
'highlighted_content': 'quote-123',
'truncated': [],
@@ -120,7 +120,7 @@ define([
'edx.course.student_notes.deleted', {
'note_id': 'note-123',
'note_text': 'text-123',
- 'tags': ["tag1", "tag2"],
+ 'tags': ['tag1', 'tag2'],
'highlighted_content': 'quote-123',
'truncated': [],
'component_usage_id': 'usage-123'
@@ -134,11 +134,11 @@ define([
});
it('should truncate values of some fields', function() {
- var oldNote = $.extend({}, note, {text: Helpers.LONG_TEXT, tags: ["review", Helpers.LONG_TEXT]}),
+ var oldNote = $.extend({}, note, {text: Helpers.LONG_TEXT, tags: ['review', Helpers.LONG_TEXT]}),
newNote = $.extend({}, note, {
text: Helpers.LONG_TEXT + '123',
quote: Helpers.LONG_TEXT + '123',
- tags: ["short", "tags", "will", "stay", Helpers.LONG_TEXT]
+ tags: ['short', 'tags', 'will', 'stay', Helpers.LONG_TEXT]
});
this.annotator.publish('annotationEditorShown', [this.annotator.editor, oldNote]);
@@ -150,11 +150,11 @@ define([
'edx.course.student_notes.edited', {
'note_id': 'note-123',
'old_note_text': Helpers.TRUNCATED_TEXT,
- 'old_tags': ["review"],
- 'tags': ["short", "tags", "will", "stay"],
+ 'old_tags': ['review'],
+ 'tags': ['short', 'tags', 'will', 'stay'],
'note_text': Helpers.TRUNCATED_TEXT,
'highlighted_content': Helpers.TRUNCATED_TEXT,
- 'truncated': ["note_text", "highlighted_content", "tags", "old_note_text", "old_tags"],
+ 'truncated': ['note_text', 'highlighted_content', 'tags', 'old_note_text', 'old_tags'],
'component_usage_id': 'usage-123'
}
);
diff --git a/lms/static/js/spec/edxnotes/plugins/scroller_spec.js b/lms/static/js/spec/edxnotes/plugins/scroller_spec.js
index 49c54dda6c..bff3697324 100644
--- a/lms/static/js/spec/edxnotes/plugins/scroller_spec.js
+++ b/lms/static/js/spec/edxnotes/plugins/scroller_spec.js
@@ -43,7 +43,7 @@ define([
spyOn($.fn, 'unbind').and.callThrough();
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
diff --git a/lms/static/js/spec/edxnotes/plugins/store_error_handler_spec.js b/lms/static/js/spec/edxnotes/plugins/store_error_handler_spec.js
index 4713596db2..78cf4f73f4 100644
--- a/lms/static/js/spec/edxnotes/plugins/store_error_handler_spec.js
+++ b/lms/static/js/spec/edxnotes/plugins/store_error_handler_spec.js
@@ -1,36 +1,36 @@
define([
- 'jquery', 'underscore', 'annotator_1.2.9',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/spec/edxnotes/helpers',
- 'js/edxnotes/views/notes_factory'
-], function ($, _, Annotator, AjaxHelpers, Helpers, NotesFactory) {
- 'use strict';
- describe('Store Error Handler Custom Message', function () {
- beforeEach(function () {
- spyOn(Annotator, 'showNotification');
- loadFixtures('js/fixtures/edxnotes/edxnotes_wrapper.html');
- this.wrapper = document.getElementById('edx-notes-wrapper-123');
- });
+ 'jquery', 'underscore', 'annotator_1.2.9',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/spec/edxnotes/helpers',
+ 'js/edxnotes/views/notes_factory'
+], function($, _, Annotator, AjaxHelpers, Helpers, NotesFactory) {
+ 'use strict';
+ describe('Store Error Handler Custom Message', function() {
+ beforeEach(function() {
+ spyOn(Annotator, 'showNotification');
+ loadFixtures('js/fixtures/edxnotes/edxnotes_wrapper.html');
+ this.wrapper = document.getElementById('edx-notes-wrapper-123');
+ });
- afterEach(function () {
- _.invoke(Annotator._instances, 'destroy');
- });
+ afterEach(function() {
+ _.invoke(Annotator._instances, 'destroy');
+ });
- it('can handle custom error if sent from server', function () {
- var requests = AjaxHelpers.requests(this);
- var token = Helpers.makeToken();
- NotesFactory.factory(this.wrapper, {
- endpoint: '/test_endpoint',
- user: 'a user',
- usageId: 'an usage',
- courseId: 'a course',
- token: token,
- tokenUrl: '/test_token_url'
- });
+ it('can handle custom error if sent from server', function() {
+ var requests = AjaxHelpers.requests(this);
+ var token = Helpers.makeToken();
+ NotesFactory.factory(this.wrapper, {
+ endpoint: '/test_endpoint',
+ user: 'a user',
+ usageId: 'an usage',
+ courseId: 'a course',
+ token: token,
+ tokenUrl: '/test_token_url'
+ });
- var errorMsg = 'can\'t create more notes';
- AjaxHelpers.respondWithError(requests, 400, {error_msg: errorMsg});
- expect(Annotator.showNotification).toHaveBeenCalledWith(errorMsg, Annotator.Notification.ERROR);
+ var errorMsg = 'can\'t create more notes';
+ AjaxHelpers.respondWithError(requests, 400, {error_msg: errorMsg});
+ expect(Annotator.showNotification).toHaveBeenCalledWith(errorMsg, Annotator.Notification.ERROR);
+ });
});
- });
});
diff --git a/lms/static/js/spec/edxnotes/utils/logger_spec.js b/lms/static/js/spec/edxnotes/utils/logger_spec.js
index 802ec55e72..d9e0557b9a 100644
--- a/lms/static/js/spec/edxnotes/utils/logger_spec.js
+++ b/lms/static/js/spec/edxnotes/utils/logger_spec.js
@@ -7,7 +7,7 @@ define([
return NotesLogger.getLogger(id, mode);
};
- beforeEach(function () {
+ beforeEach(function() {
spyOn(window.console, 'log');
spyOn(window.console, 'error');
spyOn(Logger, 'log');
@@ -109,7 +109,7 @@ define([
expect(log[1][3]).toBe('ms');
});
- it('can emit an event properly', function () {
+ it('can emit an event properly', function() {
var logger = getLogger('id', 0);
logger.emit('event_name', {id: 'some_id'});
expect(Logger.log).toHaveBeenCalledWith('event_name', {
diff --git a/lms/static/js/spec/edxnotes/views/note_item_spec.js b/lms/static/js/spec/edxnotes/views/note_item_spec.js
index 86f8abb62c..98d43ffe9f 100644
--- a/lms/static/js/spec/edxnotes/views/note_item_spec.js
+++ b/lms/static/js/spec/edxnotes/views/note_item_spec.js
@@ -1,13 +1,13 @@
define([
'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers', 'js/spec/edxnotes/helpers', 'logger',
- 'js/edxnotes/models/note', 'js/edxnotes/views/note_item',
+ 'js/edxnotes/models/note', 'js/edxnotes/views/note_item'
], function(
$, _, AjaxHelpers, TemplateHelpers, Helpers, Logger, NoteModel, NoteItemView
) {
'use strict';
describe('EdxNotes NoteItemView', function() {
- var getView = function (model, scrollToTag, formattedText) {
+ var getView = function(model, scrollToTag, formattedText) {
model = new NoteModel(_.defaults(model || {}, {
id: 'id-123',
user: 'user-123',
@@ -21,7 +21,7 @@ define([
}
}));
- return new NoteItemView({model: model, scrollToTag: scrollToTag, view: "Test View"}).render();
+ return new NoteItemView({model: model, scrollToTag: scrollToTag, view: 'Test View'}).render();
};
beforeEach(function() {
@@ -61,7 +61,7 @@ define([
});
it('should display tags if they exist', function() {
- var view = getView({tags: ["First", "Second"]});
+ var view = getView({tags: ['First', 'Second']});
expect(view.$('.reference-title').length).toBe(3);
expect(view.$('.reference-title')[2]).toContainText('Tags:');
expect(view.$('span.reference-tags').length).toBe(2);
@@ -71,8 +71,8 @@ define([
it('should highlight tags & text if they have elasticsearch formatter', function() {
var view = getView({
- tags: ["First", "{elasticsearch_highlight_start}Second{elasticsearch_highlight_end}"]
- }, {}, "{elasticsearch_highlight_start}Sample{elasticsearch_highlight_end}");
+ tags: ['First', '{elasticsearch_highlight_start}Second{elasticsearch_highlight_end}']
+ }, {}, '{elasticsearch_highlight_start}Sample{elasticsearch_highlight_end}');
expect(view.$('.reference-title').length).toBe(3);
expect(view.$('.reference-title')[2]).toContainText('Tags:');
expect(view.$('span.reference-tags').length).toBe(2);
@@ -86,8 +86,8 @@ define([
it('should escape html for tags & comments', function() {
var view = getView({
- tags: ["First", "Second ", "ȗnicode"]
- }, {}, "Sample ");
+ tags: ['First', 'Second ', 'ȗnicode']
+ }, {}, 'Sample ');
expect(view.$('.reference-title').length).toBe(3);
expect(view.$('.reference-title')[2]).toContainText('Tags:');
expect(view.$('span.reference-tags').length).toBe(3);
@@ -101,15 +101,15 @@ define([
xit('should handle a click event on the tag', function() {
var scrollToTagSpy = {
- scrollToTag: function (tagName){}
+ scrollToTag: function(tagName) {}
};
spyOn(scrollToTagSpy, 'scrollToTag');
- var view = getView({tags: ["only"]}, scrollToTagSpy.scrollToTag);
+ var view = getView({tags: ['only']}, scrollToTagSpy.scrollToTag);
view.$('a.reference-tags').click();
- expect(scrollToTagSpy.scrollToTag).toHaveBeenCalledWith("only");
+ expect(scrollToTagSpy.scrollToTag).toHaveBeenCalledWith('only');
});
- it('should log the edx.course.student_notes.used_unit_link event properly', function () {
+ it('should log the edx.course.student_notes.used_unit_link event properly', function() {
var requests = AjaxHelpers.requests(this),
view = getView();
spyOn(view, 'redirectTo');
diff --git a/lms/static/js/spec/edxnotes/views/notes_factory_spec.js b/lms/static/js/spec/edxnotes/views/notes_factory_spec.js
index a57287e305..f9e68f172c 100644
--- a/lms/static/js/spec/edxnotes/views/notes_factory_spec.js
+++ b/lms/static/js/spec/edxnotes/views/notes_factory_spec.js
@@ -9,7 +9,7 @@ define([
this.wrapper = document.getElementById('edx-notes-wrapper-123');
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
@@ -20,13 +20,13 @@ define([
token = Helpers.makeToken(),
options = {
user: 'a user',
- usage_id : 'an usage',
+ usage_id: 'an usage',
course_id: 'a course'
},
annotator = NotesFactory.factory(this.wrapper, {
endpoint: '/test_endpoint',
user: 'a user',
- usageId : 'an usage',
+ usageId: 'an usage',
courseId: 'a course',
token: token,
tokenUrl: '/test_token_url'
diff --git a/lms/static/js/spec/edxnotes/views/notes_visibility_factory_spec.js b/lms/static/js/spec/edxnotes/views/notes_visibility_factory_spec.js
index 727c759897..0d34846c5b 100644
--- a/lms/static/js/spec/edxnotes/views/notes_visibility_factory_spec.js
+++ b/lms/static/js/spec/edxnotes/views/notes_visibility_factory_spec.js
@@ -33,7 +33,7 @@ define([
spyOn(this.toggleNotes, 'toggleHandler').and.callThrough();
});
- afterEach(function () {
+ afterEach(function() {
NotesVisibilityFactory.VisibilityDecorator._setVisibility(null);
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
diff --git a/lms/static/js/spec/edxnotes/views/search_box_spec.js b/lms/static/js/spec/edxnotes/views/search_box_spec.js
index 6bf3185af6..dac652d03c 100644
--- a/lms/static/js/spec/edxnotes/views/search_box_spec.js
+++ b/lms/static/js/spec/edxnotes/views/search_box_spec.js
@@ -21,7 +21,7 @@ define([
'results': [null, null]
};
- getSearchBox = function (options) {
+ getSearchBox = function(options) {
options = _.defaults(options || {}, {
el: $('#search-notes-form').get(0),
perPage: 10,
@@ -34,30 +34,30 @@ define([
return new SearchBoxView(options);
};
- submitForm = function (searchBox, text) {
+ submitForm = function(searchBox, text) {
searchBox.$('.search-notes-input').val(text);
searchBox.$('.search-notes-submit').click();
};
- assertBoxIsEnabled = function (searchBox) {
+ assertBoxIsEnabled = function(searchBox) {
expect(searchBox.$el).not.toHaveClass('is-looking');
expect(searchBox.$('.search-notes-submit')).not.toHaveClass('is-disabled');
expect(searchBox.isDisabled).toBeFalsy();
};
- assertBoxIsDisabled = function (searchBox) {
+ assertBoxIsDisabled = function(searchBox) {
expect(searchBox.$el).toHaveClass('is-looking');
expect(searchBox.$('.search-notes-submit')).toHaveClass('is-disabled');
expect(searchBox.isDisabled).toBeTruthy();
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
spyOn(Logger, 'log');
this.searchBox = getSearchBox();
});
- it('sends a request with proper information on submit the form', function () {
+ it('sends a request with proper information on submit the form', function() {
var requests = AjaxHelpers.requests(this),
form = this.searchBox.el,
request;
@@ -72,7 +72,7 @@ define([
);
});
- it('returns success result', function () {
+ it('returns success result', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
expect(this.searchBox.options.beforeSearchStart).toHaveBeenCalledWith(
@@ -89,7 +89,7 @@ define([
);
});
- it('should log the edx.course.student_notes.searched event properly', function () {
+ it('should log the edx.course.student_notes.searched event properly', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
AjaxHelpers.respondWithJson(requests, searchResponse);
@@ -100,7 +100,7 @@ define([
});
});
- it('returns default error message if received data structure is wrong', function () {
+ it('returns default error message if received data structure is wrong', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
AjaxHelpers.respondWithJson(requests, {});
@@ -113,7 +113,7 @@ define([
);
});
- it('returns default error message if network error occurs', function () {
+ it('returns default error message if network error occurs', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
AjaxHelpers.respondWithError(requests);
@@ -126,7 +126,7 @@ define([
);
});
- it('returns error message if server error occurs', function () {
+ it('returns error message if server error occurs', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
assertBoxIsDisabled(this.searchBox);
@@ -148,7 +148,7 @@ define([
);
});
- it('does not send second request during current search', function () {
+ it('does not send second request during current search', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, 'test_text');
assertBoxIsDisabled(this.searchBox);
@@ -158,7 +158,7 @@ define([
expect(requests).toHaveLength(1);
});
- it('returns error message if the field is empty', function () {
+ it('returns error message if the field is empty', function() {
var requests = AjaxHelpers.requests(this);
submitForm(this.searchBox, ' ');
expect(requests).toHaveLength(0);
@@ -169,7 +169,7 @@ define([
);
});
- it('can clear its input box', function () {
+ it('can clear its input box', function() {
this.searchBox.$('.search-notes-input').val('search me');
this.searchBox.clearInput();
expect(this.searchBox.$('#search-notes-input').val()).toEqual('');
diff --git a/lms/static/js/spec/edxnotes/views/shim_spec.js b/lms/static/js/spec/edxnotes/views/shim_spec.js
index 37795ce8cb..5bbc3d74d7 100644
--- a/lms/static/js/spec/edxnotes/views/shim_spec.js
+++ b/lms/static/js/spec/edxnotes/views/shim_spec.js
@@ -45,7 +45,7 @@ define([
spyOn($.fn, 'off').and.callThrough();
});
- afterEach(function () {
+ afterEach(function() {
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
}
@@ -143,7 +143,7 @@ define([
var close,
annotation = {
id: '01',
- text: "Test text",
+ text: 'Test text',
highlights: [highlights[0].get(0)]
};
@@ -153,11 +153,11 @@ define([
expect($('#edx-notes-wrapper-123 .annotator-viewer')).toHaveClass('annotator-hide');
});
- describe('_setupViewer', function () {
+ describe('_setupViewer', function() {
var mockViewer = null;
- beforeEach(function () {
- var element = $('
');
+ beforeEach(function() {
+ var element = $('
');
mockViewer = {
fields: [],
element: element
@@ -166,7 +166,7 @@ define([
mockViewer.on = jasmine.createSpy().and.returnValue(mockViewer);
mockViewer.hide = jasmine.createSpy().and.returnValue(mockViewer);
mockViewer.destroy = jasmine.createSpy().and.returnValue(mockViewer);
- mockViewer.addField = jasmine.createSpy().and.callFake(function (options) {
+ mockViewer.addField = jasmine.createSpy().and.callFake(function(options) {
mockViewer.fields.push(options);
return mockViewer;
});
@@ -178,22 +178,22 @@ define([
annotators[0]._setupViewer();
});
- it('should create a new instance of Annotator.Viewer and set Annotator#viewer', function () {
+ it('should create a new instance of Annotator.Viewer and set Annotator#viewer', function() {
expect(annotators[0].viewer).toEqual(mockViewer);
});
- it('should hide the annotator on creation', function () {
+ it('should hide the annotator on creation', function() {
expect(mockViewer.hide.calls.count()).toBe(1);
});
- it('should setup the default text field', function () {
+ it('should setup the default text field', function() {
var args = mockViewer.addField.calls.mostRecent().args[0];
expect(mockViewer.addField.calls.count()).toBe(1);
expect(_.isFunction(args.load)).toBeTruthy();
});
- it('should set the contents of the field on load', function () {
+ it('should set the contents of the field on load', function() {
var field = document.createElement('div'),
annotation = {text: 'text \nwith\r\nline\n\rbreaks \r'};
@@ -201,7 +201,7 @@ define([
expect($(field).html()).toBe('text with line breaks ');
});
- it('should set the contents of the field to placeholder text when empty', function () {
+ it('should set the contents of the field to placeholder text when empty', function() {
var field = document.createElement('div'),
annotation = {text: ''};
@@ -209,7 +209,7 @@ define([
expect($(field).html()).toBe('No Comment ');
});
- it('should setup the default text field to publish an event on load', function () {
+ it('should setup the default text field to publish an event on load', function() {
var field = document.createElement('div'),
annotation = {text: ''},
callback = jasmine.createSpy();
@@ -219,30 +219,30 @@ define([
expect(callback).toHaveBeenCalledWith(field, annotation);
});
- it('should subscribe to custom events', function () {
+ it('should subscribe to custom events', function() {
expect(mockViewer.on).toHaveBeenCalledWith('edit', annotators[0].onEditAnnotation);
expect(mockViewer.on).toHaveBeenCalledWith('delete', annotators[0].onDeleteAnnotation);
});
- it('should bind to browser mouseover and mouseout events', function () {
+ it('should bind to browser mouseover and mouseout events', function() {
expect(mockViewer.element.bind).toHaveBeenCalledWith({
'mouseover': annotators[0].clearViewerHideTimer,
- 'mouseout': annotators[0].startViewerHideTimer
+ 'mouseout': annotators[0].startViewerHideTimer
});
});
- it('should append the Viewer#element to the Annotator#wrapper', function () {
+ it('should append the Viewer#element to the Annotator#wrapper', function() {
expect(mockViewer.element.appendTo).toHaveBeenCalledWith(annotators[0].wrapper);
});
});
- describe('TagsPlugin', function () {
+ describe('TagsPlugin', function() {
it('should add ARIA label information to the viewer', function() {
var tagDiv,
annotation = {
id: '01',
- text: "Test text",
- tags: ["tag1", "tag2", "tag3"],
+ text: 'Test text',
+ tags: ['tag1', 'tag2', 'tag3'],
highlights: [highlights[0].get(0)]
};
@@ -262,7 +262,7 @@ define([
// but the sr label "for" attribute should match the ID of the element immediately following it.
annotators[0].showEditor({}, {});
editor = annotators[0].editor;
- srLabel = editor.element.find("label.sr");
+ srLabel = editor.element.find('label.sr');
inputId = srLabel.next().attr('id');
expect(srLabel.attr('for')).toEqual(inputId);
});
diff --git a/lms/static/js/spec/edxnotes/views/tab_item_spec.js b/lms/static/js/spec/edxnotes/views/tab_item_spec.js
index 4e7cc208f3..ba259a55b5 100644
--- a/lms/static/js/spec/edxnotes/views/tab_item_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tab_item_spec.js
@@ -4,7 +4,7 @@ define([
], function($, TemplateHelpers, TabsCollection, TabsListView) {
'use strict';
describe('EdxNotes TabItemView', function() {
- beforeEach(function () {
+ beforeEach(function() {
TemplateHelpers.installTemplate('templates/edxnotes/tab-item');
this.collection = new TabsCollection([
{identifier: 'first-item'},
@@ -19,7 +19,7 @@ define([
}).render();
});
- it('can contain an icon', function () {
+ it('can contain an icon', function() {
var firstItem = this.tabsList.$('#first-item'),
secondItem = this.tabsList.$('#second-item');
@@ -27,7 +27,7 @@ define([
expect(secondItem.find('.icon')).toHaveClass('icon-class');
});
- it('can navigate between tabs', function () {
+ it('can navigate between tabs', function() {
var firstItem = this.tabsList.$('#first-item'),
secondItem = this.tabsList.$('#second-item');
@@ -42,7 +42,7 @@ define([
expect(secondItem).toContainText('Current tab');
});
- it('can close the tab', function () {
+ it('can close the tab', function() {
var secondItem = this.tabsList.$('#second-item');
expect(this.tabsList.$('.tab')).toHaveLength(2);
diff --git a/lms/static/js/spec/edxnotes/views/tab_view_spec.js b/lms/static/js/spec/edxnotes/views/tab_view_spec.js
index 678a1ff008..4f03d216df 100644
--- a/lms/static/js/spec/edxnotes/views/tab_view_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tab_view_spec.js
@@ -6,14 +6,14 @@ define([
'js/edxnotes/collections/tabs',
'js/edxnotes/views/tabs_list',
'js/edxnotes/views/tab_view'
-], function ($, Backbone, HtmlUtils, TemplateHelpers, TabsCollection, TabsListView, TabView) {
+], function($, Backbone, HtmlUtils, TemplateHelpers, TabsCollection, TabsListView, TabView) {
'use strict';
describe('EdxNotes TabView', function() {
var TestSubView = Backbone.View.extend({
id: 'test-subview-panel',
className: 'tab-panel',
content: 'test view content
',
- render: function () {
+ render: function() {
this.$el.html(this.content);
return this;
}
@@ -26,7 +26,7 @@ define([
}
}), getView;
- getView = function (tabsCollection, options) {
+ getView = function(tabsCollection, options) {
var view;
options = _.defaults(options || {}, {
el: $('.wrapper-student-notes'),
@@ -42,7 +42,7 @@ define([
return view;
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
TemplateHelpers.installTemplates([
'templates/edxnotes/note-item', 'templates/edxnotes/tab-item'
@@ -52,14 +52,14 @@ define([
this.tabsList.$el.appendTo($('.tab-list'));
});
- it('can create a tab and content on initialization', function () {
+ it('can create a tab and content on initialization', function() {
var view = getView(this.tabsCollection);
expect(this.tabsCollection).toHaveLength(1);
expect(view.$('.tab')).toExist();
expect(view.$('.wrapper-tabs')).toContainHtml('test view content
');
});
- it('cannot create a tab on initialization if flag is not set', function () {
+ it('cannot create a tab on initialization if flag is not set', function() {
var view = getView(this.tabsCollection, {
createTabOnInitialization: false
});
@@ -68,7 +68,7 @@ define([
expect(view.$('.wrapper-tabs')).not.toContainHtml('test view content
');
});
- it('can remove the content if tab becomes inactive', function () {
+ it('can remove the content if tab becomes inactive', function() {
var view = getView(this.tabsCollection);
this.tabsCollection.add({identifier: 'second-tab'});
view.$('#second-tab').click();
@@ -76,9 +76,9 @@ define([
expect(view.$('.wrapper-tabs')).not.toContainHtml('test view content
');
});
- it('can remove the content if tab is closed', function () {
+ it('can remove the content if tab is closed', function() {
var view = getView(this.tabsCollection);
- view.onClose = jasmine.createSpy();
+ view.onClose = jasmine.createSpy();
view.$('.tab .action-close').click();
expect(view.$('.tab')).toHaveLength(0);
expect(view.$('.wrapper-tabs')).not.toContainHtml('test view content
');
@@ -86,7 +86,7 @@ define([
expect(view.onClose).toHaveBeenCalled();
});
- it('can correctly update the content of active tab', function () {
+ it('can correctly update the content of active tab', function() {
var view = getView(this.tabsCollection);
TestSubView.prototype.content = 'New content
';
view.render();
@@ -94,7 +94,7 @@ define([
expect(view.$('.wrapper-tabs')).not.toContainHtml('test view content
');
});
- it('can show/hide error messages', function () {
+ it('can show/hide error messages', function() {
var view = getView(this.tabsCollection),
errorHolder = view.$('.wrapper-msg');
@@ -107,7 +107,7 @@ define([
expect(errorHolder.find('.copy')).toBeEmpty();
});
- it('should hide error messages before rendering', function () {
+ it('should hide error messages before rendering', function() {
var view = getView(this.tabsCollection),
errorHolder = view.$('.wrapper-msg');
view.showErrorMessageHtml('error message is here
');
diff --git a/lms/static/js/spec/edxnotes/views/tabs/course_structure_spec.js b/lms/static/js/spec/edxnotes/views/tabs/course_structure_spec.js
index f372118456..ab9ac40d02 100644
--- a/lms/static/js/spec/edxnotes/views/tabs/course_structure_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tabs/course_structure_spec.js
@@ -10,19 +10,19 @@ define([
var notes = Helpers.getDefaultNotes(),
getView, getText;
- getText = function (selector) {
- return $(selector).map(function () {
+ getText = function(selector) {
+ return $(selector).map(function() {
return _.trim($(this).text());
}).toArray();
};
- getView = function (collection, tabsCollection, options) {
+ getView = function(collection, tabsCollection, options) {
var view;
options = _.defaults(options || {}, {
el: $('.wrapper-student-notes'),
collection: collection,
- tabsCollection: tabsCollection,
+ tabsCollection: tabsCollection
});
view = new CourseStructureView(options);
@@ -31,7 +31,7 @@ define([
return view;
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
TemplateHelpers.installTemplates([
'templates/edxnotes/note-item', 'templates/edxnotes/tab-item'
@@ -41,7 +41,7 @@ define([
this.tabsCollection = new TabsCollection();
});
- it('displays a tab and content with proper data and order', function () {
+ it('displays a tab and content with proper data and order', function() {
var view = getView(this.collection, this.tabsCollection),
chapters = getText('.course-title'),
sections = getText('.course-subtitle'),
diff --git a/lms/static/js/spec/edxnotes/views/tabs/recent_activity_spec.js b/lms/static/js/spec/edxnotes/views/tabs/recent_activity_spec.js
index c821d321b6..cc085f768e 100644
--- a/lms/static/js/spec/edxnotes/views/tabs/recent_activity_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tabs/recent_activity_spec.js
@@ -8,35 +8,35 @@ define([
'use strict';
describe('EdxNotes RecentActivityView', function() {
var notes = {
- 'count': 3,
- 'current_page': 1,
- 'num_pages': 1,
- 'start': 0,
- 'next': null,
- 'previous': null,
- 'results': [
- {
- created: 'December 11, 2014 at 11:12AM',
- updated: 'December 11, 2014 at 11:12AM',
- text: 'Third added model',
- quote: 'Should be listed first'
- },
- {
- created: 'December 11, 2014 at 11:11AM',
- updated: 'December 11, 2014 at 11:11AM',
- text: 'Second added model',
- quote: 'Should be listed second'
- },
- {
- created: 'December 11, 2014 at 11:10AM',
- updated: 'December 11, 2014 at 11:10AM',
- text: 'First added model',
- quote: 'Should be listed third'
- }
- ]
- }, getView, tabInfo, recentActivityTabId;
+ 'count': 3,
+ 'current_page': 1,
+ 'num_pages': 1,
+ 'start': 0,
+ 'next': null,
+ 'previous': null,
+ 'results': [
+ {
+ created: 'December 11, 2014 at 11:12AM',
+ updated: 'December 11, 2014 at 11:12AM',
+ text: 'Third added model',
+ quote: 'Should be listed first'
+ },
+ {
+ created: 'December 11, 2014 at 11:11AM',
+ updated: 'December 11, 2014 at 11:11AM',
+ text: 'Second added model',
+ quote: 'Should be listed second'
+ },
+ {
+ created: 'December 11, 2014 at 11:10AM',
+ updated: 'December 11, 2014 at 11:10AM',
+ text: 'First added model',
+ quote: 'Should be listed third'
+ }
+ ]
+ }, getView, tabInfo, recentActivityTabId;
- getView = function (collection, tabsCollection, options) {
+ getView = function(collection, tabsCollection, options) {
var view;
options = _.defaults(options || {}, {
@@ -63,7 +63,7 @@ define([
recentActivityTabId = '#recent-panel';
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
TemplateHelpers.installTemplates([
'templates/edxnotes/note-item', 'templates/edxnotes/tab-item'
@@ -74,13 +74,13 @@ define([
this.tabsCollection = new TabsCollection();
});
- it('displays a tab and content with proper data and order', function () {
+ it('displays a tab and content with proper data and order', function() {
var view = getView(this.collection, this.tabsCollection);
- Helpers.verifyPaginationInfo(view, "Showing 1-3 out of 3 total", true, 1, 1);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-3 out of 3 total', true, 1, 1);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, notes);
});
- it('will not render header and footer if there are no notes', function () {
+ it('will not render header and footer if there are no notes', function() {
var notes = {
'count': 0,
'current_page': 1,
@@ -96,7 +96,7 @@ define([
expect(view.$('.pagination.pagination-full.bottom')).toHaveLength(0);
});
- it('can go to a page number', function () {
+ it('can go to a page number', function() {
var requests = AjaxHelpers.requests(this);
var notes = Helpers.createNotesData(
{
@@ -112,7 +112,7 @@ define([
collection.url = '/test/notes/';
var view = getView(collection, this.tabsCollection);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 12 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 12 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, notes);
view.$('input#page-number-input').val('2');
@@ -132,11 +132,11 @@ define([
}
);
Helpers.respondToRequest(requests, notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 11-12 out of 12 total", false, 2, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 11-12 out of 12 total', false, 2, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, notes);
});
- it('can navigate forward and backward', function () {
+ it('can navigate forward and backward', function() {
var requests = AjaxHelpers.requests(this);
var page1Notes = Helpers.createNotesData(
{
@@ -151,7 +151,7 @@ define([
collection.url = '/test/notes/';
var view = getView(collection, this.tabsCollection);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 15 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 15 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, page1Notes);
view.$('.pagination .next-page-link').click();
@@ -169,7 +169,7 @@ define([
}
);
Helpers.respondToRequest(requests, page2Notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 11-15 out of 15 total", false, 2, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 11-15 out of 15 total', false, 2, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, page2Notes);
view.$('.pagination .previous-page-link').click();
@@ -179,11 +179,11 @@ define([
);
Helpers.respondToRequest(requests, page1Notes);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 15 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 15 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, recentActivityTabId, page1Notes);
});
- it('sends correct page size value', function () {
+ it('sends correct page size value', function() {
var requests = AjaxHelpers.requests(this);
var notes = Helpers.createNotesData(
{
diff --git a/lms/static/js/spec/edxnotes/views/tabs/search_results_spec.js b/lms/static/js/spec/edxnotes/views/tabs/search_results_spec.js
index 8fe214a93c..f5952123b6 100644
--- a/lms/static/js/spec/edxnotes/views/tabs/search_results_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tabs/search_results_spec.js
@@ -9,24 +9,24 @@ define([
'use strict';
describe('EdxNotes SearchResultsView', function() {
var notes = [
- {
- created: 'December 11, 2014 at 11:12AM',
- updated: 'December 11, 2014 at 11:12AM',
- text: 'Third added model',
- quote: 'Should be listed first'
- },
- {
- created: 'December 11, 2014 at 11:11AM',
- updated: 'December 11, 2014 at 11:11AM',
- text: 'Second added model',
- quote: 'Should be listed second'
- },
- {
- created: 'December 11, 2014 at 11:10AM',
- updated: 'December 11, 2014 at 11:10AM',
- text: 'First added model',
- quote: 'Should be listed third'
- }
+ {
+ created: 'December 11, 2014 at 11:12AM',
+ updated: 'December 11, 2014 at 11:12AM',
+ text: 'Third added model',
+ quote: 'Should be listed first'
+ },
+ {
+ created: 'December 11, 2014 at 11:11AM',
+ updated: 'December 11, 2014 at 11:11AM',
+ text: 'Second added model',
+ quote: 'Should be listed second'
+ },
+ {
+ created: 'December 11, 2014 at 11:10AM',
+ updated: 'December 11, 2014 at 11:10AM',
+ text: 'First added model',
+ quote: 'Should be listed third'
+ }
],
responseJson = {
'count': 3,
@@ -39,7 +39,7 @@ define([
},
getView, submitForm, tabInfo, searchResultsTabId;
- getView = function (tabsCollection, perPage, options) {
+ getView = function(tabsCollection, perPage, options) {
options = _.defaults(options || {}, {
el: $('.wrapper-student-notes'),
tabsCollection: tabsCollection,
@@ -52,7 +52,7 @@ define([
return new SearchResultsView(options);
};
- submitForm = function (searchBox, text) {
+ submitForm = function(searchBox, text) {
searchBox.$('.search-notes-input').val(text);
searchBox.$('.search-notes-submit').click();
};
@@ -66,9 +66,9 @@ define([
view: 'Search Results'
};
- searchResultsTabId = "#search-results-panel";
+ searchResultsTabId = '#search-results-panel';
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
TemplateHelpers.installTemplates([
'templates/edxnotes/note-item', 'templates/edxnotes/tab-item'
@@ -77,23 +77,23 @@ define([
this.tabsCollection = new TabsCollection();
});
- it('does not create a tab and content on initialization', function () {
+ it('does not create a tab and content on initialization', function() {
var view = getView(this.tabsCollection);
expect(this.tabsCollection).toHaveLength(0);
expect(view.$('#search-results-panel')).not.toExist();
});
- it('displays a tab and content on search with proper data and order', function () {
+ it('displays a tab and content on search with proper data and order', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
submitForm(view.searchBox, 'second');
Helpers.respondToRequest(requests, responseJson, true);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, responseJson);
- Helpers.verifyPaginationInfo(view, "Showing 1-3 out of 3 total", true, 1, 1);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-3 out of 3 total', true, 1, 1);
});
- it('displays loading indicator when search is running', function () {
+ it('displays loading indicator when search is running', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
@@ -107,7 +107,7 @@ define([
expect(view.$('.ui-loading')).toHaveClass('is-hidden');
});
- it('displays no results message', function () {
+ it('displays no results message', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
@@ -122,7 +122,7 @@ define([
);
});
- it('does not send an additional request on switching between tabs', function () {
+ it('does not send an additional request on switching between tabs', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
@@ -142,7 +142,7 @@ define([
expect(view.$('.note')).toHaveLength(3);
});
- it('can clear search results if tab is closed', function () {
+ it('can clear search results if tab is closed', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
spyOn(view.searchBox, 'clearInput').and.callThrough();
@@ -155,7 +155,7 @@ define([
expect(view.searchBox.clearInput).toHaveBeenCalled();
});
- it('can correctly show/hide error messages', function () {
+ it('can correctly show/hide error messages', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this);
@@ -178,7 +178,7 @@ define([
expect(view.$('.wrapper-msg .copy')).toBeEmpty();
});
- it('can correctly update search results', function () {
+ it('can correctly update search results', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this),
newNotes = [{
@@ -205,12 +205,12 @@ define([
}, true);
expect(view.$('.note').length).toHaveLength(1);
- view.searchResults.collection.each(function (model, index) {
+ view.searchResults.collection.each(function(model, index) {
expect(model.get('text')).toBe(newNotes[index].text);
});
});
- it("will not render header and footer if there are no notes", function () {
+ it('will not render header and footer if there are no notes', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this),
notes = {
@@ -228,7 +228,7 @@ define([
expect(view.$('.pagination.pagination-full.bottom')).toHaveLength(0);
});
- it("can go to a page number", function () {
+ it('can go to a page number', function() {
var view = getView(this.tabsCollection),
requests = AjaxHelpers.requests(this),
notes = Helpers.createNotesData(
@@ -243,7 +243,7 @@ define([
submitForm(view.searchBox, 'awesome');
Helpers.respondToRequest(requests, notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 12 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 12 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, notes);
view.$('input#page-number-input').val('2');
@@ -263,11 +263,11 @@ define([
}
);
Helpers.respondToRequest(requests, notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 11-12 out of 12 total", false, 2, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 11-12 out of 12 total', false, 2, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, notes);
});
- it("can navigate forward and backward", function () {
+ it('can navigate forward and backward', function() {
var requests = AjaxHelpers.requests(this),
page1Notes = Helpers.createNotesData(
{
@@ -278,11 +278,11 @@ define([
start: 0
}
),
- view = getView(this.tabsCollection);
+ view = getView(this.tabsCollection);
submitForm(view.searchBox, 'awesome');
Helpers.respondToRequest(requests, page1Notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 15 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 15 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, page1Notes);
view.$('.pagination .next-page-link').click();
@@ -300,7 +300,7 @@ define([
}
);
Helpers.respondToRequest(requests, page2Notes, true);
- Helpers.verifyPaginationInfo(view, "Showing 11-15 out of 15 total", false, 2, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 11-15 out of 15 total', false, 2, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, page2Notes);
view.$('.pagination .previous-page-link').click();
@@ -310,11 +310,11 @@ define([
);
Helpers.respondToRequest(requests, page1Notes);
- Helpers.verifyPaginationInfo(view, "Showing 1-10 out of 15 total", false, 1, 2);
+ Helpers.verifyPaginationInfo(view, 'Showing 1-10 out of 15 total', false, 1, 2);
Helpers.verifyPageData(view, this.tabsCollection, tabInfo, searchResultsTabId, page1Notes);
});
- it("sends correct page size value", function () {
+ it('sends correct page size value', function() {
var requests = AjaxHelpers.requests(this),
view = getView(this.tabsCollection, 5);
diff --git a/lms/static/js/spec/edxnotes/views/tabs/tags_spec.js b/lms/static/js/spec/edxnotes/views/tabs/tags_spec.js
index fdeeec1dde..36e094f456 100644
--- a/lms/static/js/spec/edxnotes/views/tabs/tags_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tabs/tags_spec.js
@@ -10,17 +10,17 @@ define([
var notes = Helpers.getDefaultNotes(),
getView, getText, getNoteText;
- getText = function (selector) {
- return $(selector).map(function () { return _.trim($(this).text()); }).toArray();
+ getText = function(selector) {
+ return $(selector).map(function() { return _.trim($(this).text()); }).toArray();
};
- getNoteText = function (groupIndex) {
- return $($('.note-group')[groupIndex]).find('.note-excerpt-p').map(function () {
+ getNoteText = function(groupIndex) {
+ return $($('.note-group')[groupIndex]).find('.note-excerpt-p').map(function() {
return _.trim($(this).text());
}).toArray();
};
- getView = function (collection, tabsCollection, options) {
+ getView = function(collection, tabsCollection, options) {
var view;
options = _.defaults(options || {}, {
@@ -35,7 +35,7 @@ define([
return view;
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/edxnotes/edxnotes.html');
TemplateHelpers.installTemplates([
'templates/edxnotes/note-item', 'templates/edxnotes/tab-item'
@@ -45,7 +45,7 @@ define([
this.tabsCollection = new TabsCollection();
});
- it('displays a tab and content properly ordered by tag', function () {
+ it('displays a tab and content properly ordered by tag', function() {
var view = getView(this.collection, this.tabsCollection),
tags = getText('.tags-title'),
pumpkinNotes = getNoteText(0),
diff --git a/lms/static/js/spec/edxnotes/views/tabs_list_spec.js b/lms/static/js/spec/edxnotes/views/tabs_list_spec.js
index 5109405c79..80dd81b323 100644
--- a/lms/static/js/spec/edxnotes/views/tabs_list_spec.js
+++ b/lms/static/js/spec/edxnotes/views/tabs_list_spec.js
@@ -4,7 +4,7 @@ define([
], function($, TemplateHelpers, TabsCollection, TabsListView) {
'use strict';
describe('EdxNotes TabsListView', function() {
- beforeEach(function () {
+ beforeEach(function() {
TemplateHelpers.installTemplate('templates/edxnotes/tab-item');
this.collection = new TabsCollection([
{identifier: 'first-item'},
@@ -15,7 +15,7 @@ define([
}).render();
});
- it('has correct order and class names', function () {
+ it('has correct order and class names', function() {
var firstItem = this.tabsList.$('#first-item'),
secondItem = this.tabsList.$('#second-item');
@@ -24,7 +24,7 @@ define([
expect(secondItem).toHaveIndex(1);
});
- it('can add a new tab', function () {
+ it('can add a new tab', function() {
var firstItem = this.tabsList.$('#first-item'),
thirdItem;
@@ -36,7 +36,7 @@ define([
expect(this.tabsList.$('.tab')).toHaveLength(3);
});
- it('can remove tabs', function () {
+ it('can remove tabs', function() {
var secondItem = this.tabsList.$('#second-item');
this.collection.at(0).destroy(); // remove first tab
diff --git a/lms/static/js/spec/edxnotes/views/visibility_decorator_spec.js b/lms/static/js/spec/edxnotes/views/visibility_decorator_spec.js
index 3aa99b33dc..1cbb6af030 100644
--- a/lms/static/js/spec/edxnotes/views/visibility_decorator_spec.js
+++ b/lms/static/js/spec/edxnotes/views/visibility_decorator_spec.js
@@ -7,7 +7,7 @@ define([
var params = {
endpoint: '/test_endpoint',
user: 'a user',
- usageId : 'an usage',
+ usageId: 'an usage',
courseId: 'a course',
token: Helpers.makeToken(),
tokenUrl: '/test_token_url'
@@ -18,7 +18,7 @@ define([
this.wrapper = document.getElementById('edx-notes-wrapper-123');
});
- afterEach(function () {
+ afterEach(function() {
VisibilityDecorator._setVisibility(null);
while (Annotator._instances.length > 0) {
Annotator._instances[0].destroy();
diff --git a/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js b/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js
index b3911dec97..a94a62dfea 100644
--- a/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js
+++ b/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js
@@ -1,164 +1,225 @@
define([
- 'backbone',
- 'jquery',
- 'js/financial-assistance/models/financial_assistance_model',
- 'js/financial-assistance/views/financial_assistance_form_view'
- ], function (Backbone, $, FinancialAssistanceModel, FinancialAssistanceFormView) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Financial Assistance View', function () {
- var view = null,
- context = {
- fields: [
- {
- defaultValue: '',
- form: 'financial-assistance',
- instructions: 'select a course',
- label: 'Course',
- name: 'course',
- options: [
+ 'backbone',
+ 'jquery',
+ 'js/financial-assistance/models/financial_assistance_model',
+ 'js/financial-assistance/views/financial_assistance_form_view'
+], function(Backbone, $, FinancialAssistanceModel, FinancialAssistanceFormView) {
+ 'use strict';
+ /* jslint maxlen: 500 */
+
+ describe('Financial Assistance View', function() {
+ var view = null,
+ context = {
+ fields: [
+ {
+ defaultValue: '',
+ form: 'financial-assistance',
+ instructions: 'select a course',
+ label: 'Course',
+ name: 'course',
+ options: [
{'name': 'Verified with Audit', 'value': 'course-v1:HCFA+VA101+2015'},
{'name': 'Something Else', 'value': 'course-v1:SomethingX+SE101+215'},
{'name': 'Test Course', 'value': 'course-v1:TestX+T101+2015'}
- ],
- placeholder: '',
- required: true,
- requiredStr: '',
- type: 'select'
- }, {
- defaultValue: '',
- instructions: 'Specify your annual income in USD.',
- label: 'Annual Income',
- name: 'income',
- options: [
+ ],
+ placeholder: '',
+ required: true,
+ requiredStr: '',
+ type: 'select'
+ }, {
+ defaultValue: '',
+ instructions: 'Specify your annual income in USD.',
+ label: 'Annual Income',
+ name: 'income',
+ options: [
{'name': 'Less than $5,000', 'value': 'Less than $5,000'},
{'name': '$5,000 - $10,000', 'value': '$5,000 - $10,000'},
{'name': '$10,000 - $15,000', 'value': '$10,000 - $15,000'},
{'name': '$15,000 - $20,000', 'value': '$15,000 - $20,000'},
{'name': '$20,000 - $25,000', 'value': '$20,000 - $25,000'}
- ],
- placeholder: '',
- required: true,
- type: 'select'
- }, {
- defaultValue: '',
- instructions: 'Your response should contain approximately 250 - 500 words.',
- label: 'Tell us about your current financial situation, including any unusual circumstances.',
- name: 'reason_for_applying',
- placeholder: '',
- required: true,
- restrictions: {
- min_length: 800,
- max_length: 2500
- },
- type: 'textarea'
- }, {
- defaultValue: '',
- instructions: 'Use between 250 and 500 words or so in your response.',
- label: 'Tell us about your learning or professional goals. How will a Verified Certificate in this course help you achieve these goals?',
- name: 'goals',
- placeholder: '',
- required: true,
- restrictions: {
- min_length: 800,
- max_length: 2500
- },
- type: 'textarea'
- }, {
- defaultValue: '',
- instructions: 'Use between 250 and 500 words or so in your response.',
- label: 'Tell us about your plans for this course. What steps will you take to help you complete the course work a receive a certificate?',
- name: 'effort',
- placeholder: '',
- required: true,
- restrictions: {
- min_length: 800,
- max_length: 2500
- },
- type: 'textarea'
- }, {
- defaultValue: '',
- instructions: 'Annual income and personal information such as email address will not be shared.',
- label: 'I allow edX to use the information provided in this application for edX marketing purposes.',
- name: 'mktg-permission',
- placeholder: '',
- required: false,
- restrictions: {},
- type: 'checkbox'
- }
- ],
- user_details: {
- country: 'UK',
- email: 'xsy@edx.org',
- name: 'xsy',
- username: 'xsy4ever'
- },
- header_text: ['Line one.', 'Line two.'],
- student_faq_url: '/faqs',
- dashboard_url: '/dashboard',
- platform_name: 'edx',
- submit_url: '/api/financial/v1/assistance'
+ ],
+ placeholder: '',
+ required: true,
+ type: 'select'
+ }, {
+ defaultValue: '',
+ instructions: 'Your response should contain approximately 250 - 500 words.',
+ label: 'Tell us about your current financial situation, including any unusual circumstances.',
+ name: 'reason_for_applying',
+ placeholder: '',
+ required: true,
+ restrictions: {
+ min_length: 800,
+ max_length: 2500
+ },
+ type: 'textarea'
+ }, {
+ defaultValue: '',
+ instructions: 'Use between 250 and 500 words or so in your response.',
+ label: 'Tell us about your learning or professional goals. How will a Verified Certificate in this course help you achieve these goals?',
+ name: 'goals',
+ placeholder: '',
+ required: true,
+ restrictions: {
+ min_length: 800,
+ max_length: 2500
+ },
+ type: 'textarea'
+ }, {
+ defaultValue: '',
+ instructions: 'Use between 250 and 500 words or so in your response.',
+ label: 'Tell us about your plans for this course. What steps will you take to help you complete the course work a receive a certificate?',
+ name: 'effort',
+ placeholder: '',
+ required: true,
+ restrictions: {
+ min_length: 800,
+ max_length: 2500
+ },
+ type: 'textarea'
+ }, {
+ defaultValue: '',
+ instructions: 'Annual income and personal information such as email address will not be shared.',
+ label: 'I allow edX to use the information provided in this application for edX marketing purposes.',
+ name: 'mktg-permission',
+ placeholder: '',
+ required: false,
+ restrictions: {},
+ type: 'checkbox'
+ }
+ ],
+ user_details: {
+ country: 'UK',
+ email: 'xsy@edx.org',
+ name: 'xsy',
+ username: 'xsy4ever'
},
- completeForm,
- validSubmission,
- successfulSubmission,
- failedSubmission,
- invalidCountry,
- validCountry;
+ header_text: ['Line one.', 'Line two.'],
+ student_faq_url: '/faqs',
+ dashboard_url: '/dashboard',
+ platform_name: 'edx',
+ submit_url: '/api/financial/v1/assistance'
+ },
+ completeForm,
+ validSubmission,
+ successfulSubmission,
+ failedSubmission,
+ invalidCountry,
+ validCountry;
- completeForm = function() {
- var courseOptions = context.fields[0].options,
- courseSelectValue = courseOptions[courseOptions.length - 1].value;
- var incomeOptions = context.fields[1].options,
- incomeSelectValue = incomeOptions[incomeOptions.length - 1].value;
+ completeForm = function() {
+ var courseOptions = context.fields[0].options,
+ courseSelectValue = courseOptions[courseOptions.length - 1].value;
+ var incomeOptions = context.fields[1].options,
+ incomeSelectValue = incomeOptions[incomeOptions.length - 1].value;
- view.$('#financial-assistance-course').val(courseSelectValue);
- view.$('#financial-assistance-income').val(incomeSelectValue);
- view.$('textarea').html(Array(802).join("w"));
- };
+ view.$('#financial-assistance-course').val(courseSelectValue);
+ view.$('#financial-assistance-income').val(incomeSelectValue);
+ view.$('textarea').html(Array(802).join('w'));
+ };
- validSubmission = function() {
- completeForm();
- view.$('.js-submit-form').click();
- expect(view.model.save).toHaveBeenCalled();
- };
+ validSubmission = function() {
+ completeForm();
+ view.$('.js-submit-form').click();
+ expect(view.model.save).toHaveBeenCalled();
+ };
- successfulSubmission = function() {
- expect(view.$('.js-success-message').length).toEqual(0);
- validSubmission();
- view.model.trigger('sync');
- expect(view.$('.js-success-message').length).toEqual(1);
- };
+ successfulSubmission = function() {
+ expect(view.$('.js-success-message').length).toEqual(0);
+ validSubmission();
+ view.model.trigger('sync');
+ expect(view.$('.js-success-message').length).toEqual(1);
+ };
- failedSubmission = function() {
- expect(view.$('.js-success-message').length).toEqual(0);
- expect(view.$('.submission-error')).toHaveClass('hidden');
- validSubmission();
- view.model.trigger('error', {status: 500});
- expect(view.$('.js-success-message').length).toEqual(0);
- expect(view.$('.submission-error')).not.toHaveClass('hidden');
- };
+ failedSubmission = function() {
+ expect(view.$('.js-success-message').length).toEqual(0);
+ expect(view.$('.submission-error')).toHaveClass('hidden');
+ validSubmission();
+ view.model.trigger('error', {status: 500});
+ expect(view.$('.js-success-message').length).toEqual(0);
+ expect(view.$('.submission-error')).not.toHaveClass('hidden');
+ };
- invalidCountry = function() {
- expect(view.$('.js-success-message').length).toEqual(0);
- expect(view.$('.submission-error')).not.toHaveClass('hidden');
- expect(view.$('#user-country-title')).toHaveClass('error');
- expect(view.$('.js-submit-form').prop('disabled')).toBeTruthy();
- };
+ invalidCountry = function() {
+ expect(view.$('.js-success-message').length).toEqual(0);
+ expect(view.$('.submission-error')).not.toHaveClass('hidden');
+ expect(view.$('#user-country-title')).toHaveClass('error');
+ expect(view.$('.js-submit-form').prop('disabled')).toBeTruthy();
+ };
- validCountry = function() {
- expect(view.$('.js-success-message').length).toEqual(0);
- expect(view.$('.submission-error')).toHaveClass('hidden');
- expect(view.$('#user-country-title')).not.toHaveClass('error');
- expect(view.$('.js-submit-form').prop('disabled')).toBeFalsy();
- };
+ validCountry = function() {
+ expect(view.$('.js-success-message').length).toEqual(0);
+ expect(view.$('.submission-error')).toHaveClass('hidden');
+ expect(view.$('#user-country-title')).not.toHaveClass('error');
+ expect(view.$('.js-submit-form').prop('disabled')).toBeFalsy();
+ };
+ beforeEach(function() {
+ setFixtures('
');
+
+ spyOn(FinancialAssistanceModel.prototype, 'save');
+
+ view = new FinancialAssistanceFormView({
+ el: '.financial-assistance-wrapper',
+ context: context
+ });
+ });
+
+ afterEach(function() {
+ view.undelegateEvents();
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the form based on passed in context', function() {
+ var $form = view.$('.financial-assistance-form');
+
+ expect($form.find('select').first().attr('name')).toEqual(context.fields[0].name);
+ expect($form.find('select').last().attr('name')).toEqual(context.fields[1].name);
+ expect($form.find('textarea').first().attr('name')).toEqual(context.fields[2].name);
+ expect($form.find('input[type=checkbox]').attr('name')).toEqual(context.fields[5].name);
+ });
+
+ it('should not submit the form if the front end validation fails', function() {
+ expect(view.$('.submission-error')).toHaveClass('hidden');
+ view.$('.js-submit-form').click();
+ expect(view.model.save).not.toHaveBeenCalled();
+ expect(view.$('.submission-error')).not.toHaveClass('hidden');
+ });
+
+ it('should submit the form data and additional data if validation passes', function() {
+ validSubmission();
+ });
+
+ it('should submit the form and show a success message if content is valid and API returns success', function() {
+ successfulSubmission();
+ });
+
+ it('should submit the form and show an error message if content is valid and API returns error', function() {
+ failedSubmission();
+ });
+
+ it('should allow form resubmission after a front end validation failure', function() {
+ view.$('#financial-assistance-income').val(1312);
+ expect(view.model.save).not.toHaveBeenCalled();
+ validSubmission();
+ });
+
+ it('should allow form resubmission after an API error is returned', function() {
+ failedSubmission();
+ successfulSubmission();
+ });
+
+ it('renders with valid country', function() {
+ validCountry();
+ });
+
+ describe('when no country', function() {
beforeEach(function() {
- setFixtures('
');
-
- spyOn(FinancialAssistanceModel.prototype, 'save');
+ context.user_details.country = '';
view = new FinancialAssistanceFormView({
el: '.financial-assistance-wrapper',
@@ -166,72 +227,10 @@ define([
});
});
- afterEach(function() {
- view.undelegateEvents();
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the form based on passed in context', function() {
- var $form = view.$('.financial-assistance-form');
-
- expect($form.find('select').first().attr('name')).toEqual(context.fields[0].name);
- expect($form.find('select').last().attr('name')).toEqual(context.fields[1].name);
- expect($form.find('textarea').first().attr('name')).toEqual(context.fields[2].name);
- expect($form.find('input[type=checkbox]').attr('name')).toEqual(context.fields[5].name);
- });
-
- it('should not submit the form if the front end validation fails', function() {
- expect(view.$('.submission-error')).toHaveClass('hidden');
- view.$('.js-submit-form').click();
- expect(view.model.save).not.toHaveBeenCalled();
- expect(view.$('.submission-error')).not.toHaveClass('hidden');
- });
-
- it('should submit the form data and additional data if validation passes', function() {
- validSubmission();
- });
-
- it('should submit the form and show a success message if content is valid and API returns success', function() {
- successfulSubmission();
- });
-
- it('should submit the form and show an error message if content is valid and API returns error', function() {
- failedSubmission();
- });
-
- it('should allow form resubmission after a front end validation failure', function() {
- view.$('#financial-assistance-income').val(1312);
- expect(view.model.save).not.toHaveBeenCalled();
- validSubmission();
- });
-
- it('should allow form resubmission after an API error is returned', function() {
- failedSubmission();
- successfulSubmission();
- });
-
- it('renders with valid country', function(){
- validCountry();
- });
-
- describe('when no country', function(){
- beforeEach(function() {
- context.user_details.country = '';
-
- view = new FinancialAssistanceFormView({
- el: '.financial-assistance-wrapper',
- context: context
- });
- });
-
- it('renders invalid country', function() {
- invalidCountry();
- });
+ it('renders invalid country', function() {
+ invalidCountry();
});
});
- }
+ });
+}
);
diff --git a/lms/static/js/spec/groups/views/cohorts_spec.js b/lms/static/js/spec/groups/views/cohorts_spec.js
index 42dfbf214d..69dfcc030c 100644
--- a/lms/static/js/spec/groups/views/cohorts_spec.js
+++ b/lms/static/js/spec/groups/views/cohorts_spec.js
@@ -6,12 +6,12 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
'js/groups/views/cohort_discussions', 'js/groups/views/cohort_discussions_course_wide',
'js/groups/views/cohort_discussions_inline'
],
- function (Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollection, ContentGroupModel,
+ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollection, ContentGroupModel,
CourseCohortSettingsModel, AnimationUtil, Qubit, CourseCohortSettingsNotificationView, DiscussionTopicsSettingsModel,
CohortDiscussionsView, CohortCourseWideDiscussionsView, CohortInlineDiscussionsView) {
'use strict';
- describe("Cohorts View", function () {
+ describe('Cohorts View', function() {
var catLoversInitialCount = 123, dogLoversInitialCount = 456, unknownUserMessage,
createMockCohort, createMockCohorts, createMockContentGroups, createMockCohortSettingsJson,
createMockVerifiedTrackCohortsJson, flushVerifiedTrackCohortRequests, createCohortsView,
@@ -24,7 +24,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
createMockCohortDiscussionsJson, createMockCohortDiscussions, showAndAssertDiscussionTopics;
// Selectors
- var discussionsToggle ='.toggle-cohort-management-discussions',
+ var discussionsToggle = '.toggle-cohort-management-discussions',
inlineDiscussionsFormCss = '.cohort-inline-discussions-form',
courseWideDiscussionsFormCss = '.cohort-course-wide-discussions-form',
courseWideDiscussionsSaveButtonCss = '.cohort-course-wide-discussions-form .action-save',
@@ -39,7 +39,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
MOCK_STUDIO_GROUP_CONFIGURATIONS_URL = 'http://studio/group_configurations';
MOCK_VERIFIED_TRACK_COHORTING_URL = 'http://courses/foo/verified_track_content/settings';
- createMockCohort = function (name, id, userCount, groupId, userPartitionId, assignmentType) {
+ createMockCohort = function(name, id, userCount, groupId, userPartitionId, assignmentType) {
return {
id: id !== undefined ? id : 1,
name: name,
@@ -50,7 +50,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
};
};
- createMockCohorts = function (catCount, dogCount) {
+ createMockCohorts = function(catCount, dogCount) {
return {
cohorts: [
createMockCohort('Cat Lovers', 1, catCount || catLoversInitialCount),
@@ -59,7 +59,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
};
};
- createMockContentGroups = function () {
+ createMockContentGroups = function() {
return [
new ContentGroupModel({
id: 0, name: 'Dog Content', user_partition_id: MOCK_COHORTED_USER_PARTITION_ID
@@ -70,7 +70,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
];
};
- createMockCohortSettingsJson = function (isCohorted, cohortedInlineDiscussions, cohortedCourseWideDiscussions, alwaysCohortInlineDiscussions) {
+ createMockCohortSettingsJson = function(isCohorted, cohortedInlineDiscussions, cohortedCourseWideDiscussions, alwaysCohortInlineDiscussions) {
return {
id: 0,
is_cohorted: isCohorted || false,
@@ -80,21 +80,21 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
};
};
- createMockCohortSettings = function (isCohorted, cohortedInlineDiscussions, cohortedCourseWideDiscussions, alwaysCohortInlineDiscussions) {
+ createMockCohortSettings = function(isCohorted, cohortedInlineDiscussions, cohortedCourseWideDiscussions, alwaysCohortInlineDiscussions) {
return new CourseCohortSettingsModel(
createMockCohortSettingsJson(isCohorted, cohortedInlineDiscussions, cohortedCourseWideDiscussions, alwaysCohortInlineDiscussions)
);
};
- createMockCohortDiscussionsJson = function (allCohorted) {
+ createMockCohortDiscussionsJson = function(allCohorted) {
return {
course_wide_discussions: {
children: ['Topic_C_1', 'Topic_C_2'],
entries: {
Topic_C_1: {
- sort_key: null,
- is_cohorted: true,
- id: 'Topic_C_1'
+ sort_key: null,
+ is_cohorted: true,
+ id: 'Topic_C_1'
},
Topic_C_2: {
sort_key: null,
@@ -127,25 +127,25 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
};
};
- createMockCohortDiscussions = function (allCohorted) {
+ createMockCohortDiscussions = function(allCohorted) {
return new DiscussionTopicsSettingsModel(
createMockCohortDiscussionsJson(allCohorted)
);
};
- createMockVerifiedTrackCohortsJson = function (enabled) {
+ createMockVerifiedTrackCohortsJson = function(enabled) {
if (enabled) {
return {
enabled: true,
- verified_cohort_name: "Verified Track"
+ verified_cohort_name: 'Verified Track'
};
}
else {
- return { enabled: false };
+ return {enabled: false};
}
};
- createCohortsView = function (test, options) {
+ createCohortsView = function(test, options) {
var cohortsJson, cohorts, contentGroups, cohortSettings, cohortDiscussions;
options = options || {};
cohortsJson = options.cohorts ? {cohorts: options.cohorts} : createMockCohorts();
@@ -183,8 +183,8 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
// Flush out all requests to get verified track cohort information.
// The order relative to other requests is not important to encode,
// and for pre-existing test cases, we don't care about these additional requests.
- flushVerifiedTrackCohortRequests = function (enableVerifiedTrackCohorting) {
- for (var i = requests.length-1; i >= 0 ; i--) {
+ flushVerifiedTrackCohortRequests = function(enableVerifiedTrackCohorting) {
+ for (var i = requests.length - 1; i >= 0; i--) {
if (requests[i].url === MOCK_VERIFIED_TRACK_COHORTING_URL) {
AjaxHelpers.respondWithJson(
requests, createMockVerifiedTrackCohortsJson(enableVerifiedTrackCohorting), i
@@ -270,7 +270,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
var numDetails = cohortsView.$('.summary-items').children().length;
verifyMessage(expectedTitle, expectedMessageType, expectedAction, true);
expect(numDetails).toBe(expectedDetails.length);
- cohortsView.$('.summary-item').each(function (index) {
+ cohortsView.$('.summary-item').each(function(index) {
expect($(this).text().trim()).toBe(expectedDetails[index]);
});
};
@@ -293,9 +293,9 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
)
);
assignmentType = assignmentType || MOCK_MANUAL_ASSIGNMENT;
- var manualMessage = "Learners are added to this cohort only when you provide their email addresses " +
- "or usernames on this page.";
- var randomMessage = "Learners are added to this cohort automatically.";
+ var manualMessage = 'Learners are added to this cohort only when you provide their email addresses ' +
+ 'or usernames on this page.';
+ var randomMessage = 'Learners are added to this cohort automatically.';
var message = (assignmentType === MOCK_MANUAL_ASSIGNMENT) ? manualMessage : randomMessage;
expect(header.find('.cohort-management-group-setup .setup-value').text().trim().split('\n')[0]).toBe(message);
};
@@ -315,7 +315,6 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
};
showAndAssertDiscussionTopics = function(that) {
-
createCohortsView(that);
// Should see the control to toggle cohort discussions.
@@ -349,11 +348,11 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
toContain('Specify whether content-specific discussion topics are divided by cohort.');
};
- unknownUserMessage = function (name) {
- return "Unknown user: " + name;
+ unknownUserMessage = function(name) {
+ return 'Unknown user: ' + name;
};
- beforeEach(function () {
+ beforeEach(function() {
setFixtures('
' +
'');
@@ -371,7 +370,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
TemplateHelpers.installTemplate('templates/file-upload');
});
- it("shows an error if no cohorts are defined", function() {
+ it('shows an error if no cohorts are defined', function() {
createCohortsView(this, {cohorts: []});
verifyMessage(
'You currently have no cohorts configured',
@@ -385,17 +384,17 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(cohortsView.$('.cohort-discussions-nav')).toHaveClass('is-hidden');
});
- it("syncs data when membership tab is clicked", function() {
+ it('syncs data when membership tab is clicked', function() {
createCohortsView(this, {selectCohort: 1});
verifyHeader(1, 'Cat Lovers', catLoversInitialCount);
- $(cohortsView.getSectionCss("cohort_management")).click();
+ $(cohortsView.getSectionCss('cohort_management')).click();
AjaxHelpers.expectRequest(requests, 'GET', '/mock_service/cohorts');
respondToRefresh(1001, 2);
verifyHeader(1, 'Cat Lovers', 1001);
});
- it('can upload a CSV of cohort assignments if a cohort exists', function () {
- var uploadCsvToggle, fileUploadForm, fileUploadFormCss='#file-upload-form';
+ it('can upload a CSV of cohort assignments if a cohort exists', function() {
+ var uploadCsvToggle, fileUploadForm, fileUploadFormCss = '#file-upload-form';
createCohortsView(this);
@@ -422,38 +421,38 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
.toBe("Your file 'upload_file.txt' has been uploaded. Allow a few minutes for processing.");
});
- it('can show discussion topics if cohort exists', function () {
+ it('can show discussion topics if cohort exists', function() {
showAndAssertDiscussionTopics(this);
});
- describe("Cohort Selector", function () {
- it('has no initial selection', function () {
+ describe('Cohort Selector', function() {
+ it('has no initial selection', function() {
createCohortsView(this);
expect(cohortsView.$('.cohort-select').val()).toBe('');
expect(cohortsView.$('.cohort-management-group-header .title-value').text()).toBe('');
});
- it('can select a cohort', function () {
+ it('can select a cohort', function() {
createCohortsView(this, {selectCohort: 1});
verifyHeader(1, 'Cat Lovers', catLoversInitialCount);
});
- it('can switch cohort', function () {
+ it('can switch cohort', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.cohort-select').val('2').change();
verifyHeader(2, 'Dog Lovers', dogLoversInitialCount);
});
});
- describe("Verified Track Cohorting Settings View", function () {
- it('displays no message if the feature is disabled', function () {
+ describe('Verified Track Cohorting Settings View', function() {
+ it('displays no message if the feature is disabled', function() {
createCohortsView(this);
verifyVerifiedTrackMessage(false);
verifyVerifiedTrackUIUpdates(false, false);
});
- it('displays a confirmation if the feature is enabled and a verified track cohort exists', function () {
- var cohortName = "Verified Track";
+ it('displays a confirmation if the feature is enabled and a verified track cohort exists', function() {
+ var cohortName = 'Verified Track';
createCohortsView(this, {
cohorts: [
{
@@ -467,33 +466,33 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
enableVerifiedTrackCohorting: true
});
verifyVerifiedTrackMessage(
- "confirmation", "automatic cohorting for verified track learners. You cannot disable cohorts"
+ 'confirmation', 'automatic cohorting for verified track learners. You cannot disable cohorts'
);
verifyVerifiedTrackUIUpdates(true, true);
});
- it('displays an error if no verified track cohort exists', function () {
+ it('displays an error if no verified track cohort exists', function() {
createCohortsView(this, {enableVerifiedTrackCohorting: true});
verifyVerifiedTrackMessage(
- "error", "cohorting enabled for verified track learners, but the required cohort does not exist"
+ 'error', 'cohorting enabled for verified track learners, but the required cohort does not exist'
);
verifyVerifiedTrackUIUpdates(true, false);
});
- it('displays an error if cohorting is disabled', function () {
+ it('displays an error if cohorting is disabled', function() {
createCohortsView(this, {
cohortSettings: createMockCohortSettings(false),
enableVerifiedTrackCohorting: true
});
verifyVerifiedTrackMessage(
- "error", "automatic cohorting enabled for verified track learners, but cohorts are disabled"
+ 'error', 'automatic cohorting enabled for verified track learners, but cohorts are disabled'
);
verifyVerifiedTrackUIUpdates(false);
});
});
- describe("Course Cohort Settings", function () {
- it('can enable and disable cohorting', function () {
+ describe('Course Cohort Settings', function() {
+ it('can enable and disable cohorting', function() {
createCohortsView(this, {cohortSettings: createMockCohortSettings(false)});
expect(cohortsView.$('.cohorts-state').prop('checked')).toBeFalsy();
@@ -522,14 +521,14 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
- it('shows an appropriate cohort status message', function () {
- var createCourseCohortSettingsNotificationView = function (is_cohorted) {
+ it('shows an appropriate cohort status message', function() {
+ var createCourseCohortSettingsNotificationView = function(is_cohorted) {
var notificationView = new CourseCohortSettingsNotificationView({
el: $('.cohort-state-message'),
cohortEnabled: is_cohorted});
notificationView.render();
return notificationView;
- };
+ };
var notificationView = createCourseCohortSettingsNotificationView(true);
expect(notificationView.$('.action-toggle-message').text().trim()).toBe('Cohorts Enabled');
@@ -538,7 +537,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(notificationView.$('.action-toggle-message').text().trim()).toBe('Cohorts Disabled');
});
- it('shows an appropriate error message for HTTP500', function () {
+ it('shows an appropriate error message for HTTP500', function() {
createCohortsView(this, {cohortSettings: createMockCohortSettings(false)});
expect(cohortsView.$('.cohorts-state').prop('checked')).toBeFalsy();
cohortsView.$('.cohorts-state').prop('checked', true).change();
@@ -548,8 +547,8 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Cohort Group Header", function () {
- it("renders header correctly", function () {
+ describe('Cohort Group Header', function() {
+ it('renders header correctly', function() {
var cohortName = 'Transformers',
newCohortName = 'X Men';
var expectedRequest = function(assignment_type) {
@@ -598,8 +597,8 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Cohort Editor Tab Panel", function () {
- it("initially selects the Manage Students tab", function () {
+ describe('Cohort Editor Tab Panel', function() {
+ it('initially selects the Manage Students tab', function() {
createCohortsView(this, {selectCohort: 1});
expect(cohortsView.$('.tab-manage_students')).toHaveClass('is-selected');
expect(cohortsView.$('.tab-settings')).not.toHaveClass('is-selected');
@@ -607,7 +606,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(cohortsView.$('.tab-content-settings')).toHaveClass('is-hidden');
});
- it("can select the Settings tab", function () {
+ it('can select the Settings tab', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.tab-settings a').click();
expect(cohortsView.$('.tab-manage_students')).not.toHaveClass('is-selected');
@@ -617,11 +616,11 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Add Cohorts Form", function () {
+ describe('Add Cohorts Form', function() {
var defaultCohortName = 'New Cohort';
var assignmentType = 'random';
- it("can add a cohort", function() {
+ it('can add a cohort', function() {
var contentGroupId = 0;
createCohortsView(this, {cohorts: []});
cohortsView.$('.action-create').click();
@@ -645,7 +644,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
AjaxHelpers.respondWithJson(
requests,
- { cohorts: createMockCohort(defaultCohortName, 1, 0, null, null, assignmentType) }
+ {cohorts: createMockCohort(defaultCohortName, 1, 0, null, null, assignmentType)}
);
verifyMessage(
'The ' + defaultCohortName + ' cohort has been created.' +
@@ -658,8 +657,8 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(getAddModal().find('.cohort-management-settings-form').length).toBe(0);
});
- it("has default assignment type set to manual", function() {
- var cohortName = "iCohort";
+ it('has default assignment type set to manual', function() {
+ var cohortName = 'iCohort';
createCohortsView(this, {cohorts: []});
cohortsView.$('.action-create').click();
cohortsView.$('.cohort-name').val(cohortName);
@@ -677,12 +676,12 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
AjaxHelpers.respondWithJson(
requests,
- { cohorts: createMockCohort(cohortName, 1, 0, null, null, MOCK_MANUAL_ASSIGNMENT) }
+ {cohorts: createMockCohort(cohortName, 1, 0, null, null, MOCK_MANUAL_ASSIGNMENT)}
);
verifyHeader(1, cohortName, 0, MOCK_MANUAL_ASSIGNMENT);
});
- it("trims off whitespace before adding a cohort", function() {
+ it('trims off whitespace before adding a cohort', function() {
createCohortsView(this);
cohortsView.$('.action-create').click();
cohortsView.$('.cohort-name').val(' New Cohort ');
@@ -690,14 +689,14 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expectCohortAddRequest('New Cohort', null, null, MOCK_MANUAL_ASSIGNMENT);
});
- it("does not allow a blank cohort name to be submitted", function() {
+ it('does not allow a blank cohort name to be submitted', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.action-create').click();
cohortsView.$('.cohort-name').val(' ');
saveFormAndExpectErrors('add', ['You must specify a name for the cohort']);
});
- it("shows a message saving when choosing to have content groups but not selecting one", function() {
+ it('shows a message saving when choosing to have content groups but not selecting one', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.action-create').click();
cohortsView.$('.cohort-name').val('New Cohort');
@@ -705,7 +704,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
saveFormAndExpectErrors('add', ['You did not select a content group']);
});
- it("shows two message when both fields have problems", function() {
+ it('shows two message when both fields have problems', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.action-create').click();
cohortsView.$('.cohort-name').val('');
@@ -716,7 +715,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
]);
});
- it("shows a message when adding a cohort returns a server error", function() {
+ it('shows a message when adding a cohort returns a server error', function() {
var addModal;
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.action-create').click();
@@ -744,7 +743,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(cohortsView.$('.cohort-management-nav')).not.toHaveClass('is-disabled');
});
- it("shows an error if canceled when no cohorts are defined", function() {
+ it('shows an error if canceled when no cohorts are defined', function() {
createCohortsView(this, {cohorts: []});
cohortsView.$('.action-create').click();
expect(getAddModal().find('.cohort-management-settings-form').length).toBe(1);
@@ -757,7 +756,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
});
- it("hides any error message when switching to show a cohort", function() {
+ it('hides any error message when switching to show a cohort', function() {
createCohortsView(this, {selectCohort: 1});
// First try to save a blank name to create a message
@@ -771,7 +770,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
verifyNoMessage();
});
- it("hides any error message when canceling the form", function() {
+ it('hides any error message when canceling the form', function() {
createCohortsView(this, {selectCohort: 1});
// First try to save a blank name to create a message
@@ -785,7 +784,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Add Students Button", function () {
+ describe('Add Students Button', function() {
var getStudentInput, addStudents, respondToAdd;
getStudentInput = function() {
@@ -800,7 +799,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
respondToAdd = function(result) {
AjaxHelpers.respondWithJson(
requests,
- _.extend({ unknown: [], added: [], present: [], changed: [], success: true }, result)
+ _.extend({unknown: [], added: [], present: [], changed: [], success: true}, result)
);
};
@@ -816,7 +815,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
var catLoversUpdatedCount = catLoversInitialCount + 1;
createCohortsView(this, {selectCohort: 1});
addStudents('student@sample.com');
- respondToAdd({ added: ['student@sample.com'] });
+ respondToAdd({added: ['student@sample.com']});
respondToRefresh(catLoversUpdatedCount, dogLoversInitialCount);
verifyHeader(1, 'Cat Lovers', catLoversUpdatedCount);
verifyMessage('1 student has been added to this cohort', 'confirmation');
@@ -829,7 +828,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
AjaxHelpers.expectRequest(
requests, 'POST', '/mock_service/cohorts/1/add', 'users=unknown%40sample.com'
);
- respondToAdd({ unknown: ['unknown@sample.com'] });
+ respondToAdd({unknown: ['unknown@sample.com']});
respondToRefresh(catLoversInitialCount, dogLoversInitialCount);
verifyHeader(1, 'Cat Lovers', catLoversInitialCount);
verifyDetailedMessage('There was an error when trying to add students:', 'error',
@@ -845,9 +844,9 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
addStudents(sixUsers);
AjaxHelpers.expectRequest(
requests, 'POST', '/mock_service/cohorts/1/add',
- 'users=' + sixUsers.replace(/@/g, "%40").replace(/, /g, "%2C+")
+ 'users=' + sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+')
);
- respondToAdd({ unknown: [
+ respondToAdd({unknown: [
'unknown1@sample.com',
'unknown2@sample.com',
'unknown3@sample.com',
@@ -882,7 +881,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
addStudents(sixUsers);
AjaxHelpers.expectRequest(requests, 'POST', '/mock_service/cohorts/1/add',
- 'users=' + sixUsers.replace(/@/g, "%40").replace(/, /g, "%2C+")
+ 'users=' + sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+')
);
respondToAdd({
changed: [
@@ -896,9 +895,9 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
verifyDetailedMessage('3 students have been added to this cohort', 'confirmation',
[
- "2 students were removed from cohort 2",
- "1 student was removed from cohort 3",
- "1 student was already in the cohort"
+ '2 students were removed from cohort 2',
+ '1 student was removed from cohort 3',
+ '1 student was already in the cohort'
]
);
expect(getStudentInput().val()).toBe('');
@@ -922,14 +921,14 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
// Now verify that the error is removed on a subsequent add
addStudents('student@sample.com');
- respondToAdd({ added: ['student@sample.com'] });
+ respondToAdd({added: ['student@sample.com']});
respondToRefresh(catLoversInitialCount + 1, dogLoversInitialCount);
verifyMessage('1 student has been added to this cohort', 'confirmation');
});
});
- describe("Cohort Settings", function() {
- describe("Content Group Setting", function() {
+ describe('Cohort Settings', function() {
+ describe('Content Group Setting', function() {
var createCohortsViewWithDeletedContentGroup;
createCohortsViewWithDeletedContentGroup = function(test) {
@@ -947,7 +946,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
};
- it("shows a select element with an option for each content group", function () {
+ it('shows a select element with an option for each content group', function() {
var options;
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.tab-settings a').click();
@@ -959,7 +958,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect($(options[2]).text().trim()).toBe('Dog Content');
});
- it("can select a single content group", function () {
+ it('can select a single content group', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.tab-settings a').click();
@@ -985,7 +984,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
verifyMessage('Saved cohort', 'confirmation');
});
- it("can clear selected content group", function () {
+ it('can clear selected content group', function() {
createCohortsView(this, {
cohorts: [
{id: 1, name: 'Cat Lovers', group_id: 0, 'assignment_type': MOCK_MANUAL_ASSIGNMENT}
@@ -1014,7 +1013,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
verifyMessage('Saved cohort', 'confirmation');
});
- it("shows a message saving when choosing to have content groups but not selecting one", function() {
+ it('shows a message saving when choosing to have content groups but not selecting one', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.tab-settings a').click();
cohortsView.$('.cohort-name').val('New Cohort');
@@ -1022,7 +1021,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
saveFormAndExpectErrors('update', ['You did not select a content group']);
});
- it("shows a message when the selected content group does not exist", function () {
+ it('shows a message when the selected content group does not exist', function() {
createCohortsViewWithDeletedContentGroup(this);
cohortsView.$('.tab-settings a').click();
expect(cohortsView.$('option.option-unavailable').text().trim()).toBe('Deleted Content Group');
@@ -1031,7 +1030,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
});
- it("can clear a selected content group which had been deleted", function () {
+ it('can clear a selected content group which had been deleted', function() {
createCohortsViewWithDeletedContentGroup(this);
cohortsView.$('.tab-settings a').click();
expect(cohortsView.$('.radio-yes').prop('checked')).toBeTruthy();
@@ -1050,13 +1049,13 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(cohortsView.$('.cohort-management-details-association-course .copy-error').text().trim()).toBe('');
});
- it("shows an error when saving with a deleted content group", function () {
+ it('shows an error when saving with a deleted content group', function() {
createCohortsViewWithDeletedContentGroup(this);
cohortsView.$('.tab-settings a').click();
saveFormAndExpectErrors('save', ['The selected content group does not exist']);
});
- it("shows an error when the save fails", function () {
+ it('shows an error when the save fails', function() {
createCohortsView(this, {selectCohort: 1});
cohortsView.$('.tab-settings a').click();
cohortsView.$('.action-save').click();
@@ -1067,7 +1066,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
});
- it("shows an error message when no content groups are specified", function () {
+ it('shows an error message when no content groups are specified', function() {
var message;
createCohortsView(this, {selectCohort: 1, contentGroups: []});
cohortsView.$('.tab-settings a').click();
@@ -1081,7 +1080,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
);
});
- it("can update existing cohort settings", function () {
+ it('can update existing cohort settings', function() {
var cohortName = 'Transformers',
newCohortName = 'X Men';
var expectedRequest = function(assignment_type) {
@@ -1143,7 +1142,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
saveFormAndExpectErrors('update', ['You must specify a name for the cohort']);
});
- it("assignment settings are disabled for default cohort", function() {
+ it('assignment settings are disabled for default cohort', function() {
createCohortsView(this, {
cohorts: [
{
@@ -1159,10 +1158,10 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
// We have a single random cohort so we should not be allowed to change it assignment type
expect(cohortsView.$('.cohort-management-assignment-type-settings')).toHaveClass('is-disabled');
- expect(cohortsView.$('.copy-error').text()).toContain("There must be one cohort to which students can automatically be assigned.");
+ expect(cohortsView.$('.copy-error').text()).toContain('There must be one cohort to which students can automatically be assigned.');
});
- it("cancel settings works", function() {
+ it('cancel settings works', function() {
createCohortsView(this, {selectCohort: 1, contentGroups: []});
cohortsView.$('.tab-settings a').click();
cohortsView.$('.cohort-name').val('One Two Three');
@@ -1173,7 +1172,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Discussion Topics", function() {
+ describe('Discussion Topics', function() {
var createCourseWideView, createInlineView,
inlineView, courseWideView, assertCohortedTopics;
@@ -1208,8 +1207,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
showAndAssertDiscussionTopics(this);
});
- describe("Course Wide", function() {
-
+ describe('Course Wide', function() {
it('shows the "Save" button as disabled initially', function() {
createCourseWideView(this);
expect(courseWideView.$(courseWideDiscussionsSaveButtonCss).prop('disabled')).toBeTruthy();
@@ -1298,7 +1296,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(courseWideView.$('.message-title').text().trim()).toBe(expectedTitle);
});
- it('shows an appropriate error message for HTTP500', function () {
+ it('shows an appropriate error message for HTTP500', function() {
createCourseWideView(this);
$(courseWideView.$('.check-discussion-subcategory-course-wide')[1]).prop('checked', 'checked').change();
@@ -1310,7 +1308,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
});
- describe("Inline", function() {
+ describe('Inline', function() {
var enableSaveButton, mockGetRequest, verifySuccess, mockPatchRequest;
enableSaveButton = function() {
@@ -1485,7 +1483,6 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
});
it('shows an appropriate message when no inline topics exist', function() {
-
var topicsJson, discussionTopicsSettingsModel;
topicsJson = {
@@ -1493,9 +1490,9 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
children: ['Topic_C_1'],
entries: {
Topic_C_1: {
- sort_key: null,
- is_cohorted: true,
- id: 'Topic_C_1'
+ sort_key: null,
+ is_cohorted: true,
+ id: 'Topic_C_1'
}
}
},
@@ -1508,7 +1505,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
createInlineView(this, discussionTopicsSettingsModel);
- var expectedTitle = "No content-specific discussion topics exist.";
+ var expectedTitle = 'No content-specific discussion topics exist.';
expect(inlineView.$('.no-topics').text().trim()).toBe(expectedTitle);
});
@@ -1531,7 +1528,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
expect(inlineView.$('.message-title').text().trim()).toBe(expectedTitle);
});
- it('shows an appropriate error message for HTTP500', function () {
+ it('shows an appropriate error message for HTTP500', function() {
createInlineView(this);
enableSaveButton();
@@ -1542,9 +1539,7 @@ define(['backbone', 'jquery', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers
var expectedTitle = "We've encountered an error. Refresh your browser and then try again.";
expect(inlineView.$('.message-title').text().trim()).toBe(expectedTitle);
});
-
});
-
});
});
});
diff --git a/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js
index dba2657a43..6be15fdae5 100644
--- a/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js
@@ -1,25 +1,24 @@
define([
- 'jquery',
- 'js/certificates/views/certificate_bulk_whitelist'
- ],
+ 'jquery',
+ 'js/certificates/views/certificate_bulk_whitelist'
+],
function($, CertificateBulkWhiteListView) {
'use strict';
- describe("certificate bulk exceptions generation", function() {
-
+ describe('certificate bulk exceptions generation', function() {
var certificate_bulk_exception_url = 'test/url/';
var SELECTORS = {
- upload_csv_button: ".upload-csv-button",
- bulk_white_list_exception_form: "form#bulk-white-list-exception-form",
- bulk_exception_results: ".bulk-exception-results"
+ upload_csv_button: '.upload-csv-button',
+ bulk_white_list_exception_form: 'form#bulk-white-list-exception-form',
+ bulk_exception_results: '.bulk-exception-results'
};
beforeEach(function() {
setFixtures();
var fixture = readFixtures(
- "templates/instructor/instructor_dashboard_2/certificate-bulk-white-list.underscore"
+ 'templates/instructor/instructor_dashboard_2/certificate-bulk-white-list.underscore'
);
setFixtures(
- "" +
+ "' +
"
"
);
@@ -31,11 +30,11 @@ define([
it('bind the ajax call and the result will be success', function() {
var submitCallback;
- spyOn($, "ajax").and.callFake(function(params) {
+ spyOn($, 'ajax').and.callFake(function(params) {
params.success({
row_errors: {},
general_errors: [],
- success: ["user test in row# 1"]
+ success: ['user test in row# 1']
});
return {
always: function() {}
@@ -50,10 +49,10 @@ define([
it('bind the ajax call and the result will be general error', function() {
var submitCallback;
- spyOn($, "ajax").and.callFake(function(params) {
+ spyOn($, 'ajax').and.callFake(function(params) {
params.success({
row_errors: {},
- general_errors: ["File is not attached."],
+ general_errors: ['File is not attached.'],
success: []
});
return {
@@ -68,7 +67,7 @@ define([
it('bind the ajax call and the result will be singular form of row errors', function() {
var submitCallback;
- spyOn($, "ajax").and.callFake(function(params) {
+ spyOn($, 'ajax').and.callFake(function(params) {
params.success({
general_errors: [],
row_errors: {
@@ -90,12 +89,11 @@ define([
expect($(SELECTORS.bulk_exception_results).text()).toContain('1 learner does not exist in LMS');
expect($(SELECTORS.bulk_exception_results).text()).toContain('1 learner is already white listed');
expect($(SELECTORS.bulk_exception_results).text()).toContain('1 learner is not enrolled in course');
-
});
it('bind the ajax call and the result will be plural form of row errors', function() {
var submitCallback;
- spyOn($, "ajax").and.callFake(function(params) {
+ spyOn($, 'ajax').and.callFake(function(params) {
params.success({
general_errors: [],
row_errors: {
@@ -117,16 +115,15 @@ define([
expect($(SELECTORS.bulk_exception_results).text()).toContain('2 learners do not exist in LMS');
expect($(SELECTORS.bulk_exception_results).text()).toContain('2 learners are already white listed');
expect($(SELECTORS.bulk_exception_results).text()).toContain('2 learners are not enrolled in course');
-
});
it('toggle message details', function() {
var submitCallback;
- spyOn($, "ajax").and.callFake(function(params) {
+ spyOn($, 'ajax').and.callFake(function(params) {
params.success({
row_errors: {},
general_errors: [],
- success: ["user test in row# 1"]
+ success: ['user test in row# 1']
});
return {
always: function() {}
@@ -135,11 +132,9 @@ define([
submitCallback = jasmine.createSpy().and.returnValue();
this.view.$el.find(SELECTORS.bulk_white_list_exception_form).submit(submitCallback);
this.view.$el.find(SELECTORS.upload_csv_button).click();
- expect(this.view.$el.find("div.message > .successfully-added")).toBeHidden();
- this.view.$el.find(".arrow#successfully-added").trigger( "click" );
- expect(this.view.$el.find("div.message > .successfully-added")).toBeVisible();
-
+ expect(this.view.$el.find('div.message > .successfully-added')).toBeHidden();
+ this.view.$el.find('.arrow#successfully-added').trigger('click');
+ expect(this.view.$el.find('div.message > .successfully-added')).toBeVisible();
});
-
});
});
diff --git a/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js
index a6e961d7f3..f80c932785 100644
--- a/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js
@@ -1,16 +1,16 @@
-/*global define, sinon */
+/* global define, sinon */
define([
- 'jquery',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/certificates/models/certificate_exception',
- 'js/certificates/views/certificate_whitelist',
- 'js/certificates/views/certificate_whitelist_editor',
- 'js/certificates/collections/certificate_whitelist'
- ],
+ 'jquery',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/certificates/models/certificate_exception',
+ 'js/certificates/views/certificate_whitelist',
+ 'js/certificates/views/certificate_whitelist_editor',
+ 'js/certificates/collections/certificate_whitelist'
+],
function($, AjaxHelpers, CertificateExceptionModel, CertificateWhiteListView, CertificateWhiteListEditorView,
CertificateWhiteListCollection) {
'use strict';
- describe("edx.certificates.models.certificates_exception.CertificateExceptionModel", function() {
+ describe('edx.certificates.models.certificates_exception.CertificateExceptionModel', function() {
var certificate_exception = null;
var assertValid = function(fields, isValid, expectedErrors) {
certificate_exception.set(fields);
@@ -29,48 +29,47 @@ define([
};
beforeEach(function() {
-
certificate_exception = new CertificateExceptionModel({user_name: 'test_user'}, {url: 'test/url/'});
certificate_exception.set({
- notes: "Test notes"
+ notes: 'Test notes'
});
});
- it("accepts valid email addresses", function() {
- assertValid({user_email: "bob@example.com"}, true);
- assertValid({user_email: "bob+smith@example.com"}, true);
- assertValid({user_email: "bob+smith@example.com"}, true);
- assertValid({user_email: "bob+smith@example.com"}, true);
- assertValid({user_email: "bob@test.example.com"}, true);
- assertValid({user_email: "bob@test-example.com"}, true);
+ it('accepts valid email addresses', function() {
+ assertValid({user_email: 'bob@example.com'}, true);
+ assertValid({user_email: 'bob+smith@example.com'}, true);
+ assertValid({user_email: 'bob+smith@example.com'}, true);
+ assertValid({user_email: 'bob+smith@example.com'}, true);
+ assertValid({user_email: 'bob@test.example.com'}, true);
+ assertValid({user_email: 'bob@test-example.com'}, true);
});
- it("displays username or email required error", function() {
- assertValid({user_name: ""}, false, EXPECTED_ERRORS.user_name_or_email_required);
+ it('displays username or email required error', function() {
+ assertValid({user_name: ''}, false, EXPECTED_ERRORS.user_name_or_email_required);
});
});
- describe("edx.certificates.collections.certificate_whitelist.CertificateWhiteList", function() {
+ describe('edx.certificates.collections.certificate_whitelist.CertificateWhiteList', function() {
var certificate_white_list = null,
certificate_exception_url = 'test/url/';
var certificates_exceptions_json = [
{
id: 1,
user_id: 1,
- user_name: "test1",
- user_email: "test1@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception"
+ user_name: 'test1',
+ user_email: 'test1@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception'
},
{
id: 2,
- user_id : 2,
- user_name: "test2",
- user_email : "test2@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception"
+ user_id: 2,
+ user_name: 'test2',
+ user_email: 'test2@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception'
}
];
@@ -83,7 +82,7 @@ define([
});
});
- it("has 2 models in the collection after initialization", function() {
+ it('has 2 models in the collection after initialization', function() {
expect(certificate_white_list.models.length).toEqual(2);
});
@@ -97,7 +96,7 @@ define([
expect(certificate_white_list.getModel({user_name: 'test1'}).attributes).toEqual(
{
id: 1, user_id: 1, user_name: 'test1', user_email: 'test1@test.com',
- course_id: 'edX/test/course', created: "Thursday, October 29, 2015",
+ course_id: 'edX/test/course', created: 'Thursday, October 29, 2015',
notes: 'test notes for test certificate exception', certificate_generated: ''
}
);
@@ -105,27 +104,27 @@ define([
expect(certificate_white_list.getModel({user_email: 'test2@test.com'}).attributes).toEqual(
{
id: 2, user_id: 2, user_name: 'test2', user_email: 'test2@test.com',
- course_id: 'edX/test/course', created: "Thursday, October 29, 2015",
+ course_id: 'edX/test/course', created: 'Thursday, October 29, 2015',
notes: 'test notes for test certificate exception', certificate_generated: ''
}
);
});
- it('sends empty certificate exceptions list if no model is added', function(){
+ it('sends empty certificate exceptions list if no model is added', function() {
var successCallback = sinon.spy(),
errorCallback = sinon.spy(),
requests = AjaxHelpers.requests(this),
add_students = 'all';
var expected = {
url: certificate_exception_url + add_students,
- postData : []
+ postData: []
};
certificate_white_list.sync({success: successCallback, error: errorCallback}, add_students);
AjaxHelpers.expectJsonRequest(requests, 'POST', expected.url, expected.postData);
});
- it('syncs only newly added models with the server', function(){
+ it('syncs only newly added models with the server', function() {
var successCallback = sinon.spy(),
errorCallback = sinon.spy(),
requests = AjaxHelpers.requests(this),
@@ -136,21 +135,21 @@ define([
var expected = {
url: certificate_exception_url + add_students,
- postData : [
- {user_id: "",
- user_name: "test3",
- user_email: "",
- created: "",
- notes: "test3 notes",
- certificate_generated : '',
+ postData: [
+ {user_id: '',
+ user_name: 'test3',
+ user_email: '',
+ created: '',
+ notes: 'test3 notes',
+ certificate_generated: '',
new: true}
- ]
+ ]
};
AjaxHelpers.expectJsonRequest(requests, 'POST', expected.url, expected.postData);
});
});
- describe("edx.certificates.views.certificate_whitelist.CertificateWhiteListView", function() {
+ describe('edx.certificates.views.certificate_whitelist.CertificateWhiteListView', function() {
var view = null,
certificate_exception_url = 'test/url/';
@@ -158,28 +157,28 @@ define([
{
id: 1,
user_id: 1,
- user_name: "test1",
- user_email: "test1@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception"
+ user_name: 'test1',
+ user_email: 'test1@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception'
},
{
id: 2,
- user_id : 2,
- user_name: "test2",
- user_email : "test2@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception"
+ user_id: 2,
+ user_name: 'test2',
+ user_email: 'test2@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception'
}
];
beforeEach(function() {
setFixtures();
var fixture =
- readFixtures("templates/instructor/instructor_dashboard_2/certificate-white-list.underscore");
- setFixtures("" +
+ readFixtures('templates/instructor/instructor_dashboard_2/certificate-white-list.underscore');
+ setFixtures("' +
"
");
this.certificate_white_list = new CertificateWhiteListCollection(certificates_exceptions_json, {
@@ -197,12 +196,12 @@ define([
view.render();
});
- it("verifies view is initialized and rendered successfully", function() {
+ it('verifies view is initialized and rendered successfully', function() {
expect(view).not.toBe(undefined);
expect(view.$el.find('table tbody tr').length).toBe(2);
});
- it("verifies that Generate Exception Certificate button is disabled", function() {
+ it('verifies that Generate Exception Certificate button is disabled', function() {
expect(view.$el.find('table tbody tr').length).toBe(2);
expect(view.$el.find('#generate-exception-certificates').first()).not.toHaveAttr('disabled');
@@ -218,10 +217,10 @@ define([
expect(view.$el.find('table tbody tr').length).toBe(2);
});
- it("verifies view is rendered on add/update to collection", function() {
+ it('verifies view is rendered on add/update to collection', function() {
var user = 'test1',
notes = 'test1 notes updates',
- email='update_email@test.com';
+ email = 'update_email@test.com';
// Add another model in collection and verify it is rendered
view.collection.add({user_name: 'test3', notes: 'test3 notes'});
@@ -238,68 +237,68 @@ define([
toMatch(email);
});
- it('verifies collection sync is called when "Generate Exception Certificates" is clicked', function(){
+ it('verifies collection sync is called when "Generate Exception Certificates" is clicked', function() {
var successCallback = sinon.spy(),
errorCallback = sinon.spy();
- sinon.stub(view, "showSuccess").returns(successCallback);
- sinon.stub(view, "showError").returns(errorCallback);
- sinon.stub(view.collection, "sync");
+ sinon.stub(view, 'showSuccess').returns(successCallback);
+ sinon.stub(view, 'showError').returns(errorCallback);
+ sinon.stub(view.collection, 'sync');
- view.$el.find("#generate-exception-certificates").click();
+ view.$el.find('#generate-exception-certificates').click();
expect(view.collection.sync.called).toBe(true);
expect(view.collection.sync.calledWith({success: successCallback, error: errorCallback})).
toBe(true);
});
- it('verifies sync is called with "new/all" argument depending upon selected radio button', function(){
+ it('verifies sync is called with "new/all" argument depending upon selected radio button', function() {
var successCallback = sinon.spy(),
errorCallback = sinon.spy();
- sinon.stub(view, "showSuccess").returns(successCallback);
- sinon.stub(view, "showError").returns(errorCallback);
- sinon.stub(view.collection, "sync");
+ sinon.stub(view, 'showSuccess').returns(successCallback);
+ sinon.stub(view, 'showError').returns(errorCallback);
+ sinon.stub(view.collection, 'sync');
- view.$el.find("#generate-exception-certificates").click();
+ view.$el.find('#generate-exception-certificates').click();
// By default 'Generate a Certificate for all New additions to the Exception list ' is selected
expect(view.collection.sync.calledWith({success: successCallback, error: errorCallback}), 'new').
toBe(true);
// Select 'Generate a Certificate for all users on the Exception list ' option
- view.$el.find("input:radio[name=generate-exception-certificates-radio][value=all]").click();
- view.$el.find("#generate-exception-certificates").click();
+ view.$el.find('input:radio[name=generate-exception-certificates-radio][value=all]').click();
+ view.$el.find('#generate-exception-certificates').click();
expect(view.collection.sync.calledWith({success: successCallback, error: errorCallback}), 'all').
toBe(true);
});
});
- describe("edx.certificates.views.certificate_whitelist_editor.CertificateWhiteListEditorView", function() {
+ describe('edx.certificates.views.certificate_whitelist_editor.CertificateWhiteListEditorView', function() {
var view = null,
- list_view= null,
+ list_view = null,
certificate_exception_url = 'test/url/';
var certificates_exceptions_json = [
{
url: certificate_exception_url,
id: 1,
user_id: 1,
- user_name: "test1",
- user_email: "test1@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception",
+ user_name: 'test1',
+ user_email: 'test1@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception',
new: true
},
{
url: certificate_exception_url,
id: 2,
- user_id : 2,
- user_name: "test2",
- user_email : "test2@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate exception"
+ user_id: 2,
+ user_name: 'test2',
+ user_email: 'test2@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate exception'
}
];
@@ -307,16 +306,16 @@ define([
setFixtures();
var fixture = readFixtures(
- "templates/instructor/instructor_dashboard_2/certificate-white-list-editor.underscore"
+ 'templates/instructor/instructor_dashboard_2/certificate-white-list-editor.underscore'
);
var fixture_2 = readFixtures(
- "templates/instructor/instructor_dashboard_2/certificate-white-list.underscore"
+ 'templates/instructor/instructor_dashboard_2/certificate-white-list.underscore'
);
setFixtures(
- "" +
- "" +
+ "' +
+ "' +
"
" +
"
"
);
@@ -341,28 +340,28 @@ define([
list_view.render();
});
- it("verifies view is initialized and rendered successfully", function() {
+ it('verifies view is initialized and rendered successfully', function() {
expect(view).not.toBe(undefined);
expect(view.$el.find('#certificate-exception').length).toBe(1);
expect(view.$el.find('#notes').length).toBe(1);
expect(view.$el.find('#add-exception').length).toBe(1);
});
- it("verifies success and error messages", function() {
- var message_selector='.message',
+ it('verifies success and error messages', function() {
+ var message_selector = '.message',
success_message = 'test_user has been successfully added to the exception list. Click Generate' +
' Exception Certificate below to send the certificate.',
requests = AjaxHelpers.requests(this),
- duplicate_user='test_user';
+ duplicate_user = 'test_user';
var error_messages = {
empty_user_name_email: 'Student username/email field is required and can not be empty. ' +
'Kindly fill in username/email and then press "Add to Exception List" button.',
- duplicate_user: "" + (duplicate_user) + " already in exception list.
"
+ duplicate_user: '' + (duplicate_user) + ' already in exception list.
'
};
// click 'Add Exception' button with empty username/email field
- view.$el.find('#certificate-exception').val("");
+ view.$el.find('#certificate-exception').val('');
view.$el.find('#add-exception').click();
// Verify error message for missing username/email
@@ -370,19 +369,19 @@ define([
// Add a new Exception to list
view.$el.find('#certificate-exception').val(duplicate_user);
- view.$el.find('#notes').val("test user notes");
+ view.$el.find('#notes').val('test user notes');
view.$el.find('#add-exception').click();
AjaxHelpers.respondWithJson(
requests,
{
id: 3,
- user_id : 3,
+ user_id: 3,
user_name: duplicate_user,
- user_email : "test2@test.com",
- course_id: "edX/test/course",
- created: "Thursday, October 29, 2015",
- notes: "test user notes"
+ user_email: 'test2@test.com',
+ course_id: 'edX/test/course',
+ created: 'Thursday, October 29, 2015',
+ notes: 'test user notes'
}
);
@@ -391,18 +390,18 @@ define([
// Add a duplicate Certificate Exception
view.$el.find('#certificate-exception').val(duplicate_user);
- view.$el.find('#notes').val("test user notes");
+ view.$el.find('#notes').val('test user notes');
view.$el.find('#add-exception').click();
// Verify success message
expect(view.$el.find(message_selector).html()).toEqual(error_messages.duplicate_user);
});
- it('verifies certificate exception can be deleted by clicking "delete" ', function(){
+ it('verifies certificate exception can be deleted by clicking "delete" ', function() {
var user_name = 'test1',
certificate_exception_selector = "div.white-listed-students table tr:contains('" + user_name + "')",
delete_btn_selector =
- certificate_exception_selector + " td .delete-exception",
+ certificate_exception_selector + ' td .delete-exception',
requests = AjaxHelpers.requests(this);
$(delete_btn_selector).click();
@@ -410,9 +409,7 @@ define([
// Verify the certificate exception is removed from the list
expect($(certificate_exception_selector).length).toBe(0);
-
});
-
});
}
);
diff --git a/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js
index bf08e3436c..dac9834918 100644
--- a/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js
@@ -1,15 +1,15 @@
-/*global define */
+/* global define */
define([
- 'jquery',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/certificates/models/certificate_invalidation',
- 'js/certificates/views/certificate_invalidation_view',
- 'js/certificates/collections/certificate_invalidation_collection'
- ],
+ 'jquery',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/certificates/models/certificate_invalidation',
+ 'js/certificates/views/certificate_invalidation_view',
+ 'js/certificates/collections/certificate_invalidation_collection'
+],
function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationView,
CertificateInvalidationCollection) {
'use strict';
- describe("Field validation of invalidation model.", function() {
+ describe('Field validation of invalidation model.', function() {
var certificate_invalidation = null;
var assertValid = function(fields, isValid, expectedErrors) {
certificate_invalidation.set(fields);
@@ -28,45 +28,44 @@ define([
};
beforeEach(function() {
-
certificate_invalidation = new CertificateInvalidationModel({user: 'test_user'}, {url: 'test/url/'});
certificate_invalidation.set({
- notes: "Test notes"
+ notes: 'Test notes'
});
});
- it("accepts valid email addresses", function() {
- assertValid({user: "bob@example.com"}, true);
- assertValid({user: "bob+smith@example.com"}, true);
- assertValid({user: "bob+smith@example.com"}, true);
- assertValid({user: "bob+smith@example.com"}, true);
- assertValid({user: "bob@test.example.com"}, true);
- assertValid({user: "bob@test-example.com"}, true);
+ it('accepts valid email addresses', function() {
+ assertValid({user: 'bob@example.com'}, true);
+ assertValid({user: 'bob+smith@example.com'}, true);
+ assertValid({user: 'bob+smith@example.com'}, true);
+ assertValid({user: 'bob+smith@example.com'}, true);
+ assertValid({user: 'bob@test.example.com'}, true);
+ assertValid({user: 'bob@test-example.com'}, true);
});
- it("displays username or email required error", function() {
- assertValid({user: ""}, false, EXPECTED_ERRORS.user_name_or_email_required);
+ it('displays username or email required error', function() {
+ assertValid({user: ''}, false, EXPECTED_ERRORS.user_name_or_email_required);
});
});
- describe("Certificate invalidation collection initialization and updates.",
+ describe('Certificate invalidation collection initialization and updates.',
function() {
var certificate_invalidations = null,
certificate_invalidation_url = 'test/url/';
var certificate_invalidations_json = [
{
id: 1,
- user: "test1",
+ user: 'test1',
invalidated_by: 2,
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate invalidation"
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate invalidation'
},
{
id: 2,
- user: "test2",
+ user: 'test2',
invalidated_by: 2,
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate invalidation"
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate invalidation'
}
];
@@ -78,11 +77,11 @@ define([
});
});
- it("has 2 models in the collection after initialization", function() {
+ it('has 2 models in the collection after initialization', function() {
expect(certificate_invalidations.models.length).toEqual(2);
});
- it("model is removed from collection on destroy", function() {
+ it('model is removed from collection on destroy', function() {
var model = certificate_invalidations.get({id: 2});
model.destroy();
expect(certificate_invalidations.models.length).toEqual(1);
@@ -91,61 +90,61 @@ define([
}
);
- describe("Certificate invalidation success/error messages on add/remove invalidations.", function() {
+ describe('Certificate invalidation success/error messages on add/remove invalidations.', function() {
var view = null,
certificate_invalidation_url = 'test/url/',
user_name_field = null,
notes_field = null,
- invalidate_button=null,
- duplicate_user='test2',
- new_user='test4@test.com',
- requests=null;
+ invalidate_button = null,
+ duplicate_user = 'test2',
+ new_user = 'test4@test.com',
+ requests = null;
- var messages = {
- error: {
- empty_user_name_email: 'Student username/email field is required and can not be empty. ' +
+ var messages = {
+ error: {
+ empty_user_name_email: 'Student username/email field is required and can not be empty. ' +
'Kindly fill in username/email and then press "Invalidate Certificate" button.',
- duplicate_user: "Certificate of " + (duplicate_user) + " has already been invalidated. " +
- "Please check your spelling and retry.",
- server_error: "Server Error, Please refresh the page and try again.",
- from_server: "Test Message from server"
- },
- success: {
- saved: "Certificate has been successfully invalidated for " + new_user + '.',
- re_validated: 'The certificate for this learner has been re-validated and ' +
+ duplicate_user: 'Certificate of ' + (duplicate_user) + ' has already been invalidated. ' +
+ 'Please check your spelling and retry.',
+ server_error: 'Server Error, Please refresh the page and try again.',
+ from_server: 'Test Message from server'
+ },
+ success: {
+ saved: 'Certificate has been successfully invalidated for ' + new_user + '.',
+ re_validated: 'The certificate for this learner has been re-validated and ' +
'the system is re-running the grade for this learner.'
- }
- };
+ }
+ };
var certificate_invalidations_json = [
{
id: 1,
- user: "test1",
+ user: 'test1',
invalidated_by: 2,
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate invalidation"
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate invalidation'
},
{
id: 2,
- user: "test2",
+ user: 'test2',
invalidated_by: 2,
- created: "Thursday, October 29, 2015",
- notes: "test notes for test certificate invalidation"
+ created: 'Thursday, October 29, 2015',
+ notes: 'test notes for test certificate invalidation'
}
];
beforeEach(function() {
setFixtures();
- var fixture =readFixtures(
- "templates/instructor/instructor_dashboard_2/certificate-invalidation.underscore"
+ var fixture = readFixtures(
+ 'templates/instructor/instructor_dashboard_2/certificate-invalidation.underscore'
);
setFixtures(
"" +
- "
Invalidate Certificates " +
+ '
Invalidate Certificates ' +
"
" +
- "
" +
- ""
+ ' ' +
+ "'
);
var certificate_invalidations = new CertificateInvalidationCollection(certificate_invalidations_json, {
@@ -159,19 +158,19 @@ define([
view = new CertificateInvalidationView({collection: certificate_invalidations});
view.render();
- user_name_field = $("#certificate-invalidation-user");
- notes_field = $("#certificate-invalidation-notes");
- invalidate_button = $("#invalidate-certificate");
+ user_name_field = $('#certificate-invalidation-user');
+ notes_field = $('#certificate-invalidation-notes');
+ invalidate_button = $('#invalidate-certificate');
requests = AjaxHelpers.requests(this);
});
- it("verifies view is initialized and rendered successfully", function() {
+ it('verifies view is initialized and rendered successfully', function() {
expect(view).not.toBe(undefined);
expect(view.$el.find('table tbody tr').length).toBe(2);
});
- it("verifies view is rendered on add/remove to collection", function() {
+ it('verifies view is rendered on add/remove to collection', function() {
var user = 'test3',
notes = 'test3 notes',
model = new CertificateInvalidationModel(
@@ -193,27 +192,25 @@ define([
// Verify view is updated
expect(view.$el.find('table tbody tr').length).toBe(2);
-
-
});
- it("verifies view error message on duplicate certificate validation.", function() {
+ it('verifies view error message on duplicate certificate validation.', function() {
$(user_name_field).val(duplicate_user);
$(invalidate_button).click();
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.duplicate_user);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.duplicate_user);
});
- it("verifies view error message on empty username/email field.", function() {
- $(user_name_field).val("");
+ it('verifies view error message on empty username/email field.', function() {
+ $(user_name_field).val('');
$(invalidate_button).click();
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.empty_user_name_email);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.empty_user_name_email);
});
- it("verifies view success message on certificate invalidation.", function() {
+ it('verifies view success message on certificate invalidation.', function() {
$(user_name_field).val(new_user);
- $(notes_field).val("test notes for user test4");
+ $(notes_field).val('test notes for user test4');
$(invalidate_button).click();
AjaxHelpers.respondWithJson(
@@ -222,36 +219,36 @@ define([
id: 4,
user: 'test4',
validated_by: 5,
- created: "Thursday, December 29, 2015",
- notes: "test notes for user test4"
+ created: 'Thursday, December 29, 2015',
+ notes: 'test notes for user test4'
}
);
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.success.saved);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.success.saved);
});
- it("verifies view server error if server returns unknown response.", function() {
+ it('verifies view server error if server returns unknown response.', function() {
$(user_name_field).val(new_user);
- $(notes_field).val("test notes for user test4");
+ $(notes_field).val('test notes for user test4');
$(invalidate_button).click();
// Response with empty body
- AjaxHelpers.respondWithTextError(requests, 400, "");
+ AjaxHelpers.respondWithTextError(requests, 400, '');
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.server_error);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.server_error);
});
- it("verifies certificate re-validation request and success message.", function() {
+ it('verifies certificate re-validation request and success message.', function() {
var user = 'test1',
- re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
+ re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
user + "') td .re-validate-certificate";
$(re_validate_certificate).click();
AjaxHelpers.respondWithJson(requests, {});
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.success.re_validated);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.success.re_validated);
});
- it("verifies error message from server is displayed.", function() {
+ it('verifies error message from server is displayed.', function() {
var user = 'test1',
re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
user + "') td .re-validate-certificate";
@@ -262,9 +259,8 @@ define([
message: messages.error.from_server
});
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.from_server);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.from_server);
});
-
});
}
);
diff --git a/lms/static/js/spec/instructor_dashboard/certificates_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_spec.js
index 4cf8b76867..2dd689f9da 100644
--- a/lms/static/js/spec/instructor_dashboard/certificates_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/certificates_spec.js
@@ -1,12 +1,12 @@
-/*global define, onCertificatesReady */
+/* global define, onCertificatesReady */
define([
- 'jquery',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/instructor_dashboard/certificates'
- ],
+ 'jquery',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/instructor_dashboard/certificates'
+],
function($, AjaxHelpers) {
'use strict';
- describe("edx.instructor_dashboard.certificates.regenerate_certificates", function() {
+ describe('edx.instructor_dashboard.certificates.regenerate_certificates', function() {
var $regenerate_certificates_button = null,
$certificate_regeneration_status = null,
requests = null;
@@ -14,18 +14,18 @@ define([
success_message: 'Certificate regeneration task has been started. ' +
'You can view the status of the generation task in the "Pending Tasks" section.',
error_message: 'Please select one or more certificate statuses that require certificate regeneration.',
- server_error_message: "Error while regenerating certificates. Please try again."
+ server_error_message: 'Error while regenerating certificates. Please try again.'
};
var expected = {
url: 'test/url/',
- postData : [],
+ postData: [],
selected_statuses: ['downloadable', 'error'],
body: 'certificate_statuses=downloadable&certificate_statuses=error'
};
- var select_options = function(option_values){
- $.each(option_values, function(index, element){
- $("#certificate-regenerating-form input[value=" + element + "]").click();
+ var select_options = function(option_values) {
+ $.each(option_values, function(index, element) {
+ $('#certificate-regenerating-form input[value=' + element + ']').click();
});
};
@@ -59,26 +59,26 @@ define([
setFixtures(fixture);
onCertificatesReady();
- $regenerate_certificates_button = $("#btn-start-regenerating-certificates");
- $certificate_regeneration_status = $(".certificate-regeneration-status");
+ $regenerate_certificates_button = $('#btn-start-regenerating-certificates');
+ $certificate_regeneration_status = $('.certificate-regeneration-status');
requests = AjaxHelpers.requests(this);
});
- it("does not regenerate certificates if user cancels operation in confirm popup", function() {
+ it('does not regenerate certificates if user cancels operation in confirm popup', function() {
spyOn(window, 'confirm').and.returnValue(false);
$regenerate_certificates_button.click();
expect(window.confirm).toHaveBeenCalled();
AjaxHelpers.expectNoRequests(requests);
});
- it("sends regenerate certificates request if user accepts operation in confirm popup", function() {
+ it('sends regenerate certificates request if user accepts operation in confirm popup', function() {
spyOn(window, 'confirm').and.returnValue(true);
$regenerate_certificates_button.click();
expect(window.confirm).toHaveBeenCalled();
AjaxHelpers.expectRequest(requests, 'POST', expected.url);
});
- it("sends regenerate certificates request with selected certificate statuses", function() {
+ it('sends regenerate certificates request with selected certificate statuses', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -87,7 +87,7 @@ define([
AjaxHelpers.expectRequest(requests, 'POST', expected.url, expected.body);
});
- it("displays error message in case of server side error", function() {
+ it('displays error message in case of server side error', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -96,7 +96,7 @@ define([
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.server_error_message);
});
- it("displays error message returned by the server in case of unsuccessful request", function() {
+ it('displays error message returned by the server in case of unsuccessful request', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -105,7 +105,7 @@ define([
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.error_message);
});
- it("displays success message returned by the server in case of successful request", function() {
+ it('displays success message returned by the server in case of successful request', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -113,7 +113,6 @@ define([
AjaxHelpers.respondWithJson(requests, {message: MESSAGES.success_message, success: true});
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.success_message);
});
-
});
}
);
diff --git a/lms/static/js/spec/instructor_dashboard/data_download_spec.js b/lms/static/js/spec/instructor_dashboard/data_download_spec.js
index d873c3b337..80ad0bdd01 100644
--- a/lms/static/js/spec/instructor_dashboard/data_download_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/data_download_spec.js
@@ -1,11 +1,11 @@
-/*global define */
+/* global define */
define(['jquery',
'coffee/src/instructor_dashboard/data_download',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'slick.grid'],
- function ($, DataDownload, AjaxHelpers) {
+ function($, DataDownload, AjaxHelpers) {
'use strict';
- describe("edx.instructor_dashboard.data_download.DataDownload_Certificate", function() {
+ describe('edx.instructor_dashboard.data_download.DataDownload_Certificate', function() {
var url, data_download_certificate;
beforeEach(function() {
@@ -19,9 +19,9 @@ define(['jquery',
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
var data = {
- 'certificates': [{'course_id':'xyz_test', 'mode':'honor'}],
+ 'certificates': [{'course_id': 'xyz_test', 'mode': 'honor'}],
'queried_features': ['course_id', 'mode'],
- 'feature_names': { 'course_id': 'Course ID', 'mode': ' Mode'}
+ 'feature_names': {'course_id': 'Course ID', 'mode': ' Mode'}
};
data_download_certificate.$list_issued_certificate_table_btn.click();
diff --git a/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js b/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
index 56a95485ac..4918623a5c 100644
--- a/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
@@ -1,18 +1,18 @@
define(['backbone', 'jquery', 'js/instructor_dashboard/ecommerce'],
- function (Backbone, $, ExpiryCouponView) {
+ function(Backbone, $, ExpiryCouponView) {
'use strict';
var expiryCouponView;
- describe("edx.instructor_dashboard.ecommerce.ExpiryCouponView", function() {
+ describe('edx.instructor_dashboard.ecommerce.ExpiryCouponView', function() {
beforeEach(function() {
setFixtures('
');
expiryCouponView = new ExpiryCouponView();
});
- it("is defined", function () {
+ it('is defined', function() {
expect(expiryCouponView).toBeDefined();
});
- it("triggers the callback when the checkbox is clicked", function () {
+ it('triggers the callback when the checkbox is clicked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
spyOn(expiryCouponView, 'clicked');
expiryCouponView.delegateEvents();
@@ -20,15 +20,15 @@ define(['backbone', 'jquery', 'js/instructor_dashboard/ecommerce'],
expect(expiryCouponView.clicked).toHaveBeenCalled();
});
- it("shows the input field when the checkbox is checked", function () {
+ it('shows the input field when the checkbox is checked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
target.click();
expect(expiryCouponView.$el.find('#coupon_expiration_date').is(':visible')).toBe(true);
});
- it("hides the input field when the checkbox is unchecked", function () {
+ it('hides the input field when the checkbox is unchecked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
- expect(expiryCouponView.$el.find('#coupon_expiration_date')).toHaveAttr('style','display: none;');
+ expect(expiryCouponView.$el.find('#coupon_expiration_date')).toHaveAttr('style', 'display: none;');
});
});
});
diff --git a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
index 11223a3422..1edf90b69e 100644
--- a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
@@ -1,8 +1,8 @@
define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'],
- function ($, StudentAdmin, AjaxHelpers) {
- //'coffee/src/instructor_dashboard/student_admin'
+ function($, StudentAdmin, AjaxHelpers) {
+ // 'coffee/src/instructor_dashboard/student_admin'
'use strict';
- describe("edx.instructor_dashboard.student_admin.StudentAdmin", function() {
+ describe('edx.instructor_dashboard.student_admin.StudentAdmin', function() {
var studentadmin, dashboard_api_url, unique_student_identifier, alert_msg;
beforeEach(function() {
@@ -15,22 +15,21 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
};
studentadmin = new window.StudentAdmin($('#student_admin'));
dashboard_api_url = '/courses/PU/FSc/2014_T4/instructor/api';
- unique_student_identifier = "test@example.com";
+ unique_student_identifier = 'test@example.com';
alert_msg = '';
spyOn(window, 'alert').and.callFake(function(message) {
alert_msg = message;
});
-
});
it('initiates resetting of entrance exam when button is clicked', function() {
studentadmin.$btn_reset_entrance_exam_attempts.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Entrance exam attempts is being reset for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
@@ -56,7 +55,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when resetting of entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_reset_entrance_exam_attempts.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -67,11 +66,11 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error resetting entrance exam attempts for student '{student_id}'. Make sure student identifier is correct.");
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -79,18 +78,18 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('initiates rescoring of the entrance exam when the button is clicked', function() {
studentadmin.$btn_rescore_entrance_exam.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Started entrance exam rescore task for student '{student_id}'." +
" Click the 'Show Background Task History for Student' button to see the status of the task.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_rescore_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -109,7 +108,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when entrance exam rescoring fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_rescore_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -119,12 +118,12 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error starting a task to rescore entrance exam for student '{student_id}'." +
- " Make sure that entrance exam has problems in it and student identifier is correct.");
+ ' Make sure that entrance exam has problems in it and student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -136,13 +135,13 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
var success_message = "This student ('{student_id}') will skip the entrance exam.";
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_skip_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var url = dashboard_api_url + '/mark_student_can_skip_entrance_exam';
@@ -160,7 +159,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when skip entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_skip_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var url = dashboard_api_url + '/mark_student_can_skip_entrance_exam';
@@ -169,7 +168,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
}));
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = "An error occurred. Make sure that the student's username or email address is correct and try again.";
expect(studentadmin.$request_response_error_ee.text()).toEqual(error_message);
@@ -178,17 +177,17 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('initiates delete student state for entrance exam when button is clicked', function() {
studentadmin.$btn_delete_entrance_exam_state.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Entrance exam state is being deleted for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_delete_entrance_exam_state.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -208,7 +207,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when delete student state for entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_delete_entrance_exam_state.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -219,12 +218,12 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error deleting entrance exam state for student '{student_id}'. " +
- "Make sure student identifier is correct.");
+ 'Make sure student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -236,13 +235,13 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
var success_message = gettext("Entrance exam state is being deleted for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_entrance_exam_task_history.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -253,17 +252,17 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
// Simulate a success response from the server
AjaxHelpers.respondWithJson(requests, {
- "tasks": [
+ 'tasks': [
{
- "status": "Incomplete",
- "task_type": "rescore_problem",
- "task_id": "9955d413-eac1-441f-978d-27c60dd1c946",
- "created": "2015-02-19T10:59:01+00:00",
- "task_input": "{\"entrance_exam_url\": \"i4x://PU/FSc/chapter/d2204197cce443c4a0d5c852d4e7f638\", \"student\": \"audit\"}",
- "duration_sec": "unknown",
- "task_message": "No status information available",
- "requester": "staff",
- "task_state": "QUEUING"
+ 'status': 'Incomplete',
+ 'task_type': 'rescore_problem',
+ 'task_id': '9955d413-eac1-441f-978d-27c60dd1c946',
+ 'created': '2015-02-19T10:59:01+00:00',
+ 'task_input': '{"entrance_exam_url": "i4x://PU/FSc/chapter/d2204197cce443c4a0d5c852d4e7f638", "student": "audit"}',
+ 'duration_sec': 'unknown',
+ 'task_message': 'No status information available',
+ 'requester': 'staff',
+ 'task_state': 'QUEUING'
}
]
});
@@ -273,7 +272,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when listing entrance exam task history fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_entrance_exam_task_history.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -283,15 +282,14 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error getting entrance exam task history for student '{student_id}'. " +
- "Make sure student identifier is correct.");
+ 'Make sure student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
-
});
});
diff --git a/lms/static/js/spec/learner_dashboard/certificate_view_spec.js b/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
index 868ddde4c9..2f2ed20fc9 100644
--- a/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
@@ -1,63 +1,62 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/certificate_view'
- ], function (Backbone, $, CertificateView) {
-
- 'use strict';
- describe('Certificate View', function () {
- var view = null,
- data = {
- context: {
- certificatesData: [
- {
- "display_name": "Testing",
- "credential_url": "https://credentials.stage.edx.org/credentials/dummy-uuid-1/"
- },
- {
- "display_name": "Testing2",
- "credential_url": "https://credentials.stage.edx.org/credentials/dummy-uuid-2/"
- }
- ],
- sampleCertImageSrc: "/images/programs/sample-cert.png"
- }
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/certificate_view'
+], function(Backbone, $, CertificateView) {
+ 'use strict';
+ describe('Certificate View', function() {
+ var view = null,
+ data = {
+ context: {
+ certificatesData: [
+ {
+ 'display_name': 'Testing',
+ 'credential_url': 'https://credentials.stage.edx.org/credentials/dummy-uuid-1/'
+ },
+ {
+ 'display_name': 'Testing2',
+ 'credential_url': 'https://credentials.stage.edx.org/credentials/dummy-uuid-2/'
+ }
+ ],
+ sampleCertImageSrc: '/images/programs/sample-cert.png'
+ }
+ };
- beforeEach(function() {
- setFixtures('
');
- view = new CertificateView(data);
- view.render();
- });
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the certificates based on passed in certificates list', function() {
- var $certificates = view.$el.find('.certificate-link');
- expect($certificates.length).toBe(2);
-
- $certificates.each(function(index, el){
- expect($(el).html().trim()).toEqual(data.context.certificatesData[index].display_name);
- expect($(el).attr('href')).toEqual(data.context.certificatesData[index].credential_url);
- });
- expect(view.$el.find('.hd-6').html().trim()).toEqual('Program Certificates');
- expect(view.$el.find('img').attr('src')).toEqual(data.context.sampleCertImageSrc);
- });
-
- it('should display no certificate box if certificates list is empty', function() {
- view.remove();
- setFixtures('
');
- view = new CertificateView({
- context: {certificatesData: []}
- });
- view.render();
- expect(view.$('.certificates-list').length).toBe(0);
- });
+ beforeEach(function() {
+ setFixtures('
');
+ view = new CertificateView(data);
+ view.render();
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the certificates based on passed in certificates list', function() {
+ var $certificates = view.$el.find('.certificate-link');
+ expect($certificates.length).toBe(2);
+
+ $certificates.each(function(index, el) {
+ expect($(el).html().trim()).toEqual(data.context.certificatesData[index].display_name);
+ expect($(el).attr('href')).toEqual(data.context.certificatesData[index].credential_url);
+ });
+ expect(view.$el.find('.hd-6').html().trim()).toEqual('Program Certificates');
+ expect(view.$el.find('img').attr('src')).toEqual(data.context.sampleCertImageSrc);
+ });
+
+ it('should display no certificate box if certificates list is empty', function() {
+ view.remove();
+ setFixtures('
');
+ view = new CertificateView({
+ context: {certificatesData: []}
+ });
+ view.render();
+ expect(view.$('.certificates-list').length).toBe(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js b/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
index 277b752509..ee3e0c0cc3 100644
--- a/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
@@ -1,154 +1,153 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/program_card_view',
- 'js/learner_dashboard/collections/program_collection',
- 'js/learner_dashboard/views/collection_list_view',
- 'js/learner_dashboard/collections/program_progress_collection'
- ], function (Backbone, $, ProgramCardView, ProgramCollection, CollectionListView,
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/program_card_view',
+ 'js/learner_dashboard/collections/program_collection',
+ 'js/learner_dashboard/views/collection_list_view',
+ 'js/learner_dashboard/collections/program_progress_collection'
+], function(Backbone, $, ProgramCardView, ProgramCollection, CollectionListView,
ProgressCollection) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Collection List View', function () {
- var view = null,
- programCollection,
- progressCollection,
- context = {
- programsData:[
- {
- category: 'xseries',
- status: 'active',
- subtitle: 'program 1',
- name: 'test program 1',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-03T19:18:50.061136Z',
- modified: '2016-03-25T13:45:21.220732Z',
- marketing_slug: 'p_2?param=haha&test=b',
- id: 146,
- marketing_url: 'http://www.edx.org/xseries/p_2?param=haha&test=b',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/org1/test1',
- w435h145: 'http://www.edx.org/images/org1/test2',
- w726h242: 'http://www.edx.org/images/org1/test3'
+ 'use strict';
+ /* jslint maxlen: 500 */
+
+ describe('Collection List View', function() {
+ var view = null,
+ programCollection,
+ progressCollection,
+ context = {
+ programsData: [
+ {
+ category: 'xseries',
+ status: 'active',
+ subtitle: 'program 1',
+ name: 'test program 1',
+ organizations: [
+ {
+ display_name: 'edX',
+ key: 'edx'
}
- },
- {
- category: 'xseries',
- status: 'active',
- subtitle: 'fda',
- name: 'fda',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-09T14:30:41.484848Z',
- modified: '2016-03-09T14:30:52.840898Z',
- marketing_slug: 'gdaf',
- id: 147,
- marketing_url: 'http://www.edx.org/xseries/gdaf',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/org2/test1',
- w435h145: 'http://www.edx.org/images/org2/test2',
- w726h242: 'http://www.edx.org/images/org2/test3'
+ ],
+ created: '2016-03-03T19:18:50.061136Z',
+ modified: '2016-03-25T13:45:21.220732Z',
+ marketing_slug: 'p_2?param=haha&test=b',
+ id: 146,
+ marketing_url: 'http://www.edx.org/xseries/p_2?param=haha&test=b',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/org1/test1',
+ w435h145: 'http://www.edx.org/images/org1/test2',
+ w726h242: 'http://www.edx.org/images/org1/test3'
+ }
+ },
+ {
+ category: 'xseries',
+ status: 'active',
+ subtitle: 'fda',
+ name: 'fda',
+ organizations: [
+ {
+ display_name: 'edX',
+ key: 'edx'
}
+ ],
+ created: '2016-03-09T14:30:41.484848Z',
+ modified: '2016-03-09T14:30:52.840898Z',
+ marketing_slug: 'gdaf',
+ id: 147,
+ marketing_url: 'http://www.edx.org/xseries/gdaf',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/org2/test1',
+ w435h145: 'http://www.edx.org/images/org2/test2',
+ w726h242: 'http://www.edx.org/images/org2/test3'
}
- ],
- userProgress: [
- {
- id: 146,
- completed: ['courses', 'the', 'user', 'completed'],
- in_progress: ['in', 'progress'],
- not_started : ['courses', 'not', 'yet', 'started']
- },
- {
- id: 147,
- completed: ['Course 1'],
- in_progress: [],
- not_started: ['Course 2', 'Course 3', 'Course 4']
- }
- ]
- };
+ }
+ ],
+ userProgress: [
+ {
+ id: 146,
+ completed: ['courses', 'the', 'user', 'completed'],
+ in_progress: ['in', 'progress'],
+ not_started: ['courses', 'not', 'yet', 'started']
+ },
+ {
+ id: 147,
+ completed: ['Course 1'],
+ in_progress: [],
+ not_started: ['Course 2', 'Course 3', 'Course 4']
+ }
+ ]
+ };
- beforeEach(function() {
- setFixtures('
');
- programCollection = new ProgramCollection(context.programsData);
- progressCollection = new ProgressCollection();
- progressCollection.set(context.userProgress);
- context.progressCollection = progressCollection;
-
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- collection: programCollection,
- context: context
- });
- view.render();
- });
+ beforeEach(function() {
+ setFixtures('
');
+ programCollection = new ProgramCollection(context.programsData);
+ progressCollection = new ProgressCollection();
+ progressCollection.set(context.userProgress);
+ context.progressCollection = progressCollection;
- afterEach(function() {
- view.remove();
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ collection: programCollection,
+ context: context
});
+ view.render();
+ });
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ afterEach(function() {
+ view.remove();
+ });
- it('should load the collection items based on passed in collection', function() {
- var $cards = view.$el.find('.program-card');
- expect($cards.length).toBe(2);
- $cards.each(function(index, el){
- expect($(el).find('.title').html().trim()).toEqual(context.programsData[index].name);
- });
- });
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
- it('should display no item if collection is empty', function(){
- var $cards;
- view.remove();
- programCollection = new ProgramCollection([]);
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- context: {'xseriesUrl': '/programs'},
- collection: programCollection
- });
- view.render();
- $cards = view.$el.find('.program-card');
- expect($cards.length).toBe(0);
- });
- it('should have no title when title not provided', function(){
- var $title;
- setFixtures('
');
- view.remove();
- view.render();
- expect(view).toBeDefined();
- $title = view.$el.parent().find('.collection-title');
- expect($title.html()).not.toBeDefined();
- });
- it('should display screen reader header when provided', function(){
- var $title, titleContext = {el:'h2', title:'list start'};
- view.remove();
- setFixtures('
');
- programCollection = new ProgramCollection(context.programsData);
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- context: {'xseriesUrl': '/programs'},
- collection: programCollection,
- titleContext: titleContext
- });
- view.render();
- $title = view.$el.parent().find('.collection-title');
- expect($title.html()).toBe(titleContext.title);
+ it('should load the collection items based on passed in collection', function() {
+ var $cards = view.$el.find('.program-card');
+ expect($cards.length).toBe(2);
+ $cards.each(function(index, el) {
+ expect($(el).find('.title').html().trim()).toEqual(context.programsData[index].name);
});
});
- }
+
+ it('should display no item if collection is empty', function() {
+ var $cards;
+ view.remove();
+ programCollection = new ProgramCollection([]);
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ context: {'xseriesUrl': '/programs'},
+ collection: programCollection
+ });
+ view.render();
+ $cards = view.$el.find('.program-card');
+ expect($cards.length).toBe(0);
+ });
+ it('should have no title when title not provided', function() {
+ var $title;
+ setFixtures('
');
+ view.remove();
+ view.render();
+ expect(view).toBeDefined();
+ $title = view.$el.parent().find('.collection-title');
+ expect($title.html()).not.toBeDefined();
+ });
+ it('should display screen reader header when provided', function() {
+ var $title, titleContext = {el: 'h2', title: 'list start'};
+ view.remove();
+ setFixtures('
');
+ programCollection = new ProgramCollection(context.programsData);
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ context: {'xseriesUrl': '/programs'},
+ collection: programCollection,
+ titleContext: titleContext
+ });
+ view.render();
+ $title = view.$el.parent().find('.collection-title');
+ expect($title.html()).toBe(titleContext.title);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/course_card_view_spec.js b/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
index 0917211687..5f89de6298 100644
--- a/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
@@ -1,18 +1,17 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/models/course_card_model',
- 'js/learner_dashboard/views/course_card_view'
- ], function (Backbone, $, CourseCardModel, CourseCardView) {
-
- 'use strict';
-
- describe('Course Card View', function () {
- var view = null,
- courseCardModel,
- context,
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/models/course_card_model',
+ 'js/learner_dashboard/views/course_card_view'
+], function(Backbone, $, CourseCardModel, CourseCardView) {
+ 'use strict';
- setupView = function(data, isEnrolled){
+ describe('Course Card View', function() {
+ var view = null,
+ courseCardModel,
+ context,
+
+ setupView = function(data, isEnrolled) {
var programData = $.extend({}, data);
programData.run_modes[0].is_enrolled = isEnrolled;
@@ -23,8 +22,8 @@ define([
});
},
- validateCourseInfoDisplay = function(){
- //DRY validation for course card in enrolled state
+ validateCourseInfoDisplay = function() {
+ // DRY validation for course card in enrolled state
expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
expect(view.$('.course-details .course-title-link').text().trim()).toEqual(context.display_name);
expect(view.$('.course-details .course-title-link').attr('href')).toEqual(
@@ -35,158 +34,158 @@ define([
.toEqual(context.run_modes[0].start_date + ' - ' + context.run_modes[0].end_date);
};
- beforeEach(function() {
+ beforeEach(function() {
// Redefine this data prior to each test case so that tests can't
// break each other by modifying data copied by reference.
- context = {
- course_modes: [],
- display_name: 'Astrophysics: Exploring Exoplanets',
- key: 'ANU-ASTRO1x',
- organization: {
- display_name: 'Australian National University',
- key: 'ANUx'
- },
- run_modes: [{
- certificate_url: '',
- course_image_url: 'http://test.com/image1',
- course_key: 'course-v1:ANUx+ANU-ASTRO1x+3T2015',
- course_started: true,
- course_url: 'https://courses.example.com/courses/course-v1:edX+DemoX+Demo_Course',
- end_date: 'Jun 13, 2019',
- enrollment_open_date: 'Apr 1, 2016',
- is_course_ended: false,
- is_enrolled: true,
- is_enrollment_open: true,
- marketing_url: 'https://www.example.com/marketing/site',
- mode_slug: 'verified',
- run_key: '2T2016',
- start_date: 'Apr 25, 2016',
- upgrade_url: ''
- }]
- };
+ context = {
+ course_modes: [],
+ display_name: 'Astrophysics: Exploring Exoplanets',
+ key: 'ANU-ASTRO1x',
+ organization: {
+ display_name: 'Australian National University',
+ key: 'ANUx'
+ },
+ run_modes: [{
+ certificate_url: '',
+ course_image_url: 'http://test.com/image1',
+ course_key: 'course-v1:ANUx+ANU-ASTRO1x+3T2015',
+ course_started: true,
+ course_url: 'https://courses.example.com/courses/course-v1:edX+DemoX+Demo_Course',
+ end_date: 'Jun 13, 2019',
+ enrollment_open_date: 'Apr 1, 2016',
+ is_course_ended: false,
+ is_enrolled: true,
+ is_enrollment_open: true,
+ marketing_url: 'https://www.example.com/marketing/site',
+ mode_slug: 'verified',
+ run_key: '2T2016',
+ start_date: 'Apr 25, 2016',
+ upgrade_url: ''
+ }]
+ };
- setupView(context, false);
+ setupView(context, false);
+ });
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should render the course card based on the data enrolled', function() {
+ view.remove();
+ setupView(context, true);
+ validateCourseInfoDisplay();
+ });
+
+ it('should render the course card based on the data not enrolled', function() {
+ validateCourseInfoDisplay();
+ });
+
+ it('should update render if the course card is_enrolled updated', function() {
+ courseCardModel.set({
+ is_enrolled: true
});
+ validateCourseInfoDisplay();
+ });
- afterEach(function() {
- view.remove();
- });
+ it('should only show certificate status section if a certificate has been earned', function() {
+ var certUrl = 'sample-certificate';
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ expect(view.$('.certificate-status').length).toEqual(0);
+ view.remove();
- it('should render the course card based on the data enrolled', function() {
- view.remove();
- setupView(context, true);
- validateCourseInfoDisplay();
- });
+ context.run_modes[0].certificate_url = certUrl;
+ setupView(context, false);
+ expect(view.$('.certificate-status').length).toEqual(1);
+ expect(view.$('.certificate-status .cta-secondary').attr('href')).toEqual(certUrl);
+ });
- it('should render the course card based on the data not enrolled', function() {
- validateCourseInfoDisplay();
- });
+ it('should only show upgrade message section if an upgrade is required', function() {
+ var upgradeUrl = '/path/to/upgrade';
- it('should update render if the course card is_enrolled updated', function() {
- courseCardModel.set({
- is_enrolled: true
- });
- validateCourseInfoDisplay();
- });
+ expect(view.$('.upgrade-message').length).toEqual(0);
+ view.remove();
- it('should only show certificate status section if a certificate has been earned', function() {
- var certUrl = 'sample-certificate';
+ context.run_modes[0].upgrade_url = upgradeUrl;
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(1);
+ expect(view.$('.upgrade-message .cta-primary').attr('href')).toEqual(upgradeUrl);
+ });
- expect(view.$('.certificate-status').length).toEqual(0);
- view.remove();
-
- context.run_modes[0].certificate_url = certUrl;
- setupView(context, false);
- expect(view.$('.certificate-status').length).toEqual(1);
- expect(view.$('.certificate-status .cta-secondary').attr('href')).toEqual(certUrl);
- });
-
- it('should only show upgrade message section if an upgrade is required', function() {
- var upgradeUrl = '/path/to/upgrade';
-
- expect(view.$('.upgrade-message').length).toEqual(0);
- view.remove();
-
- context.run_modes[0].upgrade_url = upgradeUrl;
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(1);
- expect(view.$('.upgrade-message .cta-primary').attr('href')).toEqual(upgradeUrl);
- });
-
- it('should not show both the upgrade message and certificate status sections', function() {
+ it('should not show both the upgrade message and certificate status sections', function() {
// Verify that no empty elements are left in the DOM.
- context.run_modes[0].upgrade_url = '';
- context.run_modes[0].certificate_url = '';
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(0);
- expect(view.$('.certificate-status').length).toEqual(0);
- view.remove();
+ context.run_modes[0].upgrade_url = '';
+ context.run_modes[0].certificate_url = '';
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(0);
+ expect(view.$('.certificate-status').length).toEqual(0);
+ view.remove();
// Verify that the upgrade message takes priority.
- context.run_modes[0].upgrade_url = '/path/to/upgrade';
- context.run_modes[0].certificate_url = '/path/to/certificate';
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(1);
- expect(view.$('.certificate-status').length).toEqual(0);
- });
+ context.run_modes[0].upgrade_url = '/path/to/upgrade';
+ context.run_modes[0].certificate_url = '/path/to/certificate';
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(1);
+ expect(view.$('.certificate-status').length).toEqual(0);
+ });
- it('should show a message if an there is an upcoming course run', function(){
- context.run_modes[0].is_enrollment_open = false;
+ it('should show a message if an there is an upcoming course run', function() {
+ context.run_modes[0].is_enrollment_open = false;
- setupView(context, false);
+ setupView(context, false);
- expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
- expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
- expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
- expect(view.$('.course-details .course-text .run-period').length).toBe(0);
- expect(view.$('.no-action-message').text().trim()).toBe('Coming Soon');
- expect(view.$('.enrollment-open-date').text().trim()).toEqual(
+ expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
+ expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
+ expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
+ expect(view.$('.course-details .course-text .run-period').length).toBe(0);
+ expect(view.$('.no-action-message').text().trim()).toBe('Coming Soon');
+ expect(view.$('.enrollment-open-date').text().trim()).toEqual(
context.run_modes[0].enrollment_open_date
);
- });
+ });
- it('should show a message if there are no known upcoming course runs', function(){
- context.run_modes[0].is_enrollment_open = false;
- context.run_modes[0].is_course_ended = true;
+ it('should show a message if there are no known upcoming course runs', function() {
+ context.run_modes[0].is_enrollment_open = false;
+ context.run_modes[0].is_course_ended = true;
- setupView(context, false);
+ setupView(context, false);
- expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
- expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
- expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
- expect(view.$('.course-details .course-text .run-period').length).toBe(0);
- expect(view.$('.no-action-message').text().trim()).toBe('Not Currently Available');
- expect(view.$('.enrollment-opens').length).toEqual(0);
- });
+ expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
+ expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
+ expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
+ expect(view.$('.course-details .course-text .run-period').length).toBe(0);
+ expect(view.$('.no-action-message').text().trim()).toBe('Not Currently Available');
+ expect(view.$('.enrollment-opens').length).toEqual(0);
+ });
- it('should link to the marketing site when a URL is available', function(){
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].marketing_url);
- });
- });
-
- it('should link to the course home when no marketing URL is available', function(){
- context.run_modes[0].marketing_url = null;
- setupView(context, false);
-
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].course_url);
- });
- });
-
- it('should not link to the marketing site or the course home if neither URL is available', function(){
- context.run_modes[0].marketing_url = null;
- context.run_modes[0].course_url = null;
- setupView(context, false);
-
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).length).toEqual(0);
- });
+ it('should link to the marketing site when a URL is available', function() {
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].marketing_url);
});
});
- }
+
+ it('should link to the course home when no marketing URL is available', function() {
+ context.run_modes[0].marketing_url = null;
+ setupView(context, false);
+
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].course_url);
+ });
+ });
+
+ it('should not link to the marketing site or the course home if neither URL is available', function() {
+ context.run_modes[0].marketing_url = null;
+ context.run_modes[0].course_url = null;
+ setupView(context, false);
+
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).length).toEqual(0);
+ });
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js b/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
index 6d61720776..95423f2fdb 100644
--- a/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
@@ -1,243 +1,242 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/models/course_card_model',
- 'js/learner_dashboard/models/course_enroll_model',
- 'js/learner_dashboard/views/course_enroll_view'
- ], function (Backbone, $, CourseCardModel, CourseEnrollModel, CourseEnrollView) {
-
- 'use strict';
-
- describe('Course Enroll View', function () {
- var view = null,
- courseCardModel,
- courseEnrollModel,
- urlModel,
- setupView,
- singleRunModeList,
- multiRunModeList,
- context = {
- display_name: 'Edx Demo course',
- key: 'edX+DemoX+Demo_Course',
- organization: {
- display_name: 'edx.org',
- key: 'edX'
- }
- },
- urls = {
- dashboard_url: '/dashboard',
- id_verification_url: '/verify_student/start_flow/',
- track_selection_url: '/select_track/course/'
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/models/course_card_model',
+ 'js/learner_dashboard/models/course_enroll_model',
+ 'js/learner_dashboard/views/course_enroll_view'
+], function(Backbone, $, CourseCardModel, CourseEnrollModel, CourseEnrollView) {
+ 'use strict';
- beforeEach(function() {
- // Redefine this data prior to each test case so that tests can't
- // break each other by modifying data copied by reference.
- singleRunModeList = [{
- start_date: 'Apr 25, 2016',
- end_date: 'Jun 13, 2016',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/image1',
- marketing_url: 'http://test.com/image2',
- is_course_ended: false,
- mode_slug: 'audit',
- run_key: '2T2016',
- is_enrolled: false,
- is_enrollment_open: true
- }];
-
- multiRunModeList = [{
- start_date: 'May 21, 2015',
- end_date: 'Sep 21, 2015',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/run_2_image_1',
- marketing_url: 'http://test.com/run_2_image_2',
- mode_slug: 'verified',
- is_course_ended: false,
- run_key: '1T2015',
- is_enrolled: false,
- is_enrollment_open: true,
- },{
- start_date: 'Sep 22, 2015',
- end_date: 'Dec 28, 2015',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/run_3_image_1',
- marketing_url: 'http://test.com/run_3_image_2',
- is_course_ended: false,
- mode_slug: 'verified',
- run_key: '2T2015',
- is_enrolled: false,
- is_enrollment_open: true
- }];
- });
-
- setupView = function(runModes, urls){
- context.run_modes = runModes;
- setFixtures('
');
- courseCardModel = new CourseCardModel(context);
- courseEnrollModel = new CourseEnrollModel({}, {
- courseId: courseCardModel.get('course_key')
- });
- if(urls){
- urlModel = new Backbone.Model(urls);
+ describe('Course Enroll View', function() {
+ var view = null,
+ courseCardModel,
+ courseEnrollModel,
+ urlModel,
+ setupView,
+ singleRunModeList,
+ multiRunModeList,
+ context = {
+ display_name: 'Edx Demo course',
+ key: 'edX+DemoX+Demo_Course',
+ organization: {
+ display_name: 'edx.org',
+ key: 'edX'
}
- view = new CourseEnrollView({
- $parentEl: $('.course-actions'),
- model: courseCardModel,
- enrollModel: courseEnrollModel,
- urlModel: urlModel
- });
+ },
+ urls = {
+ dashboard_url: '/dashboard',
+ id_verification_url: '/verify_student/start_flow/',
+ track_selection_url: '/select_track/course/'
};
- afterEach(function() {
- view.remove();
- urlModel = null;
- courseCardModel = null;
- courseEnrollModel = null;
- });
+ beforeEach(function() {
+ // Redefine this data prior to each test case so that tests can't
+ // break each other by modifying data copied by reference.
+ singleRunModeList = [{
+ start_date: 'Apr 25, 2016',
+ end_date: 'Jun 13, 2016',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/image1',
+ marketing_url: 'http://test.com/image2',
+ is_course_ended: false,
+ mode_slug: 'audit',
+ run_key: '2T2016',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }];
- it('should exist', function() {
- setupView(singleRunModeList);
- expect(view).toBeDefined();
- });
-
- it('should render the course enroll view based on not enrolled data', function() {
- setupView(singleRunModeList);
- expect(view.$('.enrollment-info').html().trim()).toEqual('not enrolled');
- expect(view.$('.enroll-button').text().trim()).toEqual('Enroll Now');
- expect(view.$('.run-select').length).toBe(0);
- });
-
- it('should render the course enroll view based on enrolled data', function(){
- singleRunModeList[0].is_enrolled = true;
-
- setupView(singleRunModeList);
-
- expect(view.$('.enrollment-info').html().trim()).toEqual('enrolled');
- expect(view.$('.view-course-link').attr('href')).toEqual(context.run_modes[0].course_url);
- expect(view.$('.view-course-link').text().trim()).toEqual('View Course');
- expect(view.$('.run-select').length).toBe(0);
- });
-
- it('should allow the learner to view an archived course', function(){
- // Regression test for ECOM-4974.
- singleRunModeList[0].is_enrolled = true;
- singleRunModeList[0].is_enrollment_open = false;
- singleRunModeList[0].is_course_ended = true;
-
- setupView(singleRunModeList);
-
- expect(view.$('.view-course-link').text().trim()).toEqual('View Archived Course');
- });
-
- it('should not render anything if run modes is empty', function(){
- setupView([]);
- expect(view.$('.enrollment-info').length).toBe(0);
- expect(view.$('.run-select').length).toBe(0);
- expect(view.$('.enroll-button').length).toBe(0);
- });
-
- it('should render run selection drop down if mulitple run available', function(){
- setupView(multiRunModeList);
- expect(view.$('.run-select').length).toBe(1);
- expect(view.$('.run-select').val()).toEqual('');
- expect(view.$('.run-select option').length).toBe(3);
- });
-
- it('should switch run context if dropdown selection changed', function(){
- setupView(multiRunModeList);
- spyOn(courseCardModel, 'updateRun').and.callThrough();
- expect(view.$('.run-select').val()).toEqual('');
- view.$('.run-select').val(multiRunModeList[1].run_key);
- view.$('.run-select').trigger("change");
- expect(view.$('.run-select').val()).toEqual(multiRunModeList[1].run_key);
- expect(courseCardModel.updateRun)
- .toHaveBeenCalledWith(multiRunModeList[1].run_key);
- expect(courseCardModel.get('run_key')).toEqual(multiRunModeList[1].run_key);
- });
-
- it('should enroll learner when enroll button clicked', function(){
- setupView(singleRunModeList);
- expect(view.$('.enroll-button').length).toBe(1);
- spyOn(courseEnrollModel, 'save');
- view.$('.enroll-button').click();
- expect(courseEnrollModel.save).toHaveBeenCalled();
- });
-
- it('should enroll learner into the updated run with button click', function(){
- setupView(multiRunModeList);
- spyOn(courseEnrollModel, 'save');
- view.$('.run-select').val(multiRunModeList[1].run_key);
- view.$('.run-select').trigger("change");
- view.$('.enroll-button').click();
- expect(courseEnrollModel.save).toHaveBeenCalled();
- });
-
- it('should redirect to trackSelectionUrl when enrollment success for audit track', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = 'audit';
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
-
- it('should redirect when enrollment success for no track', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = null;
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
- it('should not redirect when urls not provided', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = 'verified';
- setupView(singleRunModeList);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.verificationUrl).not.toBeDefined();
- expect(view.dashboardUrl).not.toBeDefined();
- expect(view.trackSelectionUrl).not.toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).not.toHaveBeenCalled();
- });
-
- it('should redirect to track selection on error', function(){
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollError(courseEnrollModel, {status: 500});
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
- it('should redirect to login on 403 error', function(){
- var response = {
- status: 403,
- responseJSON:{
- user_message_url: 'test_url/haha'
- }};
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollError(courseEnrollModel, response);
- expect(view.redirect).toHaveBeenCalledWith(
- response.responseJSON.user_message_url);
- });
+ multiRunModeList = [{
+ start_date: 'May 21, 2015',
+ end_date: 'Sep 21, 2015',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/run_2_image_1',
+ marketing_url: 'http://test.com/run_2_image_2',
+ mode_slug: 'verified',
+ is_course_ended: false,
+ run_key: '1T2015',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }, {
+ start_date: 'Sep 22, 2015',
+ end_date: 'Dec 28, 2015',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/run_3_image_1',
+ marketing_url: 'http://test.com/run_3_image_2',
+ is_course_ended: false,
+ mode_slug: 'verified',
+ run_key: '2T2015',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }];
});
- }
+
+ setupView = function(runModes, urls) {
+ context.run_modes = runModes;
+ setFixtures('
');
+ courseCardModel = new CourseCardModel(context);
+ courseEnrollModel = new CourseEnrollModel({}, {
+ courseId: courseCardModel.get('course_key')
+ });
+ if (urls) {
+ urlModel = new Backbone.Model(urls);
+ }
+ view = new CourseEnrollView({
+ $parentEl: $('.course-actions'),
+ model: courseCardModel,
+ enrollModel: courseEnrollModel,
+ urlModel: urlModel
+ });
+ };
+
+ afterEach(function() {
+ view.remove();
+ urlModel = null;
+ courseCardModel = null;
+ courseEnrollModel = null;
+ });
+
+ it('should exist', function() {
+ setupView(singleRunModeList);
+ expect(view).toBeDefined();
+ });
+
+ it('should render the course enroll view based on not enrolled data', function() {
+ setupView(singleRunModeList);
+ expect(view.$('.enrollment-info').html().trim()).toEqual('not enrolled');
+ expect(view.$('.enroll-button').text().trim()).toEqual('Enroll Now');
+ expect(view.$('.run-select').length).toBe(0);
+ });
+
+ it('should render the course enroll view based on enrolled data', function() {
+ singleRunModeList[0].is_enrolled = true;
+
+ setupView(singleRunModeList);
+
+ expect(view.$('.enrollment-info').html().trim()).toEqual('enrolled');
+ expect(view.$('.view-course-link').attr('href')).toEqual(context.run_modes[0].course_url);
+ expect(view.$('.view-course-link').text().trim()).toEqual('View Course');
+ expect(view.$('.run-select').length).toBe(0);
+ });
+
+ it('should allow the learner to view an archived course', function() {
+ // Regression test for ECOM-4974.
+ singleRunModeList[0].is_enrolled = true;
+ singleRunModeList[0].is_enrollment_open = false;
+ singleRunModeList[0].is_course_ended = true;
+
+ setupView(singleRunModeList);
+
+ expect(view.$('.view-course-link').text().trim()).toEqual('View Archived Course');
+ });
+
+ it('should not render anything if run modes is empty', function() {
+ setupView([]);
+ expect(view.$('.enrollment-info').length).toBe(0);
+ expect(view.$('.run-select').length).toBe(0);
+ expect(view.$('.enroll-button').length).toBe(0);
+ });
+
+ it('should render run selection drop down if mulitple run available', function() {
+ setupView(multiRunModeList);
+ expect(view.$('.run-select').length).toBe(1);
+ expect(view.$('.run-select').val()).toEqual('');
+ expect(view.$('.run-select option').length).toBe(3);
+ });
+
+ it('should switch run context if dropdown selection changed', function() {
+ setupView(multiRunModeList);
+ spyOn(courseCardModel, 'updateRun').and.callThrough();
+ expect(view.$('.run-select').val()).toEqual('');
+ view.$('.run-select').val(multiRunModeList[1].run_key);
+ view.$('.run-select').trigger('change');
+ expect(view.$('.run-select').val()).toEqual(multiRunModeList[1].run_key);
+ expect(courseCardModel.updateRun)
+ .toHaveBeenCalledWith(multiRunModeList[1].run_key);
+ expect(courseCardModel.get('run_key')).toEqual(multiRunModeList[1].run_key);
+ });
+
+ it('should enroll learner when enroll button clicked', function() {
+ setupView(singleRunModeList);
+ expect(view.$('.enroll-button').length).toBe(1);
+ spyOn(courseEnrollModel, 'save');
+ view.$('.enroll-button').click();
+ expect(courseEnrollModel.save).toHaveBeenCalled();
+ });
+
+ it('should enroll learner into the updated run with button click', function() {
+ setupView(multiRunModeList);
+ spyOn(courseEnrollModel, 'save');
+ view.$('.run-select').val(multiRunModeList[1].run_key);
+ view.$('.run-select').trigger('change');
+ view.$('.enroll-button').click();
+ expect(courseEnrollModel.save).toHaveBeenCalled();
+ });
+
+ it('should redirect to trackSelectionUrl when enrollment success for audit track', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = 'audit';
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+
+ it('should redirect when enrollment success for no track', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = null;
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+ it('should not redirect when urls not provided', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = 'verified';
+ setupView(singleRunModeList);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.verificationUrl).not.toBeDefined();
+ expect(view.dashboardUrl).not.toBeDefined();
+ expect(view.trackSelectionUrl).not.toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).not.toHaveBeenCalled();
+ });
+
+ it('should redirect to track selection on error', function() {
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollError(courseEnrollModel, {status: 500});
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+ it('should redirect to login on 403 error', function() {
+ var response = {
+ status: 403,
+ responseJSON: {
+ user_message_url: 'test_url/haha'
+ }};
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollError(courseEnrollModel, response);
+ expect(view.redirect).toHaveBeenCalledWith(
+ response.responseJSON.user_message_url);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/program_card_view_spec.js b/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
index 2bd1ed91f7..32603ecb2a 100644
--- a/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
@@ -1,124 +1,122 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/collections/program_progress_collection',
- 'js/learner_dashboard/models/program_model',
- 'js/learner_dashboard/views/program_card_view'
- ], function (Backbone, $, ProgressCollection, ProgramModel, ProgramCardView) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Program card View', function () {
- var view = null,
- programModel,
- program = {
- category: 'FooBar',
- status: 'active',
- subtitle: 'program 1',
- name: 'test program 1',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-03T19:18:50.061136Z',
- modified: '2016-03-25T13:45:21.220732Z',
- marketing_slug: 'p_2?param=haha&test=b',
- id: 146,
- detail_url: 'http://courses.edx.org/dashboard/programs/1/foo',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/test1',
- w435h145: 'http://www.edx.org/images/test2',
- w726h242: 'http://www.edx.org/images/test3'
- }
- },
- userProgress = [
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/collections/program_progress_collection',
+ 'js/learner_dashboard/models/program_model',
+ 'js/learner_dashboard/views/program_card_view'
+], function(Backbone, $, ProgressCollection, ProgramModel, ProgramCardView) {
+ 'use strict';
+ /* jslint maxlen: 500 */
+
+ describe('Program card View', function() {
+ var view = null,
+ programModel,
+ program = {
+ category: 'FooBar',
+ status: 'active',
+ subtitle: 'program 1',
+ name: 'test program 1',
+ organizations: [
{
- id: 146,
- completed: ['courses', 'the', 'user', 'completed'],
- in_progress: ['in', 'progress'],
- not_started : ['courses', 'not', 'yet', 'started']
- },
- {
- id: 147,
- completed: ['Course 1'],
- in_progress: [],
- not_started: ['Course 2', 'Course 3', 'Course 4']
+ display_name: 'edX',
+ key: 'edx'
}
],
- progressCollection = new ProgressCollection(),
- cardRenders = function($card) {
- expect($card).toBeDefined();
- expect($card.find('.title').html().trim()).toEqual(program.name);
- expect($card.find('.category span').html().trim()).toEqual(program.category);
- expect($card.find('.organization').html().trim()).toEqual(program.organizations[0].key);
- expect($card.find('.card-link').attr('href')).toEqual(program.detail_url);
- };
+ created: '2016-03-03T19:18:50.061136Z',
+ modified: '2016-03-25T13:45:21.220732Z',
+ marketing_slug: 'p_2?param=haha&test=b',
+ id: 146,
+ detail_url: 'http://courses.edx.org/dashboard/programs/1/foo',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/test1',
+ w435h145: 'http://www.edx.org/images/test2',
+ w726h242: 'http://www.edx.org/images/test3'
+ }
+ },
+ userProgress = [
+ {
+ id: 146,
+ completed: ['courses', 'the', 'user', 'completed'],
+ in_progress: ['in', 'progress'],
+ not_started: ['courses', 'not', 'yet', 'started']
+ },
+ {
+ id: 147,
+ completed: ['Course 1'],
+ in_progress: [],
+ not_started: ['Course 2', 'Course 3', 'Course 4']
+ }
+ ],
+ progressCollection = new ProgressCollection(),
+ cardRenders = function($card) {
+ expect($card).toBeDefined();
+ expect($card.find('.title').html().trim()).toEqual(program.name);
+ expect($card.find('.category span').html().trim()).toEqual(program.category);
+ expect($card.find('.organization').html().trim()).toEqual(program.organizations[0].key);
+ expect($card.find('.card-link').attr('href')).toEqual(program.detail_url);
+ };
- beforeEach(function() {
- setFixtures('
');
- programModel = new ProgramModel(program);
- progressCollection.set(userProgress);
- view = new ProgramCardView({
- model: programModel,
- context: {
- progressCollection: progressCollection
- }
- });
- });
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the program-card based on passed in context', function() {
- cardRenders(view.$el);
- });
-
- it('should call reEvaluatePicture if reLoadBannerImage is called', function(){
- spyOn(view, 'reEvaluatePicture');
- view.reLoadBannerImage();
- expect(view.reEvaluatePicture).toHaveBeenCalled();
- });
-
- it('should handle exceptions from reEvaluatePicture', function(){
- spyOn(view, 'reEvaluatePicture').and.callFake(function(){
- throw {name:'Picturefill had exceptions'};
- });
- view.reLoadBannerImage();
- expect(view.reEvaluatePicture).toHaveBeenCalled();
- expect(view.reLoadBannerImage).not.toThrow('Picturefill had exceptions');
-
- });
-
- it('should calculate the correct percentages for progress bars', function() {
- expect(view.$('.complete').css('width')).toEqual('40%');
- expect(view.$('.in-progress').css('width')).toEqual('20%');
- });
-
- it('should display the correct completed courses message', function() {
- var program = _.findWhere(userProgress, {id: 146}),
- completed = program.completed.length,
- total = completed + program.in_progress.length + program.not_started.length;
-
- expect(view.$('.certificate-status .status-text').not('.secondary').html()).toEqual('You have earned certificates in ' + completed + ' of the ' + total + ' courses so far.');
- });
-
- it('should render cards if there is no progressData', function() {
- view.remove();
- view = new ProgramCardView({
- model: programModel,
- context: {}
- });
- cardRenders(view.$el);
- expect(view.$('.progress').length).toEqual(0);
+ beforeEach(function() {
+ setFixtures('
');
+ programModel = new ProgramModel(program);
+ progressCollection.set(userProgress);
+ view = new ProgramCardView({
+ model: programModel,
+ context: {
+ progressCollection: progressCollection
+ }
});
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the program-card based on passed in context', function() {
+ cardRenders(view.$el);
+ });
+
+ it('should call reEvaluatePicture if reLoadBannerImage is called', function() {
+ spyOn(view, 'reEvaluatePicture');
+ view.reLoadBannerImage();
+ expect(view.reEvaluatePicture).toHaveBeenCalled();
+ });
+
+ it('should handle exceptions from reEvaluatePicture', function() {
+ spyOn(view, 'reEvaluatePicture').and.callFake(function() {
+ throw {name: 'Picturefill had exceptions'};
+ });
+ view.reLoadBannerImage();
+ expect(view.reEvaluatePicture).toHaveBeenCalled();
+ expect(view.reLoadBannerImage).not.toThrow('Picturefill had exceptions');
+ });
+
+ it('should calculate the correct percentages for progress bars', function() {
+ expect(view.$('.complete').css('width')).toEqual('40%');
+ expect(view.$('.in-progress').css('width')).toEqual('20%');
+ });
+
+ it('should display the correct completed courses message', function() {
+ var program = _.findWhere(userProgress, {id: 146}),
+ completed = program.completed.length,
+ total = completed + program.in_progress.length + program.not_started.length;
+
+ expect(view.$('.certificate-status .status-text').not('.secondary').html()).toEqual('You have earned certificates in ' + completed + ' of the ' + total + ' courses so far.');
+ });
+
+ it('should render cards if there is no progressData', function() {
+ view.remove();
+ view = new ProgramCardView({
+ model: programModel,
+ context: {}
+ });
+ cardRenders(view.$el);
+ expect(view.$('.progress').length).toEqual(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/program_details_header_spec.js b/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
index db8c560160..954ea62667 100644
--- a/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
+++ b/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
@@ -1,66 +1,65 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/program_header_view'
- ], function (Backbone, $, ProgramHeaderView) {
-
- 'use strict';
-
- describe('Program Details Header View', function () {
- var view = null,
- context = {
- urls: {
- program_listing_url: '/dashboard/programs'
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/program_header_view'
+], function(Backbone, $, ProgramHeaderView) {
+ 'use strict';
+
+ describe('Program Details Header View', function() {
+ var view = null,
+ context = {
+ urls: {
+ program_listing_url: '/dashboard/programs'
+ },
+ programData: {
+ uuid: '12-ab',
+ name: 'Astrophysics',
+ subtitle: 'Learn contemporary astrophysics from the leaders in the field.',
+ category: 'xseries',
+ organizations: [
+ {
+ display_name: 'Australian National University',
+ img: 'common/test/data/static/picture1.jpg',
+ key: 'ANUx'
+ }
+ ],
+ banner_image_urls: {
+ w1440h480: 'common/test/data/static/picture1.jpg',
+ w726h242: 'common/test/data/static/picture2.jpg',
+ w348h116: 'common/test/data/static/picture3.jpg'
},
- programData: {
- uuid: '12-ab',
- name: 'Astrophysics',
- subtitle: 'Learn contemporary astrophysics from the leaders in the field.',
- category: 'xseries',
- organizations: [
- {
- display_name: 'Australian National University',
- img: 'common/test/data/static/picture1.jpg',
- key: 'ANUx'
- }
- ],
- banner_image_urls: {
- w1440h480: 'common/test/data/static/picture1.jpg',
- w726h242: 'common/test/data/static/picture2.jpg',
- w348h116: 'common/test/data/static/picture3.jpg'
- },
- program_details_url: '/dashboard/programs'
- }
- };
+ program_details_url: '/dashboard/programs'
+ }
+ };
- beforeEach(function() {
- setFixtures('');
- view = new ProgramHeaderView({
- model: new Backbone.Model(context)
- });
- view.render();
+ beforeEach(function() {
+ setFixtures('');
+ view = new ProgramHeaderView({
+ model: new Backbone.Model(context)
});
+ view.render();
+ });
- afterEach(function() {
- view.remove();
- });
+ afterEach(function() {
+ view.remove();
+ });
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
- it('should render the header based on the passed in model', function() {
- var programListUrl = view.$('.breadcrumb-list .crumb:nth-of-type(2) .crumb-link').attr('href');
+ it('should render the header based on the passed in model', function() {
+ var programListUrl = view.$('.breadcrumb-list .crumb:nth-of-type(2) .crumb-link').attr('href');
- expect(view.$('.title').html()).toEqual(context.programData.name);
- expect(view.$('.subtitle').html()).toEqual(context.programData.subtitle);
- expect(view.$('.org-logo').length).toEqual(context.programData.organizations.length);
- expect(view.$('.org-logo').attr('src')).toEqual(context.programData.organizations[0].img);
- expect(view.$('.org-logo').attr('alt')).toEqual(
+ expect(view.$('.title').html()).toEqual(context.programData.name);
+ expect(view.$('.subtitle').html()).toEqual(context.programData.subtitle);
+ expect(view.$('.org-logo').length).toEqual(context.programData.organizations.length);
+ expect(view.$('.org-logo').attr('src')).toEqual(context.programData.organizations[0].img);
+ expect(view.$('.org-logo').attr('alt')).toEqual(
context.programData.organizations[0].display_name + '\'s logo'
);
- expect(programListUrl).toEqual(context.urls.program_listing_url);
- });
+ expect(programListUrl).toEqual(context.urls.program_listing_url);
});
- }
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js b/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
index c76b1f7e87..7bc6e9fead 100644
--- a/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
@@ -1,67 +1,65 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/sidebar_view'
- ], function (Backbone, $, SidebarView) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Sidebar View', function () {
- var view = null,
- context = {
- marketingUrl: 'https://www.example.org/programs',
- certificatesData: [
- {
- "display_name": "Testing",
- "credential_url": "https://credentials.example.com/credentials/uuid/"
- }
- ],
- sampleCertImageSrc: "/images/programs/sample-cert.png"
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/sidebar_view'
+], function(Backbone, $, SidebarView) {
+ 'use strict';
+ /* jslint maxlen: 500 */
- beforeEach(function() {
- setFixtures('');
-
- view = new SidebarView({
- el: '.sidebar',
- context: context
- });
- view.render();
+ describe('Sidebar View', function() {
+ var view = null,
+ context = {
+ marketingUrl: 'https://www.example.org/programs',
+ certificatesData: [
+ {
+ 'display_name': 'Testing',
+ 'credential_url': 'https://credentials.example.com/credentials/uuid/'
+ }
+ ],
+ sampleCertImageSrc: '/images/programs/sample-cert.png'
+ };
+
+ beforeEach(function() {
+ setFixtures('');
+
+ view = new SidebarView({
+ el: '.sidebar',
+ context: context
});
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the exploration panel given a marketing URL', function() {
- var $sidebar = view.$el;
- expect($sidebar.find('.program-advertise .advertise-message').html().trim())
- .toEqual('Browse recently launched courses and see what\'s new in your favorite subjects');
- expect($sidebar.find('.program-advertise .ad-link a').attr('href')).toEqual(context.marketingUrl);
- });
-
- it('should load the certificates based on passed in certificates list', function() {
- expect(view.$('.certificate-link').length).toBe(1);
- });
-
- it('should not load the advertising panel if no marketing URL is provided', function(){
- var $ad;
- view.remove();
- view = new SidebarView({
- el: '.sidebar',
- context: {certificatesData: []}
- });
- view.render();
- $ad = view.$el.find('.program-advertise');
- expect($ad.length).toBe(0);
- expect(view.$('.certificate-link').length).toBe(0);
- });
-
+ view.render();
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the exploration panel given a marketing URL', function() {
+ var $sidebar = view.$el;
+ expect($sidebar.find('.program-advertise .advertise-message').html().trim())
+ .toEqual('Browse recently launched courses and see what\'s new in your favorite subjects');
+ expect($sidebar.find('.program-advertise .ad-link a').attr('href')).toEqual(context.marketingUrl);
+ });
+
+ it('should load the certificates based on passed in certificates list', function() {
+ expect(view.$('.certificate-link').length).toBe(1);
+ });
+
+ it('should not load the advertising panel if no marketing URL is provided', function() {
+ var $ad;
+ view.remove();
+ view = new SidebarView({
+ el: '.sidebar',
+ context: {certificatesData: []}
+ });
+ view.render();
+ $ad = view.$el.find('.program-advertise');
+ expect($ad.length).toBe(0);
+ expect(view.$('.certificate-link').length).toBe(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/markdown_editor_spec.js b/lms/static/js/spec/markdown_editor_spec.js
index 674039575b..3ef0494b77 100644
--- a/lms/static/js/spec/markdown_editor_spec.js
+++ b/lms/static/js/spec/markdown_editor_spec.js
@@ -3,47 +3,47 @@ define(['Markdown.Editor'], function(MarkdownEditor) {
describe('Markdown.Editor', function() {
var editor = new MarkdownEditor();
- describe('util.isValidUrl', function () {
- it('should return true for http://example.com', function () {
+ describe('util.isValidUrl', function() {
+ it('should return true for http://example.com', function() {
expect(
editor.util.isValidUrl('http://example.com')
).toBeTruthy();
});
- it('should return true for https://example.com', function () {
+ it('should return true for https://example.com', function() {
expect(
editor.util.isValidUrl('https://example.com')
).toBeTruthy();
});
- it('should return true for ftp://example.com', function () {
+ it('should return true for ftp://example.com', function() {
expect(
editor.util.isValidUrl('ftp://example.com')
).toBeTruthy();
});
- it('should return false for http://', function () {
+ it('should return false for http://', function() {
expect(editor.util.isValidUrl('http://')).toBeFalsy();
});
- it('should return false for https://', function () {
+ it('should return false for https://', function() {
expect(editor.util.isValidUrl('https://')).toBeFalsy();
});
- it('should return false for ftp://', function () {
+ it('should return false for ftp://', function() {
expect(editor.util.isValidUrl('ftp://')).toBeFalsy();
});
- it('should return false for fake://example.com', function () {
+ it('should return false for fake://example.com', function() {
expect(
editor.util.isValidUrl('fakeprotocol://example.com')
).toBeFalsy();
});
- it('should return false for fake://', function () {
+ it('should return false for fake://', function() {
expect(
editor.util.isValidUrl('fakeprotocol://')
).toBeFalsy();
});
- it('should return false for www.noprotocol.com', function () {
+ it('should return false for www.noprotocol.com', function() {
expect(
editor.util.isValidUrl('www.noprotocol.com')
).toBeFalsy();
});
- it('should return false for an empty string', function () {
+ it('should return false for an empty string', function() {
expect(
editor.util.isValidUrl('')
).toBeFalsy();
diff --git a/lms/static/js/spec/navigation_spec.js b/lms/static/js/spec/navigation_spec.js
index 12e2964c59..ccdb529118 100644
--- a/lms/static/js/spec/navigation_spec.js
+++ b/lms/static/js/spec/navigation_spec.js
@@ -5,7 +5,7 @@ define(['jquery', 'js/utils/navigation'], function($) {
var accordion, chapterMenu;
function keyPressEvent(key) {
- return $.Event('keydown', { which: key });
+ return $.Event('keydown', {which: key});
}
beforeEach(function() {
@@ -20,9 +20,7 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('constructor', function() {
-
describe('always', function() {
-
it('ensures accordion is present', function() {
expect(accordion.length).toBe(1);
});
@@ -38,7 +36,6 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('open section with mouse click', function() {
-
it('ensures new section is opened and previous section is closed', function() {
accordion.find('.button-chapter').last().trigger('click');
@@ -58,7 +55,6 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('open section with spacebar', function() {
-
it('ensures new section is opened and previous section is closed', function() {
accordion.find('.button-chapter').last().focus().trigger(keyPressEvent(this.KEY.SPACE));
@@ -78,4 +74,4 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/lms/static/js/spec/search/search_spec.js b/lms/static/js/spec/search/search_spec.js
index 5c6685b088..e339eb5950 100644
--- a/lms/static/js/spec/search/search_spec.js
+++ b/lms/static/js/spec/search/search_spec.js
@@ -38,29 +38,26 @@ define([
'use strict';
describe('Search', function() {
- beforeEach(function () {
+ beforeEach(function() {
PageHelpers.preventBackboneChangingUrl();
});
- describe('SearchResult', function () {
-
- beforeEach(function () {
+ describe('SearchResult', function() {
+ beforeEach(function() {
this.result = new SearchResult();
});
- it('has properties', function () {
+ it('has properties', function() {
expect(this.result.get('location')).toBeDefined();
expect(this.result.get('content_type')).toBeDefined();
expect(this.result.get('excerpt')).toBeDefined();
expect(this.result.get('url')).toBeDefined();
});
-
});
- describe('SearchCollection', function () {
-
- beforeEach(function () {
+ describe('SearchCollection', function() {
+ beforeEach(function() {
this.collection = new SearchCollection();
this.onSearch = jasmine.createSpy('onSearch');
@@ -73,21 +70,21 @@ define([
this.collection.on('error', this.onError);
});
- it('sends a request without a course ID', function () {
+ it('sends a request without a course ID', function() {
var collection = new SearchCollection([]);
spyOn($, 'ajax');
collection.performSearch('search string');
expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/');
});
- it('sends a request with course ID', function () {
- var collection = new SearchCollection([], { courseId: 'edx101' });
+ it('sends a request with course ID', function() {
+ var collection = new SearchCollection([], {courseId: 'edx101'});
spyOn($, 'ajax');
collection.performSearch('search string');
expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/edx101');
});
- it('sends a request and parses the json result', function () {
+ it('sends a request and parses the json result', function() {
var requests = AjaxHelpers.requests(this);
this.collection.performSearch('search string');
var response = {
@@ -112,7 +109,7 @@ define([
expect(this.collection.first().attributes).toEqual(response.results[0].data);
});
- it('handles errors', function () {
+ it('handles errors', function() {
var requests = AjaxHelpers.requests(this);
this.collection.performSearch('search string');
AjaxHelpers.respondWithError(requests, 500);
@@ -120,19 +117,19 @@ define([
expect(this.onError).toHaveBeenCalled();
});
- it('loads next page', function () {
+ it('loads next page', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, results: [] };
+ var response = {total: 35, results: []};
this.collection.loadNextPage();
AjaxHelpers.respondWithJson(requests, response);
expect(this.onNext).toHaveBeenCalled();
expect(this.onError).not.toHaveBeenCalled();
});
- it('sends correct paging parameters', function () {
+ it('sends correct paging parameters', function() {
var requests = AjaxHelpers.requests(this);
var searchString = 'search string';
- var response = { total: 52, results: [] };
+ var response = {total: 52, results: []};
this.collection.performSearch(searchString);
AjaxHelpers.respondWithJson(requests, response);
this.collection.loadNextPage();
@@ -145,9 +142,9 @@ define([
expect($.ajax.calls.mostRecent().args[0].data.page_index).toEqual(2);
});
- it('has next page', function () {
+ it('has next page', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, access_denied_count: 5, results: [] };
+ var response = {total: 35, access_denied_count: 5, results: []};
this.collection.performSearch('search string');
AjaxHelpers.respondWithJson(requests, response);
expect(this.collection.hasNextPage()).toEqual(true);
@@ -156,9 +153,9 @@ define([
expect(this.collection.hasNextPage()).toEqual(false);
});
- it('aborts any previous request', function () {
+ it('aborts any previous request', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, results: [] };
+ var response = {total: 35, results: []};
this.collection.performSearch('old search');
this.collection.performSearch('new search');
@@ -178,15 +175,14 @@ define([
expect(this.onNext.calls.count()).toEqual(1);
});
- describe('reset state', function () {
-
- beforeEach(function () {
+ describe('reset state', function() {
+ beforeEach(function() {
this.collection.page = 2;
this.collection.totalCount = 35;
this.collection.latestModelsCount = 5;
});
- it('resets state when performing new search', function () {
+ it('resets state when performing new search', function() {
this.collection.performSearch('search string');
expect(this.collection.models.length).toEqual(0);
expect(this.collection.page).toEqual(0);
@@ -194,42 +190,37 @@ define([
expect(this.collection.latestModelsCount).toEqual(0);
});
- it('resets state when canceling a search', function () {
+ it('resets state when canceling a search', function() {
this.collection.cancelSearch();
expect(this.collection.models.length).toEqual(0);
expect(this.collection.page).toEqual(0);
expect(this.collection.totalCount).toEqual(0);
expect(this.collection.latestModelsCount).toEqual(0);
});
-
});
-
});
- describe('SearchRouter', function () {
-
- beforeEach(function () {
+ describe('SearchRouter', function() {
+ beforeEach(function() {
this.router = new SearchRouter();
this.onSearch = jasmine.createSpy('onSearch');
this.router.on('search', this.onSearch);
});
- it ('has a search route', function () {
+ it('has a search route', function() {
expect(this.router.routes['search/:query']).toEqual('search');
});
- it ('triggers a search event', function () {
+ it('triggers a search event', function() {
var query = 'mercury';
this.router.search(query);
expect(this.onSearch).toHaveBeenCalledWith(query);
});
-
});
- describe('SearchItemView', function () {
-
+ describe('SearchItemView', function() {
function beforeEachHelper(SearchItemView) {
TemplateHelpers.installTemplates([
'templates/search/course_search_item',
@@ -252,9 +243,9 @@ define([
url: 'path/to/content'
});
- this.item = new SearchItemView({ model: this.model });
+ this.item = new SearchItemView({model: this.model});
this.item.render();
- this.seqItem = new SearchItemView({ model: this.seqModel });
+ this.seqItem = new SearchItemView({model: this.seqModel});
this.seqItem.render();
}
@@ -277,10 +268,10 @@ define([
}
function logsSearchItemViewEvent() {
- this.model.collection = new SearchCollection([this.model], { course_id: 'edx101' });
+ this.model.collection = new SearchCollection([this.model], {course_id: 'edx101'});
this.item.render();
// Mock the redirect call
- spyOn(this.item, 'redirect').and.callFake( function() {} );
+ spyOn(this.item, 'redirect').and.callFake(function() {});
spyOn(Logger, 'log').and.returnValue($.Deferred().resolve());
this.item.$el.find('a').trigger('click');
expect(this.item.redirect).toHaveBeenCalled();
@@ -288,8 +279,8 @@ define([
expect(this.item.redirect).toHaveBeenCalled();
}
- describe('CourseSearchItemView', function () {
- beforeEach(function () {
+ describe('CourseSearchItemView', function() {
+ beforeEach(function() {
beforeEachHelper.call(this, CourseSearchItemView);
});
it('renders items correctly', rendersItem);
@@ -297,23 +288,21 @@ define([
it('logs view event', logsSearchItemViewEvent);
});
- describe('DashSearchItemView', function () {
- beforeEach(function () {
+ describe('DashSearchItemView', function() {
+ beforeEach(function() {
beforeEachHelper.call(this, DashSearchItemView);
});
it('renders items correctly', rendersItem);
it('renders Sequence items correctly', rendersSequentialItem);
- it('displays course name in breadcrumbs', function () {
+ it('displays course name in breadcrumbs', function() {
expect(this.seqItem.$el.find('.result-course-name')).toContainHtml(this.model.get('course_name'));
});
it('logs view event', logsSearchItemViewEvent);
});
-
});
- describe('SearchForm', function () {
-
+ describe('SearchForm', function() {
function trimsInputString() {
var term = ' search string ';
$('.search-field').val(term);
@@ -361,8 +350,8 @@ define([
expect($('.search-button')).toBeVisible();
}
- describe('CourseSearchForm', function () {
- beforeEach(function () {
+ describe('CourseSearchForm', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/course_search_form.html');
this.form = new CourseSearchForm();
this.onClear = jasmine.createSpy('onClear');
@@ -377,8 +366,8 @@ define([
it('clears search when search box is empty', clearsSearchOnEmpty);
});
- describe('DashSearchForm', function () {
- beforeEach(function () {
+ describe('DashSearchForm', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/dashboard_search_form.html');
this.form = new DashSearchForm();
this.onClear = jasmine.createSpy('onClear');
@@ -392,27 +381,25 @@ define([
it('clears search when clicking on cancel button', clearsSearchOnCancel);
it('clears search when search box is empty', clearsSearchOnEmpty);
});
-
});
- describe('SearchResultsView', function () {
-
- function showsLoadingMessage () {
+ describe('SearchResultsView', function() {
+ function showsLoadingMessage() {
this.resultsView.showLoadingMessage();
expect(this.resultsView.$contentElement).toBeHidden();
expect(this.resultsView.$el).toBeVisible();
expect(this.resultsView.$el).not.toBeEmpty();
}
- function showsErrorMessage () {
+ function showsErrorMessage() {
this.resultsView.showErrorMessage();
expect(this.resultsView.$contentElement).toBeHidden();
expect(this.resultsView.$el).toBeVisible();
expect(this.resultsView.$el).not.toBeEmpty();
}
- function returnsToContent () {
+ function returnsToContent() {
this.resultsView.clear();
expect(this.resultsView.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
expect(this.resultsView.$el).toBeHidden();
@@ -426,7 +413,7 @@ define([
expect(this.resultsView.$el.find('ol')).not.toExist();
}
- function rendersSearchResults () {
+ function rendersSearchResults() {
var searchResults = [{
location: ['section', 'subsection', 'unit'],
url: '/some/url/to/content',
@@ -451,36 +438,36 @@ define([
expect(this.resultsView.$el.find('li').length).toEqual(2);
}
- function showsMoreResultsLink () {
+ function showsMoreResultsLink() {
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next')[0]).toExist();
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return false; };
+ this.collection.hasNextPage = function() { return false; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next')[0]).not.toExist();
}
- function triggersNextPageEvent () {
+ function triggersNextPageEvent() {
var onNext = jasmine.createSpy('onNext');
this.resultsView.on('next', onNext);
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
this.resultsView.$el.find('a.search-load-next').click();
expect(onNext).toHaveBeenCalled();
}
- function showsLoadMoreSpinner () {
+ function showsLoadMoreSpinner() {
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
this.resultsView.loadNext();
// toBeVisible does not work with inline
- expect(this.resultsView.$el.find('a.search-load-next .icon')).toHaveCss({ 'display': 'inline' });
+ expect(this.resultsView.$el.find('a.search-load-next .icon')).toHaveCss({'display': 'inline'});
this.resultsView.renderNext();
expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
}
@@ -503,18 +490,18 @@ define([
]);
var MockCollection = Backbone.Collection.extend({
- hasNextPage: function () {},
+ hasNextPage: function() {},
latestModelsCount: 0,
pageSize: 20,
- latestModels: function () {
+ latestModels: function() {
return SearchCollection.prototype.latestModels.apply(this, arguments);
}
});
this.collection = new MockCollection();
- this.resultsView = new SearchResultsView({ collection: this.collection });
+ this.resultsView = new SearchResultsView({collection: this.collection});
}
- describe('CourseSearchResultsView', function () {
+ describe('CourseSearchResultsView', function() {
beforeEach(function() {
beforeEachHelper.call(this, CourseSearchResultsView);
this.contentElementDisplayValue = 'table-cell';
@@ -529,7 +516,7 @@ define([
it('shows a spinner when loading more results', showsLoadMoreSpinner);
});
- describe('DashSearchResultsView', function () {
+ describe('DashSearchResultsView', function() {
beforeEach(function() {
beforeEachHelper.call(this, DashSearchResultsView);
this.contentElementDisplayValue = 'block';
@@ -542,7 +529,7 @@ define([
it('shows a link to load more results', showsMoreResultsLink);
it('triggers an event for next page', triggersNextPageEvent);
it('shows a spinner when loading more results', showsLoadMoreSpinner);
- it('returns back to courses', function () {
+ it('returns back to courses', function() {
var onReset = jasmine.createSpy('onReset');
this.resultsView.on('reset', onReset);
this.resultsView.render();
@@ -553,13 +540,11 @@ define([
expect(this.resultsView.$el).toBeHidden();
});
});
-
});
- describe('SearchApp', function () {
-
- function showsLoadingMessage () {
+ describe('SearchApp', function() {
+ function showsLoadingMessage() {
$('.search-field').val('search string');
$('.search-button').trigger('click');
expect(this.$contentElement).toBeHidden();
@@ -567,7 +552,7 @@ define([
expect(this.$searchResults).not.toBeEmpty();
}
- function performsSearch () {
+ function performsSearch() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -589,7 +574,7 @@ define([
expect(this.$searchResults.find('li').length).toEqual(1);
}
- function showsErrorMessage () {
+ function showsErrorMessage() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -597,7 +582,7 @@ define([
expect(this.$searchResults).toContainHtml('There was an error');
}
- function updatesNavigationHistory () {
+ function updatesNavigationHistory() {
$('.search-field').val('edx');
$('.search-button').trigger('click');
expect(Backbone.history.navigate.calls.mostRecent().args[0]).toContain('search/edx');
@@ -605,7 +590,7 @@ define([
expect(Backbone.history.navigate.calls.argsFor(1)[0]).toBe('');
}
- function cancelsSearchRequest () {
+ function cancelsSearchRequest() {
var requests = AjaxHelpers.requests(this);
// send search request to server
$('.search-field').val('search string');
@@ -618,13 +603,13 @@ define([
expect(this.$searchResults).toBeHidden();
}
- function clearsResults () {
+ function clearsResults() {
$('.cancel-button').trigger('click');
expect(this.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
expect(this.$searchResults).toBeHidden();
}
- function loadsNextPage () {
+ function loadsNextPage() {
var requests = AjaxHelpers.requests(this);
var response = {
total: 1337,
@@ -652,14 +637,14 @@ define([
expect(this.$searchResults.find('li').length).toEqual(2);
}
- function navigatesToSearch () {
+ function navigatesToSearch() {
var requests = AjaxHelpers.requests(this);
Backbone.history.start();
Backbone.history.loadUrl('search/query');
expect(requests[0].requestBody).toContain('search_string=query');
}
- function loadTemplates () {
+ function loadTemplates() {
TemplateHelpers.installTemplates([
'templates/search/course_search_item',
'templates/search/dashboard_search_item',
@@ -670,9 +655,8 @@ define([
]);
}
- describe('CourseSearchApp', function () {
-
- beforeEach(function () {
+ describe('CourseSearchApp', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/course_search_form.html');
appendSetFixtures(
'
' +
@@ -688,7 +672,7 @@ define([
this.$searchResults = $('.courseware-results');
});
- afterEach(function (){
+ afterEach(function() {
Backbone.history.stop();
});
@@ -700,12 +684,10 @@ define([
it('clears results', clearsResults);
it('loads next page', loadsNextPage);
it('navigates to search', navigatesToSearch);
-
});
- describe('DashSearchApp', function () {
-
- beforeEach(function () {
+ describe('DashSearchApp', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/dashboard_search_form.html');
appendSetFixtures(
'
' +
@@ -720,7 +702,7 @@ define([
this.$searchResults = $('#dashboard-search-results');
});
- afterEach(function (){
+ afterEach(function() {
Backbone.history.stop();
});
@@ -732,7 +714,7 @@ define([
it('clears results', clearsResults);
it('loads next page', loadsNextPage);
it('navigates to search', navigatesToSearch);
- it('returns to course list', function () {
+ it('returns to course list', function() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -755,10 +737,7 @@ define([
expect(this.$searchResults).toBeHidden();
expect(this.$searchResults).toBeEmpty();
});
-
});
-
});
-
});
});
diff --git a/lms/static/js/spec/shoppingcart/shoppingcart_spec.js b/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
index c9ee98efbb..e600bcc73e 100644
--- a/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
+++ b/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
@@ -2,7 +2,7 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
function(AjaxHelpers) {
'use strict';
- describe("edx.shoppingcart.showcart.CartView", function() {
+ describe('edx.shoppingcart.showcart.CartView', function() {
var view = null;
var requests = null;
@@ -23,11 +23,11 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
// Verify that the client contacts the server to
// check for all th valid cart items
AjaxHelpers.expectRequest(
- requests, "GET", "/shoppingcart/verify_cart/"
+ requests, 'GET', '/shoppingcart/verify_cart/'
);
});
- it("cart has invalid items, course enrollment has been closed", function() {
+ it('cart has invalid items, course enrollment has been closed', function() {
// Simulate a response from the server containing the
// parameter 'is_course_enrollment_closed'. This decides that
// do we have all the cart items valid in the cart or not
@@ -38,21 +38,19 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
expect(view.responseFromServer).toHaveBeenCalled();
var data = view.responseFromServer.calls.mostRecent().args[0];
expect(data.is_course_enrollment_closed).toBe(true);
-
});
- it("cart has all valid items, course enrollment is still open", function() {
+ it('cart has all valid items, course enrollment is still open', function() {
// Simulate a response from the server containing the
// parameter 'is_course_enrollment_closed'. This decides that
// do we have all the cart items valid in the cart or not
- AjaxHelpers.respondWithJson(requests, {
+ AjaxHelpers.respondWithJson(requests, {
is_course_enrollment_closed: false
});
expect(view.responseFromServer).toHaveBeenCalled();
var data = view.responseFromServer.calls.mostRecent().args[0];
expect(data.is_course_enrollment_closed).toBe(false);
-
});
});
}
diff --git a/lms/static/js/spec/staff_debug_actions_spec.js b/lms/static/js/spec/staff_debug_actions_spec.js
index d916e2c12a..05cc047f4f 100644
--- a/lms/static/js/spec/staff_debug_actions_spec.js
+++ b/lms/static/js/spec/staff_debug_actions_spec.js
@@ -1,48 +1,47 @@
define([
- 'backbone',
- 'jquery',
- 'js/staff_debug_actions',
+ 'backbone',
+ 'jquery',
+ 'js/staff_debug_actions',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
- ],
- function (Backbone, $, tmp, AjaxHelpers) {
+],
+ function(Backbone, $, tmp, AjaxHelpers) {
'use strict';
var StaffDebug = window.StaffDebug;
- describe('StaffDebugActions', function () {
+ describe('StaffDebugActions', function() {
var location = 'i4x://edX/Open_DemoX/edx_demo_course/problem/test_loc';
var locationName = 'test_loc';
var fixture_id = 'sd_fu_' + locationName;
- var fixture = $('
', { id: fixture_id, placeholder: "userman" });
+ var fixture = $('
', {id: fixture_id, placeholder: 'userman'});
var escapableLocationName = 'test\.\*\+\?\^\:\$\{\}\(\)\|\]\[loc';
var escapableFixture_id = 'sd_fu_' + escapableLocationName;
- var escapableFixture = $('
', {id: escapableFixture_id, placeholder: "userman"});
+ var escapableFixture = $('
', {id: escapableFixture_id, placeholder: 'userman'});
var esclocationName = 'P2:problem_1';
- var escapableId = 'result_' + esclocationName;
+ var escapableId = 'result_' + esclocationName;
var escapableResultArea = $('
', {id: escapableId});
- describe('get_url ', function () {
- it('defines url to courseware ajax entry point', function () {
- spyOn(StaffDebug, "get_current_url")
- .and.returnValue("/courses/edX/Open_DemoX/edx_demo_course/courseware/stuff");
+ describe('get_url ', function() {
+ it('defines url to courseware ajax entry point', function() {
+ spyOn(StaffDebug, 'get_current_url')
+ .and.returnValue('/courses/edX/Open_DemoX/edx_demo_course/courseware/stuff');
expect(StaffDebug.get_url('rescore_problem'))
.toBe('/courses/edX/Open_DemoX/edx_demo_course/instructor/api/rescore_problem');
});
});
- describe('sanitize_string', function () {
- it('escapes escapable characters in a string', function () {
+ describe('sanitize_string', function() {
+ it('escapes escapable characters in a string', function() {
expect(StaffDebug.sanitized_string('.*+?^:${}()|][')).toBe('\\.\\*\\+\\?\\^\\:\\$\\{\\}\\(\\)\\|\\]\\[');
});
});
- describe('get_user', function () {
-
- it('gets the placeholder username if input field is empty', function () {
+ describe('get_user', function() {
+ it('gets the placeholder username if input field is empty', function() {
$('body').append(fixture);
expect(StaffDebug.get_user(locationName)).toBe('userman');
$('#' + fixture_id).remove();
});
- it('gets a filled in name if there is one', function () {
+ it('gets a filled in name if there is one', function() {
$('body').append(fixture);
$('#' + fixture_id).val('notuserman');
expect(StaffDebug.get_user(locationName)).toBe('notuserman');
@@ -56,13 +55,13 @@ define([
$("input[id^='sd_fu_']").remove();
});
});
- describe('do_idash_action success', function () {
- it('adds a success message to the results element after using an action', function () {
+ describe('do_idash_action success', function() {
+ it('adds a success message to the results element after using an action', function() {
$('body').append(escapableResultArea);
var requests = AjaxHelpers.requests(this);
var action = {
locationName: esclocationName,
- success_msg: 'Successfully reset the attempts for user userman',
+ success_msg: 'Successfully reset the attempts for user userman'
};
StaffDebug.do_idash_action(action);
AjaxHelpers.respondWithJson(requests, action);
@@ -70,22 +69,22 @@ define([
$('#result_' + locationName).remove();
});
});
- describe('do_idash_action error', function () {
- it('adds a failure message to the results element after using an action', function () {
+ describe('do_idash_action error', function() {
+ it('adds a failure message to the results element after using an action', function() {
$('body').append(escapableResultArea);
var requests = AjaxHelpers.requests(this);
var action = {
locationName: esclocationName,
- error_msg: 'Failed to reset attempts.',
+ error_msg: 'Failed to reset attempts.'
};
StaffDebug.do_idash_action(action);
AjaxHelpers.respondWithError(requests);
expect($('#idash_msg').text()).toBe('Failed to reset attempts. ');
$('#result_' + locationName).remove();
});
- });
- describe('reset', function () {
- it('makes an ajax call with the expected parameters', function () {
+ });
+ describe('reset', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -103,8 +102,8 @@ define([
$('#' + fixture_id).remove();
});
});
- describe('sdelete', function () {
- it('makes an ajax call with the expected parameters', function () {
+ describe('sdelete', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -123,8 +122,8 @@ define([
$('#' + fixture_id).remove();
});
});
- describe('rescore', function () {
- it('makes an ajax call with the expected parameters', function () {
+ describe('rescore', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -143,4 +142,4 @@ define([
});
});
});
- });
\ No newline at end of file
+ });
diff --git a/lms/static/js/spec/student_account/access_spec.js b/lms/static/js/spec/student_account/access_spec.js
index 6a2cc49608..66ddf2705a 100644
--- a/lms/static/js/spec/student_account/access_spec.js
+++ b/lms/static/js/spec/student_account/access_spec.js
@@ -1,232 +1,230 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/AccessView',
- 'js/student_account/views/FormView',
- 'js/student_account/enrollment',
- 'js/student_account/shoppingcart',
- 'js/student_account/emailoptin'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/AccessView',
+ 'js/student_account/views/FormView',
+ 'js/student_account/enrollment',
+ 'js/student_account/shoppingcart',
+ 'js/student_account/emailoptin'
+ ],
function($, _, Backbone, TemplateHelpers, AjaxHelpers, AccessView, FormView, EnrollmentInterface,
ShoppingCartInterface) {
-
- describe('edx.student.account.AccessView', function() {
- var requests = null,
- view = null,
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/submit',
- fields: [
- {
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'xsy@edx.org',
- instructions: 'Enter your email here.',
- restrictions: {}
- },
- {
- name: 'username',
- label: 'Username',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'Xsy',
- instructions: 'Enter your username here.',
- restrictions: {
- max_length: 200
+ describe('edx.student.account.AccessView', function() {
+ var requests = null,
+ view = null,
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/submit',
+ fields: [
+ {
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'xsy@edx.org',
+ instructions: 'Enter your email here.',
+ restrictions: {}
+ },
+ {
+ name: 'username',
+ label: 'Username',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'Xsy',
+ instructions: 'Enter your username here.',
+ restrictions: {
+ max_length: 200
+ }
}
- }
- ]
- },
- FORWARD_URL = (
+ ]
+ },
+ FORWARD_URL = (
'/account/finish_auth' +
'?course_id=edx%2FDemoX%2FFall' +
'&enrollment_action=enroll' +
'&next=%2Fdashboard'
),
- THIRD_PARTY_COMPLETE_URL = '/auth/complete/provider/';
+ THIRD_PARTY_COMPLETE_URL = '/auth/complete/provider/';
- var ajaxSpyAndInitialize = function(that, mode, nextUrl, finishAuthUrl) {
- var options = {
- initial_mode: mode,
- third_party_auth: {
- currentProvider: null,
- providers: [],
- secondaryProviders: [{name: "provider"}],
- finishAuthUrl: finishAuthUrl
+ var ajaxSpyAndInitialize = function(that, mode, nextUrl, finishAuthUrl) {
+ var options = {
+ initial_mode: mode,
+ third_party_auth: {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [{name: 'provider'}],
+ finishAuthUrl: finishAuthUrl
+ },
+ login_redirect_url: nextUrl, // undefined for default
+ platform_name: 'edX',
+ login_form_desc: FORM_DESCRIPTION,
+ registration_form_desc: FORM_DESCRIPTION,
+ password_reset_form_desc: FORM_DESCRIPTION
},
- login_redirect_url: nextUrl, // undefined for default
- platform_name: 'edX',
- login_form_desc: FORM_DESCRIPTION,
- registration_form_desc: FORM_DESCRIPTION,
- password_reset_form_desc: FORM_DESCRIPTION
- },
- $logistrationElement = $('#login-and-registration-container');
+ $logistrationElement = $('#login-and-registration-container');
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Initialize the access view
- view = new AccessView(_.extend(options, {el: $logistrationElement}));
+ view = new AccessView(_.extend(options, {el: $logistrationElement}));
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
// Mock the enrollment and shopping cart interfaces
- spyOn( EnrollmentInterface, 'enroll' ).and.callFake( function() {} );
- spyOn( ShoppingCartInterface, 'addCourseToCart' ).and.callFake( function() {} );
- };
+ spyOn(EnrollmentInterface, 'enroll').and.callFake(function() {});
+ spyOn(ShoppingCartInterface, 'addCourseToCart').and.callFake(function() {});
+ };
- var assertForms = function(visibleType, hiddenType) {
- expect($(visibleType)).not.toHaveClass('hidden');
- expect($(hiddenType)).toHaveClass('hidden');
- expect($('#password-reset-form')).toHaveClass('hidden');
- };
+ var assertForms = function(visibleType, hiddenType) {
+ expect($(visibleType)).not.toHaveClass('hidden');
+ expect($(hiddenType)).toHaveClass('hidden');
+ expect($('#password-reset-form')).toHaveClass('hidden');
+ };
- var selectForm = function(type) {
+ var selectForm = function(type) {
// Create a fake change event to control form toggling
- var changeEvent = $.Event('change');
- changeEvent.currentTarget = $('.form-toggle[data-type="' + type + '"]');
+ var changeEvent = $.Event('change');
+ changeEvent.currentTarget = $('.form-toggle[data-type="' + type + '"]');
// Load form corresponding to the change event
- view.toggleForm(changeEvent);
- };
+ view.toggleForm(changeEvent);
+ };
- beforeEach(function() {
- spyOn(window.history, 'pushState');
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/access');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/password_reset');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- TemplateHelpers.installTemplate('templates/student_account/institution_login');
- TemplateHelpers.installTemplate('templates/student_account/institution_register');
+ beforeEach(function() {
+ spyOn(window.history, 'pushState');
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/access');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ TemplateHelpers.installTemplate('templates/student_account/institution_login');
+ TemplateHelpers.installTemplate('templates/student_account/institution_register');
// Stub analytics tracking
- window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
- });
+ window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
+ });
- afterEach(function() {
- Backbone.history.stop();
- });
+ afterEach(function() {
+ Backbone.history.stop();
+ });
- it('can initially display the login form', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('can initially display the login form', function() {
+ ajaxSpyAndInitialize(this, 'login');
/* Verify that the login form is expanded, and that the
/* registration form is collapsed.
*/
- assertForms('#login-form', '#register-form');
- });
+ assertForms('#login-form', '#register-form');
+ });
- it('can initially display the registration form', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('can initially display the registration form', function() {
+ ajaxSpyAndInitialize(this, 'register');
/* Verify that the registration form is expanded, and that the
/* login form is collapsed.
*/
- assertForms('#register-form', '#login-form');
- });
+ assertForms('#register-form', '#login-form');
+ });
- it('toggles between the login and registration forms', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('toggles between the login and registration forms', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate selection of the registration form
- selectForm('register');
- assertForms('#register-form', '#login-form');
+ selectForm('register');
+ assertForms('#register-form', '#login-form');
// Simulate selection of the login form
- selectForm('login');
- assertForms('#login-form', '#register-form');
- });
+ selectForm('login');
+ assertForms('#login-form', '#register-form');
+ });
- it('toggles between the login and institution login view', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('toggles between the login and institution login view', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate clicking on institution login button
- $('#login-form .button-secondary-login[data-type="institution_login"]').click();
- assertForms('#institution_login-form', '#login-form');
+ $('#login-form .button-secondary-login[data-type="institution_login"]').click();
+ assertForms('#institution_login-form', '#login-form');
// Simulate selection of the login form
- selectForm('login');
- assertForms('#login-form', '#institution_login-form');
- });
+ selectForm('login');
+ assertForms('#login-form', '#institution_login-form');
+ });
- it('toggles between the register and institution register view', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('toggles between the register and institution register view', function() {
+ ajaxSpyAndInitialize(this, 'register');
// Simulate clicking on institution login button
- $('#register-form .button-secondary-login[data-type="institution_login"]').click();
- assertForms('#institution_login-form', '#register-form');
+ $('#register-form .button-secondary-login[data-type="institution_login"]').click();
+ assertForms('#institution_login-form', '#register-form');
// Simulate selection of the login form
- selectForm('register');
- assertForms('#register-form', '#institution_login-form');
- });
+ selectForm('register');
+ assertForms('#register-form', '#institution_login-form');
+ });
- it('displays the reset password form', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('displays the reset password form', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate a click on the reset password link
- view.resetPassword();
+ view.resetPassword();
// Verify that the login-anchor is hidden
- expect($("#login-anchor")).toHaveClass('hidden');
+ expect($('#login-anchor')).toHaveClass('hidden');
// Verify that the password reset form is not hidden
- expect($("#password-reset-form")).not.toHaveClass('hidden');
- });
+ expect($('#password-reset-form')).not.toHaveClass('hidden');
+ });
- it('redirects the user to the dashboard on auth complete', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('redirects the user to the dashboard on auth complete', function() {
+ ajaxSpyAndInitialize(this, 'register');
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Since we did not provide a ?next query param, expect a redirect to the dashboard.
- expect( view.redirect ).toHaveBeenCalledWith( '/dashboard' );
- });
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
- it('proceeds with the third party auth pipeline if active', function() {
- ajaxSpyAndInitialize(this, 'register', '/', THIRD_PARTY_COMPLETE_URL);
+ it('proceeds with the third party auth pipeline if active', function() {
+ ajaxSpyAndInitialize(this, 'register', '/', THIRD_PARTY_COMPLETE_URL);
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( THIRD_PARTY_COMPLETE_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(THIRD_PARTY_COMPLETE_URL);
+ });
- it('redirects the user to the next page on auth complete', function() {
+ it('redirects the user to the next page on auth complete', function() {
// The 'next' argument is often used to redirect to the auto-enrollment view
- ajaxSpyAndInitialize(this, 'register', FORWARD_URL);
+ ajaxSpyAndInitialize(this, 'register', FORWARD_URL);
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( FORWARD_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(FORWARD_URL);
+ });
- it('ignores redirect to external URLs', function() {
- ajaxSpyAndInitialize(this, 'register', "http://www.example.com");
+ it('ignores redirect to external URLs', function() {
+ ajaxSpyAndInitialize(this, 'register', 'http://www.example.com');
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Expect that we ignore the external URL and redirect to the dashboard
- expect( view.redirect ).toHaveBeenCalledWith( "/dashboard" );
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
});
-
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/account_settings_factory_spec.js b/lms/static/js/spec/student_account/account_settings_factory_spec.js
index bd661cf30d..fd417507c2 100644
--- a/lms/static/js/spec/student_account/account_settings_factory_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_factory_spec.js
@@ -9,12 +9,11 @@ define(['backbone',
'js/student_account/views/account_settings_factory',
'js/student_account/views/account_settings_view'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers, Helpers,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers, Helpers,
AccountSettingsFieldViewSpecHelpers, AccountSettingsPage) {
'use strict';
- describe("edx.user.AccountSettingsFactory", function () {
-
+ describe('edx.user.AccountSettingsFactory', function() {
var FIELDS_DATA = {
'country': {
'options': Helpers.FIELD_OPTIONS
@@ -31,7 +30,7 @@ define(['backbone',
}, 'preferred_language': {
'options': Helpers.FIELD_OPTIONS
}, 'time_zone': {
- 'options': Helpers.FIELD_OPTIONS,
+ 'options': Helpers.FIELD_OPTIONS
}
};
@@ -39,7 +38,7 @@ define(['backbone',
'providers': [
{
'id': 'oa2-network1',
- 'name': "Network1",
+ 'name': 'Network1',
'connected': true,
'accepts_logins': 'true',
'connect_url': 'yetanother1.com/auth/connect',
@@ -47,7 +46,7 @@ define(['backbone',
},
{
'id': 'oa2-network2',
- 'name': "Network2",
+ 'name': 'Network2',
'connected': true,
'accepts_logins': 'true',
'connect_url': 'yetanother2.com/auth/connect',
@@ -65,12 +64,11 @@ define(['backbone',
var requests;
- beforeEach(function () {
+ beforeEach(function() {
setFixtures('
');
});
- it("shows loading error when UserAccountModel fails to load", function() {
-
+ it('shows loading error when UserAccountModel fails to load', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -90,8 +88,7 @@ define(['backbone',
});
- it("shows loading error when UserPreferencesModel fails to load", function() {
-
+ it('shows loading error when UserPreferencesModel fails to load', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -111,6 +108,11 @@ define(['backbone',
request = requests[1];
expect(request.method).toBe('GET');
+ expect(request.url).toBe('/user_api/v1/preferences/time_zones/?country_code=1');
+ AjaxHelpers.respondWithJson(requests, Helpers.TIME_ZONE_RESPONSE);
+
+ request = requests[2];
+ expect(request.method).toBe('GET');
expect(request.url).toBe(Helpers.USER_PREFERENCES_API_URL);
AjaxHelpers.respondWithError(requests, 500);
@@ -119,8 +121,7 @@ define(['backbone',
Helpers.expectSettingsSectionsButNotFieldsToBeRendered(accountSettingsView);
});
- it("renders fields after the models are successfully fetched", function() {
-
+ it('renders fields after the models are successfully fetched', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -130,6 +131,7 @@ define(['backbone',
Helpers.expectSettingsSectionsButNotFieldsToBeRendered(accountSettingsView);
AjaxHelpers.respondWithJson(requests, Helpers.createAccountSettingsData());
+ AjaxHelpers.respondWithJson(requests, Helpers.TIME_ZONE_RESPONSE);
AjaxHelpers.respondWithJson(requests, Helpers.createUserPreferencesData());
Helpers.expectLoadingIndicatorIsVisible(accountSettingsView, false);
@@ -137,7 +139,7 @@ define(['backbone',
Helpers.expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView);
});
- it("expects all fields to behave correctly", function () {
+ it('expects all fields to behave correctly', function() {
var i, view;
requests = AjaxHelpers.requests(this);
@@ -145,6 +147,7 @@ define(['backbone',
var accountSettingsView = createAccountSettingsPage();
AjaxHelpers.respondWithJson(requests, Helpers.createAccountSettingsData());
+ AjaxHelpers.respondWithJson(requests, Helpers.TIME_ZONE_RESPONSE);
AjaxHelpers.respondWithJson(requests, Helpers.createUserPreferencesData());
AjaxHelpers.respondWithJson(requests, {}); // Page viewed analytics event
@@ -153,7 +156,7 @@ define(['backbone',
expect(sectionsData[0].fields.length).toBe(7);
var textFields = [sectionsData[0].fields[1], sectionsData[0].fields[2]];
- for (i = 0; i < textFields.length ; i++) {
+ for (i = 0; i < textFields.length; i++) {
view = textFields[i].view;
FieldViewsSpecHelpers.verifyTextField(view, {
title: view.options.title,
@@ -162,7 +165,7 @@ define(['backbone',
validValue: 'My Name',
invalidValue1: '',
invalidValue2: '@',
- validationError: "Think again!",
+ validationError: 'Think again!',
defaultValue: ''
}, requests);
}
@@ -182,7 +185,7 @@ define(['backbone',
validValue: Helpers.FIELD_OPTIONS[1][0],
invalidValue1: Helpers.FIELD_OPTIONS[2][0],
invalidValue2: Helpers.FIELD_OPTIONS[3][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
diff --git a/lms/static/js/spec/student_account/account_settings_fields_helpers.js b/lms/static/js/spec/student_account/account_settings_fields_helpers.js
index dba80de795..69e20281c9 100644
--- a/lms/static/js/spec/student_account/account_settings_fields_helpers.js
+++ b/lms/static/js/spec/student_account/account_settings_fields_helpers.js
@@ -5,10 +5,10 @@ define(['backbone',
'common/js/spec_helpers/template_helpers',
'js/spec/views/fields_helpers',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers) {
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers) {
'use strict';
- var verifyAuthField = function (view, data, requests) {
+ var verifyAuthField = function(view, data, requests) {
var selector = '.u-field-value .u-field-link-title-' + view.options.valueAttribute;
spyOn(view, 'redirect_to');
diff --git a/lms/static/js/spec/student_account/account_settings_fields_spec.js b/lms/static/js/spec/student_account/account_settings_fields_spec.js
index 5c6c5095d6..c69958b75a 100644
--- a/lms/static/js/spec/student_account/account_settings_fields_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_fields_spec.js
@@ -9,16 +9,15 @@ define(['backbone',
'js/student_account/views/account_settings_fields',
'js/student_account/models/user_account_model',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers,
AccountSettingsFieldViewSpecHelpers, AccountSettingsFieldViews) {
'use strict';
- describe("edx.AccountSettingsFieldViews", function () {
-
+ describe('edx.AccountSettingsFieldViews', function() {
var requests,
timerCallback;
- beforeEach(function () {
+ beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.clock().install();
});
@@ -27,7 +26,7 @@ define(['backbone',
jasmine.clock().uninstall();
});
- it("sends request to reset password on clicking link in PasswordFieldView", function() {
+ it('sends request to reset password on clicking link in PasswordFieldView', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(AccountSettingsFieldViews.PasswordFieldView, {
@@ -37,16 +36,83 @@ define(['backbone',
var view = new AccountSettingsFieldViews.PasswordFieldView(fieldData).render();
view.$('.u-field-value > button').click();
- AjaxHelpers.expectRequest(requests, 'POST', '/password_reset', "email=legolas%40woodland.middlearth");
- AjaxHelpers.respondWithJson(requests, {"success": "true"});
+ AjaxHelpers.expectRequest(requests, 'POST', '/password_reset', 'email=legolas%40woodland.middlearth');
+ AjaxHelpers.respondWithJson(requests, {'success': 'true'});
FieldViewsSpecHelpers.expectMessageContains(
view,
"We've sent a message to legolas@woodland.middlearth. " +
- "Click the link in the message to reset your password."
+ 'Click the link in the message to reset your password.'
);
});
- it("sends request to /i18n/setlang/ after changing language preference in LanguagePreferenceFieldView", function() {
+ it('update time zone dropdown after country dropdown changes', function() {
+ var baseSelector = '.u-field-value > select';
+ var groupsSelector = baseSelector + '> optgroup';
+ var groupOptionsSelector = groupsSelector + '> option';
+
+ var timeZoneData = FieldViewsSpecHelpers.createFieldData(AccountSettingsFieldViews.TimeZoneFieldView, {
+ valueAttribute: 'time_zone',
+ groupOptions: [{
+ groupTitle: gettext('All Time Zones'),
+ selectOptions: FieldViewsSpecHelpers.SELECT_OPTIONS
+ }],
+ persistChanges: true,
+ required: true
+ });
+ var countryData = FieldViewsSpecHelpers.createFieldData(AccountSettingsFieldViews.DropdownFieldView, {
+ valueAttribute: 'country',
+ options: [['KY', 'Cayman Islands'], ['CA', 'Canada'], ['GY', 'Guyana']],
+ persistChanges: true
+ });
+
+ var countryChange = {country: 'GY'};
+ var timeZoneChange = {time_zone: 'Pacific/Kosrae'};
+
+ var timeZoneView = new AccountSettingsFieldViews.TimeZoneFieldView(timeZoneData).render();
+ var countryView = new AccountSettingsFieldViews.DropdownFieldView(countryData).render();
+
+ requests = AjaxHelpers.requests(this);
+
+ timeZoneView.listenToCountryView(countryView);
+
+ // expect time zone dropdown to have single subheader ('All Time Zones')
+ expect(timeZoneView.$(groupsSelector).length).toBe(1);
+ expect(timeZoneView.$(groupOptionsSelector).length).toBe(3);
+ expect(timeZoneView.$(groupOptionsSelector)[0].value).toBe(FieldViewsSpecHelpers.SELECT_OPTIONS[0][0]);
+
+ // change country
+ countryView.$(baseSelector).val(countryChange[countryData.valueAttribute]).change();
+ FieldViewsSpecHelpers.expectAjaxRequestWithData(requests, countryChange);
+ AjaxHelpers.respondWithJson(requests, {success: 'true'});
+
+ AjaxHelpers.expectRequest(
+ requests,
+ 'GET',
+ '/user_api/v1/preferences/time_zones/?country_code=GY'
+ );
+ AjaxHelpers.respondWithJson(requests, [
+ {time_zone: 'America/Guyana', description: 'America/Guyana (ECT, UTC-0500)'},
+ {time_zone: 'Pacific/Kosrae', description: 'Pacific/Kosrae (KOST, UTC+1100)'}
+ ]);
+
+ // expect time zone dropdown to have two subheaders (country/all time zone sub-headers) with new values
+ expect(timeZoneView.$(groupsSelector).length).toBe(2);
+ expect(timeZoneView.$(groupOptionsSelector).length).toBe(5);
+ expect(timeZoneView.$(groupOptionsSelector)[0].value).toBe('America/Guyana');
+
+ // select time zone option from option
+ timeZoneView.$(baseSelector).val(timeZoneChange[timeZoneData.valueAttribute]).change();
+ FieldViewsSpecHelpers.expectAjaxRequestWithData(requests, timeZoneChange);
+ AjaxHelpers.respondWithJson(requests, {success: 'true'});
+ timeZoneView.render();
+
+ // expect time zone dropdown to have three subheaders (currently selected/country/all time zones)
+ expect(timeZoneView.$(groupsSelector).length).toBe(3);
+ expect(timeZoneView.$(groupOptionsSelector).length).toBe(6);
+ expect(timeZoneView.$(groupOptionsSelector)[0].value).toBe('Pacific/Kosrae');
+ });
+
+ it('sends request to /i18n/setlang/ after changing language in LanguagePreferenceFieldView', function() {
requests = AjaxHelpers.requests(this);
var selector = '.u-field-value > select';
@@ -70,7 +136,7 @@ define(['backbone',
'language=' + data[fieldData.valueAttribute]
);
AjaxHelpers.respondWithNoContent(requests);
- FieldViewsSpecHelpers.expectMessageContains(view, "Your changes have been saved.");
+ FieldViewsSpecHelpers.expectMessageContains(view, 'Your changes have been saved.');
data = {'language': FieldViewsSpecHelpers.SELECT_OPTIONS[1][0]};
view.$(selector).val(data[fieldData.valueAttribute]).change();
@@ -86,11 +152,11 @@ define(['backbone',
AjaxHelpers.respondWithError(requests, 500);
FieldViewsSpecHelpers.expectMessageContains(
view,
- "You must sign out and sign back in before your language changes take effect."
+ 'You must sign out and sign back in before your language changes take effect.'
);
});
- it("reads and saves the value correctly for LanguageProficienciesFieldView", function() {
+ it('reads and saves the value correctly for LanguageProficienciesFieldView', function() {
requests = AjaxHelpers.requests(this);
var selector = '.u-field-value > select';
@@ -111,7 +177,7 @@ define(['backbone',
AjaxHelpers.respondWithNoContent(requests);
});
- it("correctly links and unlinks from AuthFieldView", function() {
+ it('correctly links and unlinks from AuthFieldView', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
diff --git a/lms/static/js/spec/student_account/account_settings_view_spec.js b/lms/static/js/spec/student_account/account_settings_view_spec.js
index 2d21870a03..638fd119f0 100644
--- a/lms/static/js/spec/student_account/account_settings_view_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_view_spec.js
@@ -8,45 +8,43 @@ define(['backbone',
'js/student_account/models/user_account_model',
'js/student_account/views/account_settings_view'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, FieldViews, UserAccountModel,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, FieldViews, UserAccountModel,
AccountSettingsView) {
'use strict';
- describe("edx.user.AccountSettingsView", function () {
-
- var createAccountSettingsView = function () {
-
+ describe('edx.user.AccountSettingsView', function() {
+ var createAccountSettingsView = function() {
var model = new UserAccountModel();
model.set(Helpers.createAccountSettingsData());
var aboutSectionsData = [
{
- title: "Basic Account Information",
+ title: 'Basic Account Information',
fields: [
{
view: new FieldViews.ReadonlyFieldView({
model: model,
- title: "Username",
- valueAttribute: "username"
+ title: 'Username',
+ valueAttribute: 'username'
})
},
{
view: new FieldViews.TextFieldView({
model: model,
- title: "Full Name",
- valueAttribute: "name"
+ title: 'Full Name',
+ valueAttribute: 'name'
})
}
]
},
{
- title: "Additional Information",
+ title: 'Additional Information',
fields: [
{
view: new FieldViews.DropdownFieldView({
model: model,
- title: "Education Completed",
- valueAttribute: "level_of_education",
+ title: 'Education Completed',
+ valueAttribute: 'level_of_education',
options: Helpers.FIELD_OPTIONS
})
}
@@ -65,12 +63,11 @@ define(['backbone',
return accountSettingsView;
};
- beforeEach(function () {
+ beforeEach(function() {
setFixtures('
');
});
- it("shows loading error correctly", function() {
-
+ it('shows loading error correctly', function() {
var accountSettingsView = createAccountSettingsView();
accountSettingsView.render();
@@ -84,8 +81,7 @@ define(['backbone',
Helpers.expectSettingsSectionsButNotFieldsToBeRendered(accountSettingsView);
});
- it("renders all fields as expected", function() {
-
+ it('renders all fields as expected', function() {
var accountSettingsView = createAccountSettingsView();
accountSettingsView.render();
@@ -98,6 +94,5 @@ define(['backbone',
Helpers.expectLoadingErrorIsVisible(accountSettingsView, false);
Helpers.expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView);
});
-
});
});
diff --git a/lms/static/js/spec/student_account/account_spec.js b/lms/static/js/spec/student_account/account_spec.js
index bbca8f8ee2..e7504499ba 100644
--- a/lms/static/js/spec/student_account/account_spec.js
+++ b/lms/static/js/spec/student_account/account_spec.js
@@ -1,6 +1,6 @@
define(['js/student_account/account'],
function() {
- describe("edx.student.account.AccountModel", function() {
+ describe('edx.student.account.AccountModel', function() {
'use strict';
var account = null;
@@ -18,73 +18,73 @@ define(['js/student_account/account'],
var EXPECTED_ERRORS = {
email: {
- email: "Please enter a valid email address"
+ email: 'Please enter a valid email address'
},
password: {
- password: "Please enter a valid password"
+ password: 'Please enter a valid password'
}
};
beforeEach(function() {
account = new edx.student.account.AccountModel();
account.set({
- email: "bob@example.com",
- password: "password"
+ email: 'bob@example.com',
+ password: 'password'
});
});
- it("accepts valid email addresses", function() {
- assertValid({email: "bob@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob@test.example.com"}, true);
- assertValid({email: "bob@test-example.com"}, true);
+ it('accepts valid email addresses', function() {
+ assertValid({email: 'bob@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob@test.example.com'}, true);
+ assertValid({email: 'bob@test-example.com'}, true);
});
- it("rejects blank email addresses", function() {
- assertValid({email: ""}, false, EXPECTED_ERRORS.email);
- assertValid({email: " "}, false, EXPECTED_ERRORS.email);
+ it('rejects blank email addresses', function() {
+ assertValid({email: ''}, false, EXPECTED_ERRORS.email);
+ assertValid({email: ' '}, false, EXPECTED_ERRORS.email);
});
- it("rejects invalid email addresses", function() {
- assertValid({email: "bob"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "bob@example"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "@"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "@example.com"}, false, EXPECTED_ERRORS.email);
+ it('rejects invalid email addresses', function() {
+ assertValid({email: 'bob'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'bob@example'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: '@'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: '@example.com'}, false, EXPECTED_ERRORS.email);
// The server will reject emails with non-ASCII unicode
// Technically these are valid email addresses, but the email validator
// in Django 1.4 will reject them anyway, so we should too.
- assertValid({email: "fŕáńḱ@example.com"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "frank@éxáḿṕĺé.com"}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'fŕáńḱ@example.com'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'frank@éxáḿṕĺé.com'}, false, EXPECTED_ERRORS.email);
});
- it("rejects a long email address", function() {
+ it('rejects a long email address', function() {
// Construct an email exactly one character longer than the maximum length
- var longEmail = new Array(account.EMAIL_MAX_LENGTH - 10).join("e") + "@example.com";
+ var longEmail = new Array(account.EMAIL_MAX_LENGTH - 10).join('e') + '@example.com';
assertValid({email: longEmail}, false, EXPECTED_ERRORS.email);
});
- it("accepts a valid password", function() {
- assertValid({password: "password-test123"}, true, EXPECTED_ERRORS.password);
+ it('accepts a valid password', function() {
+ assertValid({password: 'password-test123'}, true, EXPECTED_ERRORS.password);
});
- it("rejects a short password", function() {
- assertValid({password: ""}, false, EXPECTED_ERRORS.password);
- assertValid({password: "a"}, false, EXPECTED_ERRORS.password);
- assertValid({password: "aa"}, true, EXPECTED_ERRORS.password);
+ it('rejects a short password', function() {
+ assertValid({password: ''}, false, EXPECTED_ERRORS.password);
+ assertValid({password: 'a'}, false, EXPECTED_ERRORS.password);
+ assertValid({password: 'aa'}, true, EXPECTED_ERRORS.password);
});
- it("rejects a long password", function() {
+ it('rejects a long password', function() {
// Construct a password exactly one character longer than the maximum length
- var longPassword = new Array(account.PASSWORD_MAX_LENGTH + 2).join("a");
+ var longPassword = new Array(account.PASSWORD_MAX_LENGTH + 2).join('a');
assertValid({password: longPassword}, false, EXPECTED_ERRORS.password);
});
});
- describe("edx.student.account.AccountView", function() {
+ describe('edx.student.account.AccountView', function() {
var view = null,
ajaxSuccess = true;
@@ -108,7 +108,7 @@ define(['js/student_account/account'],
expect(ajaxArgs.url).toEqual(url);
expect(ajaxArgs.type).toEqual(method);
expect(ajaxArgs.data).toEqual(data);
- expect(ajaxArgs.headers.hasOwnProperty("X-CSRFToken")).toBe(true);
+ expect(ajaxArgs.headers.hasOwnProperty('X-CSRFToken')).toBe(true);
};
var assertStatus = function(selection, success, errorClass, expectedStatus) {
@@ -121,13 +121,13 @@ define(['js/student_account/account'],
};
beforeEach(function() {
- var fixture = readFixtures("templates/student_account/account.underscore");
- setFixtures("
" + fixture + "
");
+ var fixture = readFixtures('templates/student_account/account.underscore');
+ setFixtures('
' + fixture + '
');
view = new edx.student.account.AccountView().render();
// Stub Ajax calls to return success/failure
- spyOn($, "ajax").and.callFake(function() {
+ spyOn($, 'ajax').and.callFake(function() {
return $.Deferred(function(defer) {
if (ajaxSuccess) {
defer.resolve();
@@ -138,63 +138,63 @@ define(['js/student_account/account'],
});
});
- it("requests an email address change", function() {
- requestEmailChange("bob@example.com", "password");
- assertAjax("email", "POST", {
- email: "bob@example.com",
- password: "password"
+ it('requests an email address change', function() {
+ requestEmailChange('bob@example.com', 'password');
+ assertAjax('email', 'POST', {
+ email: 'bob@example.com',
+ password: 'password'
});
- assertStatus(view.$requestStatus, true, "error", "Please check your email to confirm the change");
+ assertStatus(view.$requestStatus, true, 'error', 'Please check your email to confirm the change');
});
- it("displays email validation errors", function() {
+ it('displays email validation errors', function() {
// Invalid email should display an error
- requestEmailChange("invalid", "password");
- assertStatus(view.$emailStatus, false, "validation-error", "Please enter a valid email address");
+ requestEmailChange('invalid', 'password');
+ assertStatus(view.$emailStatus, false, 'validation-error', 'Please enter a valid email address');
// Once the error is fixed, the status should return to normal
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$emailStatus, true, "validation-error", "");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$emailStatus, true, 'validation-error', '');
});
- it("displays an invalid password error", function() {
+ it('displays an invalid password error', function() {
// Password cannot be empty
- requestEmailChange("bob@example.com", "");
- assertStatus(view.$passwordStatus, false, "validation-error", "Please enter a valid password");
+ requestEmailChange('bob@example.com', '');
+ assertStatus(view.$passwordStatus, false, 'validation-error', 'Please enter a valid password');
// Once the error is fixed, the status should return to normal
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$passwordStatus, true, "validation-error", "");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$passwordStatus, true, 'validation-error', '');
});
- it("displays server errors", function() {
+ it('displays server errors', function() {
// Simulate an error from the server
ajaxSuccess = false;
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$requestStatus, false, "error", "The data could not be saved.");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$requestStatus, false, 'error', 'The data could not be saved.');
// On retry, it should succeed
ajaxSuccess = true;
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$requestStatus, true, "error", "Please check your email to confirm the change");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$requestStatus, true, 'error', 'Please check your email to confirm the change');
});
- it("requests a password reset", function() {
+ it('requests a password reset', function() {
requestPasswordChange();
- assertAjax("password", "POST", {});
- assertStatus(view.$passwordResetStatus, true, "error", "Password reset email sent. Follow the link in the email to change your password.");
+ assertAjax('password', 'POST', {});
+ assertStatus(view.$passwordResetStatus, true, 'error', 'Password reset email sent. Follow the link in the email to change your password.');
});
- it("displays an error message if a password reset email could not be sent", function() {
+ it('displays an error message if a password reset email could not be sent', function() {
// Simulate an error from the server
ajaxSuccess = false;
requestPasswordChange();
- assertStatus(view.$passwordResetStatus, false, "error", "We weren't able to send you a password reset email.");
+ assertStatus(view.$passwordResetStatus, false, 'error', "We weren't able to send you a password reset email.");
// Retry, this time simulating success
ajaxSuccess = true;
requestPasswordChange();
- assertStatus(view.$passwordResetStatus, true, "error", "Password reset email sent. Follow the link in the email to change your password.");
+ assertStatus(view.$passwordResetStatus, true, 'error', 'Password reset email sent. Follow the link in the email to change your password.');
});
});
}
diff --git a/lms/static/js/spec/student_account/emailoptin_spec.js b/lms/static/js/spec/student_account/emailoptin_spec.js
index 00b49b4efa..6ef8b247e4 100644
--- a/lms/static/js/spec/student_account/emailoptin_spec.js
+++ b/lms/static/js/spec/student_account/emailoptin_spec.js
@@ -1,19 +1,18 @@
define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account/emailoptin'],
- function( AjaxHelpers, EmailOptInInterface ) {
+ function(AjaxHelpers, EmailOptInInterface) {
'use strict';
- describe( 'EmailOptInInterface', function() {
-
+ describe('EmailOptInInterface', function() {
var COURSE_KEY = 'edX/DemoX/Fall',
EMAIL_OPT_IN = 'True',
EMAIL_OPT_IN_URL = '/user_api/v1/preferences/email_opt_in/';
it('Opts in for organization emails', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EmailOptInInterface.setPreference( COURSE_KEY, EMAIL_OPT_IN );
+ EmailOptInInterface.setPreference(COURSE_KEY, EMAIL_OPT_IN);
// Expect that the correct request was made to the server
AjaxHelpers.expectRequest(
diff --git a/lms/static/js/spec/student_account/enrollment_spec.js b/lms/static/js/spec/student_account/enrollment_spec.js
index d7dea0512f..06c758fbf3 100644
--- a/lms/static/js/spec/student_account/enrollment_spec.js
+++ b/lms/static/js/spec/student_account/enrollment_spec.js
@@ -1,9 +1,8 @@
define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account/enrollment'],
- function( AjaxHelpers, EnrollmentInterface ) {
+ function(AjaxHelpers, EnrollmentInterface) {
'use strict';
- describe( 'EnrollmentInterface', function() {
-
+ describe('EnrollmentInterface', function() {
var COURSE_KEY = 'edX/DemoX/Fall',
ENROLL_URL = '/api/commerce/v0/baskets/',
FORWARD_URL = '/course_modes/choose/edX/DemoX/Fall/',
@@ -16,10 +15,10 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
it('enrolls a user in a course', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Expect that the correct request was made to the server
AjaxHelpers.expectRequest(
@@ -33,29 +32,29 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
AjaxHelpers.respondWithJson(requests, {});
// Verify that the user was redirected correctly
- expect( EnrollmentInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user if enrollment fails', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Simulate an error response from the server
AjaxHelpers.respondWithError(requests);
// Verify that the user was still redirected
- expect(EnrollmentInterface.redirect).toHaveBeenCalledWith( FORWARD_URL );
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user if blocked by an embargo', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Simulate an error response (403) from the server
// with a "user_message_url" parameter for the redirect.
@@ -63,14 +62,12 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
// explaining why he/she can't enroll.
AjaxHelpers.respondWithError(
requests, 403,
- { 'user_message_url': EMBARGO_MSG_URL }
+ {'user_message_url': EMBARGO_MSG_URL}
);
// Verify that the user was redirected
- expect(EnrollmentInterface.redirect).toHaveBeenCalledWith( EMBARGO_MSG_URL );
-
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(EMBARGO_MSG_URL);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_account/finish_auth_spec.js b/lms/static/js/spec/student_account/finish_auth_spec.js
index fcc53a0d59..89e7bc5368 100644
--- a/lms/static/js/spec/student_account/finish_auth_spec.js
+++ b/lms/static/js/spec/student_account/finish_auth_spec.js
@@ -1,42 +1,41 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'jquery.url',
- 'utility',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/FinishAuthView',
- 'js/student_account/enrollment',
- 'js/student_account/shoppingcart',
- 'js/student_account/emailoptin'
- ],
+ 'jquery',
+ 'jquery.url',
+ 'utility',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/FinishAuthView',
+ 'js/student_account/enrollment',
+ 'js/student_account/shoppingcart',
+ 'js/student_account/emailoptin'
+ ],
function($, url, utility, AjaxHelpers, FinishAuthView, EnrollmentInterface, ShoppingCartInterface,
EmailOptInInterface) {
+ describe('FinishAuthView', function() {
+ var requests = null,
+ view = null,
+ FORWARD_URL = '/courseware/next',
+ COURSE_KEY = 'course-v1:edX+test+15';
- describe('FinishAuthView', function() {
- var requests = null,
- view = null,
- FORWARD_URL = '/courseware/next',
- COURSE_KEY = 'course-v1:edX+test+15';
-
- var ajaxSpyAndInitialize = function(that) {
+ var ajaxSpyAndInitialize = function(that) {
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Initialize the access view
- view = new FinishAuthView({});
+ view = new FinishAuthView({});
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
// Mock the enrollment and shopping cart interfaces
- spyOn( EnrollmentInterface, 'enroll' ).and.callFake( function() {} );
- spyOn( ShoppingCartInterface, 'addCourseToCart' ).and.callFake( function() {} );
- spyOn( EmailOptInInterface, 'setPreference' )
- .and.callFake( function() { return {'always': function(r) { r(); }}; } );
+ spyOn(EnrollmentInterface, 'enroll').and.callFake(function() {});
+ spyOn(ShoppingCartInterface, 'addCourseToCart').and.callFake(function() {});
+ spyOn(EmailOptInInterface, 'setPreference')
+ .and.callFake(function() { return {'always': function(r) { r(); }}; });
- view.render();
- };
+ view.render();
+ };
/**
* Simulate query string params.
@@ -44,173 +43,173 @@
* @param {object} params Parameters to set, each of which
* should be prefixed with '?'
*/
- var setFakeQueryParams = function( params ) {
- spyOn( $, 'url' ).and.callFake(function( requestedParam ) {
- if ( params.hasOwnProperty(requestedParam) ) {
- return params[requestedParam];
- }
- });
- };
+ var setFakeQueryParams = function(params) {
+ spyOn($, 'url').and.callFake(function(requestedParam) {
+ if (params.hasOwnProperty(requestedParam)) {
+ return params[requestedParam];
+ }
+ });
+ };
- beforeEach(function() {
+ beforeEach(function() {
// Stub analytics tracking
- window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
- });
-
- it('saves the email opt-in preference before enrollment', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?email_opt_in': 'true'
+ window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
});
- ajaxSpyAndInitialize(this);
+ it('saves the email opt-in preference before enrollment', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?email_opt_in': 'true'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to save the email opt in preference
- expect( EmailOptInInterface.setPreference ).toHaveBeenCalledWith(
+ expect(EmailOptInInterface.setPreference).toHaveBeenCalledWith(
COURSE_KEY,
'true'
);
// Expect that the view tried to enroll the student
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/'
);
- });
-
- it('enrolls the user on auth complete', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY
});
- ajaxSpyAndInitialize(this);
+ it('enrolls the user on auth complete', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to enroll the student
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/'
);
- });
-
- it('sends the user to the course mode selection flow with bulk purchase workflow', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?purchase_workflow': 'bulk'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the course mode selection flow with bulk purchase workflow', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?purchase_workflow': 'bulk'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view redirected to the course
// mode select flow with the purchase_workflow parameter
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/?purchase_workflow=bulk'
);
- });
-
- it('sends the user to the payment flow for a paid course mode', function() {
- // Simulate providing enrollment query string params
- // AND specifying a course mode.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'verified'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the payment flow for a paid course mode', function() {
+ // Simulate providing enrollment query string params
+ // AND specifying a course mode.
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'verified'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to auto-enroll the student
// with a redirect into the payment flow.
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/verify_student/start-flow/' + COURSE_KEY + '/'
);
- });
+ });
- it('sends the user to the payment flow for a paid course mode with bulk purchase workflow', function() {
+ it('sends the user to the payment flow for a paid course mode with bulk purchase workflow', function() {
// Simulate providing enrollment query string params
// AND specifying a course mode
// AND purchase workflow type.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'professional-no-id',
- '?purchase_workflow': 'bulk'
- });
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'professional-no-id',
+ '?purchase_workflow': 'bulk'
+ });
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to auto-enroll the student
// with a redirect into the payment flow including the
// purchase_workflow parameter.
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/verify_student/start-flow/' + COURSE_KEY + '/?purchase_workflow=bulk'
);
- });
-
- it('sends the user to the student dashboard for an unpaid course mode', function() {
- // Simulate providing enrollment query string params
- // AND specifying a course mode.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'audit'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the student dashboard for an unpaid course mode', function() {
+ // Simulate providing enrollment query string params
+ // AND specifying a course mode.
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'audit'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried auto-enrolled the student
// and sent the student to the dashboard
// (skipping the payment flow).
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(COURSE_KEY, '/dashboard');
- });
-
- it('adds a white-label course to the shopping cart on auth complete', function() {
- // Simulate providing "add to cart" query string params
- setFakeQueryParams({
- '?enrollment_action': 'add_to_cart',
- '?course_id': COURSE_KEY
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(COURSE_KEY, '/dashboard');
});
- ajaxSpyAndInitialize(this);
+ it('adds a white-label course to the shopping cart on auth complete', function() {
+ // Simulate providing "add to cart" query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'add_to_cart',
+ '?course_id': COURSE_KEY
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to add the course to the user's shopping cart
- expect( ShoppingCartInterface.addCourseToCart ).toHaveBeenCalledWith( COURSE_KEY );
- });
+ expect(ShoppingCartInterface.addCourseToCart).toHaveBeenCalledWith(COURSE_KEY);
+ });
- it('redirects the user to the dashboard if no course is provided', function() {
- ajaxSpyAndInitialize(this);
+ it('redirects the user to the dashboard if no course is provided', function() {
+ ajaxSpyAndInitialize(this);
// Since we did not provide a ?next query param, expect a redirect to the dashboard.
- expect( view.redirect ).toHaveBeenCalledWith( '/dashboard' );
- });
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
- it('redirects the user to the next page when done', function() {
+ it('redirects the user to the next page when done', function() {
// Simulate providing a ?next query string parameter
- setFakeQueryParams({ '?next': FORWARD_URL });
+ setFakeQueryParams({'?next': FORWARD_URL});
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( FORWARD_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(FORWARD_URL);
+ });
- it('ignores redirect to external URLs', function() {
+ it('ignores redirect to external URLs', function() {
// Simulate providing a ?next query string parameter
// that goes to an external URL
- setFakeQueryParams({ '?next': "http://www.example.com" });
+ setFakeQueryParams({'?next': 'http://www.example.com'});
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Expect that we ignore the external URL and redirect to the dashboard
- expect( view.redirect ).toHaveBeenCalledWith( "/dashboard" );
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/helpers.js b/lms/static/js/spec/student_account/helpers.js
index 7cf34f8472..0bfc695ef1 100644
--- a/lms/static/js/spec/student_account/helpers.js
+++ b/lms/static/js/spec/student_account/helpers.js
@@ -23,7 +23,7 @@ define(['underscore'], function(_) {
requires_parental_consent: false,
country: '1',
language: null,
- bio: "About the student",
+ bio: 'About the student',
language_proficiencies: [{code: '1'}],
profile_image: PROFILE_IMAGE,
accomplishments_shared: false
@@ -49,10 +49,15 @@ define(['underscore'], function(_) {
['3', 'Option 3']
];
+ var TIME_ZONE_RESPONSE = [{
+ time_zone: 'America/Guyana',
+ description: 'America/Guyana (ECT, UTC-0500)'
+ }];
+
var IMAGE_MAX_BYTES = 1024 * 1024;
var IMAGE_MIN_BYTES = 100;
- var expectLoadingIndicatorIsVisible = function (view, visible) {
+ var expectLoadingIndicatorIsVisible = function(view, visible) {
if (visible) {
expect($('.ui-loading-indicator')).not.toHaveClass('is-hidden');
} else {
@@ -60,7 +65,7 @@ define(['underscore'], function(_) {
}
};
- var expectLoadingErrorIsVisible = function (view, visible) {
+ var expectLoadingErrorIsVisible = function(view, visible) {
if (visible) {
expect(view.$('.ui-loading-error')).not.toHaveClass('is-hidden');
} else {
@@ -83,11 +88,11 @@ define(['underscore'], function(_) {
}
};
- var expectSettingsSectionsButNotFieldsToBeRendered = function (accountSettingsView) {
- expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView, false)
+ var expectSettingsSectionsButNotFieldsToBeRendered = function(accountSettingsView) {
+ expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView, false);
};
- var expectSettingsSectionsAndFieldsToBeRendered = function (accountSettingsView, fieldsAreRendered) {
+ var expectSettingsSectionsAndFieldsToBeRendered = function(accountSettingsView, fieldsAreRendered) {
var sectionsData = accountSettingsView.options.tabSections.aboutTabSections;
var sectionElements = accountSettingsView.$('.section');
@@ -103,7 +108,7 @@ define(['underscore'], function(_) {
} else {
expect(sectionFieldElements.length).toBe(sectionsData[sectionIndex].fields.length);
- _.each(sectionFieldElements, function (sectionFieldElement, fieldIndex) {
+ _.each(sectionFieldElements, function(sectionFieldElement, fieldIndex) {
expectElementContainsField(sectionFieldElement, sectionsData[sectionIndex].fields[fieldIndex]);
});
}
@@ -123,10 +128,11 @@ define(['underscore'], function(_) {
createAccountSettingsData: createAccountSettingsData,
createUserPreferencesData: createUserPreferencesData,
FIELD_OPTIONS: FIELD_OPTIONS,
+ TIME_ZONE_RESPONSE: TIME_ZONE_RESPONSE,
expectLoadingIndicatorIsVisible: expectLoadingIndicatorIsVisible,
expectLoadingErrorIsVisible: expectLoadingErrorIsVisible,
expectElementContainsField: expectElementContainsField,
expectSettingsSectionsButNotFieldsToBeRendered: expectSettingsSectionsButNotFieldsToBeRendered,
- expectSettingsSectionsAndFieldsToBeRendered: expectSettingsSectionsAndFieldsToBeRendered,
+ expectSettingsSectionsAndFieldsToBeRendered: expectSettingsSectionsAndFieldsToBeRendered
};
});
diff --git a/lms/static/js/spec/student_account/hinted_login_spec.js b/lms/static/js/spec/student_account/hinted_login_spec.js
index 80f6bfd585..5fd0ecaf96 100644
--- a/lms/static/js/spec/student_account/hinted_login_spec.js
+++ b/lms/static/js/spec/student_account/hinted_login_spec.js
@@ -1,90 +1,89 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/HintedLoginView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/HintedLoginView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, HintedLoginView) {
+ describe('edx.student.account.HintedLoginView', function() {
+ var view = null,
+ requests = null,
+ PLATFORM_NAME = 'edX',
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ],
+ secondaryProviders: [
+ {
+ id: 'saml-harvard',
+ name: 'Harvard',
+ iconClass: 'fa-university',
+ loginUrl: '/auth/login/tpa-saml/?auth_entry=account_login&idp=harvard',
+ registerUrl: '/auth/login/tpa-saml/?auth_entry=account_register&idp=harvard'
+ }
+ ]
+ };
- describe('edx.student.account.HintedLoginView', function() {
- var view = null,
- requests = null,
- PLATFORM_NAME = 'edX',
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ],
- secondaryProviders: [
- {
- id: 'saml-harvard',
- name: 'Harvard',
- iconClass: 'fa-university',
- loginUrl: '/auth/login/tpa-saml/?auth_entry=account_login&idp=harvard',
- registerUrl: '/auth/login/tpa-saml/?auth_entry=account_register&idp=harvard'
- }
- ]
- };
-
- var createHintedLoginView = function(hintedProvider) {
+ var createHintedLoginView = function(hintedProvider) {
// Initialize the login view
- view = new HintedLoginView({
- thirdPartyAuth: THIRD_PARTY_AUTH,
- hintedProvider: hintedProvider,
- platformName: PLATFORM_NAME
- });
+ view = new HintedLoginView({
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ hintedProvider: hintedProvider,
+ platformName: PLATFORM_NAME
+ });
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
- view.render();
- };
+ view.render();
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/hinted_login');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/hinted_login');
+ });
- it('displays a choice as two buttons', function() {
- createHintedLoginView("oa2-google-oauth2");
+ it('displays a choice as two buttons', function() {
+ createHintedLoginView('oa2-google-oauth2');
- expect($('.proceed-button.button-oa2-google-oauth2')).toBeVisible();
- expect($('.form-toggle')).toBeVisible();
- expect($('.proceed-button.button-oa2-facebook')).not.toBeVisible();
- });
+ expect($('.proceed-button.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.form-toggle')).toBeVisible();
+ expect($('.proceed-button.button-oa2-facebook')).not.toBeVisible();
+ });
- it('works with secondary providers as well', function() {
- createHintedLoginView("saml-harvard");
+ it('works with secondary providers as well', function() {
+ createHintedLoginView('saml-harvard');
- expect($('.proceed-button.button-saml-harvard')).toBeVisible();
- expect($('.form-toggle')).toBeVisible();
- expect($('.proceed-button.button-oa2-google-oauth2')).not.toBeVisible();
- });
+ expect($('.proceed-button.button-saml-harvard')).toBeVisible();
+ expect($('.form-toggle')).toBeVisible();
+ expect($('.proceed-button.button-oa2-google-oauth2')).not.toBeVisible();
+ });
- it('redirects the user to the hinted provider if the user clicks the proceed button', function() {
- createHintedLoginView('oa2-google-oauth2');
+ it('redirects the user to the hinted provider if the user clicks the proceed button', function() {
+ createHintedLoginView('oa2-google-oauth2');
// Click the "Yes, proceed" button
- $('.proceed-button').click();
+ $('.proceed-button').click();
- expect(view.redirect).toHaveBeenCalledWith( '/auth/login/google-oauth2/?auth_entry=account_login' );
+ expect(view.redirect).toHaveBeenCalledWith('/auth/login/google-oauth2/?auth_entry=account_login');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/institution_login_spec.js b/lms/static/js/spec/student_account/institution_login_spec.js
index d087509ecc..839eefb25b 100644
--- a/lms/static/js/spec/student_account/institution_login_spec.js
+++ b/lms/static/js/spec/student_account/institution_login_spec.js
@@ -1,87 +1,85 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'js/student_account/views/InstitutionLoginView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/student_account/views/InstitutionLoginView'
+ ],
function($, _, TemplateHelpers, InstitutionLoginView) {
+ describe('edx.student.account.InstitutionLoginView', function() {
+ var view = null,
+ PLATFORM_NAME = 'edX',
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ };
- describe('edx.student.account.InstitutionLoginView', function() {
- var view = null,
- PLATFORM_NAME = 'edX',
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [],
- secondaryProviders: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
+ var createInstLoginView = function(mode) {
+ // Initialize the login view
+ view = new InstitutionLoginView({
+ mode: mode,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
+ view.render();
};
- var createInstLoginView = function(mode) {
- // Initialize the login view
- view = new InstitutionLoginView({
- mode: mode,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/institution_login');
+ TemplateHelpers.installTemplate('templates/student_account/institution_register');
});
- view.render();
- };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/institution_login');
- TemplateHelpers.installTemplate('templates/student_account/institution_register');
- });
+ it('displays a list of providers', function() {
+ var $google, $facebook;
- it('displays a list of providers', function() {
- var $google, $facebook;
-
- createInstLoginView('login');
- expect($('#institution_login-form').html()).not.toBe("");
- $google = $('li a:contains("Google")');
- expect($google).toBeVisible();
- expect($google).toHaveAttr(
+ createInstLoginView('login');
+ expect($('#institution_login-form').html()).not.toBe('');
+ $google = $('li a:contains("Google")');
+ expect($google).toBeVisible();
+ expect($google).toHaveAttr(
'href', '/auth/login/google-oauth2/?auth_entry=account_login'
);
- $facebook = $('li a:contains("Facebook")');
- expect($facebook).toBeVisible();
- expect($facebook).toHaveAttr(
+ $facebook = $('li a:contains("Facebook")');
+ expect($facebook).toBeVisible();
+ expect($facebook).toHaveAttr(
'href', '/auth/login/facebook/?auth_entry=account_login'
);
- });
+ });
- it('displays a list of providers', function() {
- var $google, $facebook;
+ it('displays a list of providers', function() {
+ var $google, $facebook;
- createInstLoginView('register');
- expect($('#institution_login-form').html()).not.toBe("");
- $google = $('li a:contains("Google")');
- expect($google).toBeVisible();
- expect($google).toHaveAttr(
+ createInstLoginView('register');
+ expect($('#institution_login-form').html()).not.toBe('');
+ $google = $('li a:contains("Google")');
+ expect($google).toBeVisible();
+ expect($google).toHaveAttr(
'href', '/auth/login/google-oauth2/?auth_entry=account_register'
);
- $facebook = $('li a:contains("Facebook")');
- expect($facebook).toBeVisible();
- expect($facebook).toHaveAttr(
+ $facebook = $('li a:contains("Facebook")');
+ expect($facebook).toBeVisible();
+ expect($facebook).toHaveAttr(
'href', '/auth/login/facebook/?auth_entry=account_register'
);
+ });
});
-
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/login_spec.js b/lms/static/js/spec/student_account/login_spec.js
index 2817b965db..7ecc50ee7b 100644
--- a/lms/static/js/spec/student_account/login_spec.js
+++ b/lms/static/js/spec/student_account/login_spec.js
@@ -1,321 +1,320 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'sinon',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/LoginModel',
- 'js/student_account/views/LoginView',
- 'js/student_account/models/PasswordResetModel'
- ],
+ 'jquery',
+ 'underscore',
+ 'sinon',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/LoginModel',
+ 'js/student_account/views/LoginView',
+ 'js/student_account/models/PasswordResetModel'
+ ],
function($, _, sinon, TemplateHelpers, AjaxHelpers, LoginModel, LoginView, PasswordResetModel) {
+ describe('edx.student.account.LoginView', function() {
+ var model = null,
+ resetModel = null,
+ view = null,
+ requests = null,
+ authComplete = false,
+ PLATFORM_NAME = 'edX',
+ USER_DATA = {
+ email: 'xsy@edx.org',
+ password: 'xsyisawesome',
+ remember: true
+ },
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ },
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/user_api/v1/account/login_session/',
+ fields: [
+ {
+ placeholder: 'username@domain.com',
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'email',
+ required: true,
+ instructions: 'Enter your email.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'password',
+ label: 'Password',
+ defaultValue: '',
+ type: 'password',
+ required: true,
+ instructions: 'Enter your password.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'remember',
+ label: 'Remember me',
+ defaultValue: '',
+ type: 'checkbox',
+ required: true,
+ instructions: 'Agree to the terms of service.',
+ restrictions: {}
+ }
+ ]
+ },
+ COURSE_ID = 'edX/demoX/Fall';
- describe('edx.student.account.LoginView', function() {
- var model = null,
- resetModel = null,
- view = null,
- requests = null,
- authComplete = false,
- PLATFORM_NAME = 'edX',
- USER_DATA = {
- email: 'xsy@edx.org',
- password: 'xsyisawesome',
- remember: true
- },
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
- },
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/user_api/v1/account/login_session/',
- fields: [
- {
- placeholder: 'username@domain.com',
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'email',
- required: true,
- instructions: 'Enter your email.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'password',
- label: 'Password',
- defaultValue: '',
- type: 'password',
- required: true,
- instructions: 'Enter your password.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'remember',
- label: 'Remember me',
- defaultValue: '',
- type: 'checkbox',
- required: true,
- instructions: 'Agree to the terms of service.',
- restrictions: {}
- }
- ]
- },
- COURSE_ID = 'edX/demoX/Fall';
-
- var createLoginView = function(test) {
+ var createLoginView = function(test) {
// Initialize the login model
- model = new LoginModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new LoginModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the passwordReset model
- resetModel = new PasswordResetModel({}, {
- method: 'GET',
- url: '#'
- });
+ resetModel = new PasswordResetModel({}, {
+ method: 'GET',
+ url: '#'
+ });
// Initialize the login view
- view = new LoginView({
- fields: FORM_DESCRIPTION.fields,
- model: model,
- resetModel: resetModel,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
- });
+ view = new LoginView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model,
+ resetModel: resetModel,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(test);
+ requests = AjaxHelpers.requests(test);
// Intercept events from the view
- authComplete = false;
- view.on("auth-complete", function() {
- authComplete = true;
- });
- };
+ authComplete = false;
+ view.on('auth-complete', function() {
+ authComplete = true;
+ });
+ };
- var submitForm = function(validationSuccess) {
+ var submitForm = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of login form data
- $('#login-email').val(USER_DATA.email);
- $('#login-password').val(USER_DATA.password);
+ $('#login-email').val(USER_DATA.email);
+ $('#login-password').val(USER_DATA.password);
// Check the 'Remember me' checkbox
- $('#login-remember').prop('checked', USER_DATA.remember);
+ $('#login-remember').prop('checked', USER_DATA.remember);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('logs the user in', function() {
- createLoginView(this);
+ it('logs the user in', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
$.param(USER_DATA)
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that auth-complete is triggered
- expect(authComplete).toBe(true);
- });
+ expect(authComplete).toBe(true);
+ });
- it('sends analytics info containing the enrolled course ID', function() {
- var expectedData;
+ it('sends analytics info containing the enrolled course ID', function() {
+ var expectedData;
- createLoginView(this);
+ createLoginView(this);
// Simulate that the user is attempting to enroll in a course
// by setting the course_id query string param.
- spyOn($, 'url').and.callFake(function( param ) {
- if (param === '?course_id') {
- return encodeURIComponent( COURSE_ID );
- }
- });
+ spyOn($, 'url').and.callFake(function(param) {
+ if (param === '?course_id') {
+ return encodeURIComponent(COURSE_ID);
+ }
+ });
// Attempt to login
- submitForm( true );
+ submitForm(true);
// Verify that the client sent the course ID for analytics
- expectedData = {};
- $.extend(expectedData, USER_DATA, {
- analytics: JSON.stringify({
- enroll_course_id: COURSE_ID
- })
- });
+ expectedData = {};
+ $.extend(expectedData, USER_DATA, {
+ analytics: JSON.stringify({
+ enroll_course_id: COURSE_ID
+ })
+ });
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( expectedData )
+ $.param(expectedData)
);
- });
+ });
- it('displays third-party auth login buttons', function() {
- createLoginView(this);
+ it('displays third-party auth login buttons', function() {
+ createLoginView(this);
// Verify that Google and Facebook registration buttons are displayed
- expect($('.button-oa2-google-oauth2')).toBeVisible();
- expect($('.button-oa2-facebook')).toBeVisible();
- });
+ expect($('.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.button-oa2-facebook')).toBeVisible();
+ });
- it('displays a link to the password reset form', function() {
- createLoginView(this);
+ it('displays a link to the password reset form', function() {
+ createLoginView(this);
// Verify that the password reset link is displayed
- expect($('.forgot-password')).toBeVisible();
- });
+ expect($('.forgot-password')).toBeVisible();
+ });
- it('validates login form fields', function() {
- createLoginView(this);
+ it('validates login form fields', function() {
+ createLoginView(this);
- submitForm(true);
+ submitForm(true);
// Verify that validation of form fields occurred
- expect(view.validate).toHaveBeenCalledWith($('#login-email')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#login-password')[0]);
- });
+ expect(view.validate).toHaveBeenCalledWith($('#login-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#login-password')[0]);
+ });
- it('displays login form validation errors', function() {
- createLoginView(this);
+ it('displays login form validation errors', function() {
+ createLoginView(this);
// Submit the form, with failed validation
- submitForm(false);
+ submitForm(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// Expect auth complete NOT to have been triggered
- expect(authComplete).toBe(false);
+ expect(authComplete).toBe(false);
// Form button should be re-enabled when errors occur
- expect(view.$submitButton).not.toHaveAttr('disabled');
- });
+ expect(view.$submitButton).not.toHaveAttr('disabled');
+ });
- it('displays an error if the server returns an error while logging in', function() {
- createLoginView(this);
+ it('displays an error if the server returns an error while logging in', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
// Form button should be re-enabled on server failure.
- expect(view.$submitButton).not.toHaveAttr('disabled');
+ expect(view.$submitButton).not.toHaveAttr('disabled');
// If we try again and succeed, the error should go away
- submitForm();
+ submitForm();
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden and auth complete is triggered
- expect(view.$errors).toHaveClass('hidden');
- expect(authComplete).toBe(true);
- });
+ expect(view.$errors).toHaveClass('hidden');
+ expect(authComplete).toBe(true);
+ });
- it('displays an error if there is no internet connection', function () {
- var clock,
- oldTimeout,
- timeout;
+ it('displays an error if there is no internet connection', function() {
+ var clock,
+ oldTimeout,
+ timeout;
// We're defining "no internet connection" in this case as the
// request timing out. We use a combination of the sinon fake
// timer and jQuery.ajaxSetup() to force a request timeout.
- clock = sinon.useFakeTimers();
- oldTimeout = $.ajaxSetup().timeout;
- timeout = 1;
- $.ajaxSetup({timeout: timeout});
+ clock = sinon.useFakeTimers();
+ oldTimeout = $.ajaxSetup().timeout;
+ timeout = 1;
+ $.ajaxSetup({timeout: timeout});
- createLoginView(this);
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate a request timeout
- clock.tick(timeout + 1);
+ clock.tick(timeout + 1);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
- expect(view.$errors.text()).toContain(
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
+ expect(view.$errors.text()).toContain(
'An error has occurred. Check your Internet connection and try again.'
);
// Finally, restore the old timeout and turn off the fake timer.
- $.ajaxSetup({timeout: oldTimeout});
- clock.restore();
- });
+ $.ajaxSetup({timeout: oldTimeout});
+ clock.restore();
+ });
- it('displays an error if there is a server error', function () {
- createLoginView(this);
+ it('displays an error if there is a server error', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests, 500);
+ AjaxHelpers.respondWithError(requests, 500);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
- expect(view.$errors.text()).toContain(
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
+ expect(view.$errors.text()).toContain(
'An error has occurred. Try refreshing the page, or check your Internet connection.'
);
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/logistration_factory_spec.js b/lms/static/js/spec/student_account/logistration_factory_spec.js
index d793360853..05c36b3a02 100644
--- a/lms/static/js/spec/student_account/logistration_factory_spec.js
+++ b/lms/static/js/spec/student_account/logistration_factory_spec.js
@@ -1,17 +1,16 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/logistration_factory'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/logistration_factory'
+ ],
function($, _, Backbone, TemplateHelpers, AjaxHelpers, LogistrationFactory) {
-
- describe('Logistration Factory', function() {
- var FORM_DESCRIPTION = {
+ describe('Logistration Factory', function() {
+ var FORM_DESCRIPTION = {
method: 'post',
submit_url: '/submit',
fields: [
@@ -40,91 +39,91 @@
]
};
- var initializeLogistrationFactory = function(that, mode, nextUrl, finishAuthUrl) {
- var options = {
- initial_mode: mode,
- third_party_auth: {
- currentProvider: null,
- providers: [],
- secondaryProviders: [{name: 'provider'}],
- finishAuthUrl: finishAuthUrl
- },
- login_redirect_url: nextUrl, // undefined for default
- platform_name: 'edX',
- login_form_desc: FORM_DESCRIPTION,
- registration_form_desc: FORM_DESCRIPTION,
- password_reset_form_desc: FORM_DESCRIPTION
- };
+ var initializeLogistrationFactory = function(that, mode, nextUrl, finishAuthUrl) {
+ var options = {
+ initial_mode: mode,
+ third_party_auth: {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [{name: 'provider'}],
+ finishAuthUrl: finishAuthUrl
+ },
+ login_redirect_url: nextUrl, // undefined for default
+ platform_name: 'edX',
+ login_form_desc: FORM_DESCRIPTION,
+ registration_form_desc: FORM_DESCRIPTION,
+ password_reset_form_desc: FORM_DESCRIPTION
+ };
// Initialize the logistration Factory
- LogistrationFactory(options);
- };
+ LogistrationFactory(options);
+ };
- var assertForms = function(visibleForm, hiddenFormsList) {
- expect($(visibleForm)).not.toHaveClass('hidden');
+ var assertForms = function(visibleForm, hiddenFormsList) {
+ expect($(visibleForm)).not.toHaveClass('hidden');
- _.each(hiddenFormsList, function (hiddenForm) {
- expect($(hiddenForm)).toHaveClass('hidden');
- }, this);
- };
+ _.each(hiddenFormsList, function(hiddenForm) {
+ expect($(hiddenForm)).toHaveClass('hidden');
+ }, this);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/access');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/password_reset')
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/access');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ });
- afterEach(function() {
- Backbone.history.stop();
- });
+ afterEach(function() {
+ Backbone.history.stop();
+ });
- it('can initially render the login form', function() {
- var hiddenFormsList;
+ it('can initially render the login form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'login');
+ initializeLogistrationFactory(this, 'login');
/* Verify that only login form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#register-form',
- '#password-reset-form'
- ];
- assertForms('#login-form', hiddenFormsList);
- });
+ hiddenFormsList = [
+ '#register-form',
+ '#password-reset-form'
+ ];
+ assertForms('#login-form', hiddenFormsList);
+ });
- it('can initially render the registration form', function() {
- var hiddenFormsList;
+ it('can initially render the registration form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'register');
+ initializeLogistrationFactory(this, 'register');
/* Verify that only registration form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#login-form',
- '#password-reset-form'
- ];
- assertForms('#register-form', hiddenFormsList);
- });
+ hiddenFormsList = [
+ '#login-form',
+ '#password-reset-form'
+ ];
+ assertForms('#register-form', hiddenFormsList);
+ });
- it('can initially render the password reset form', function() {
- var hiddenFormsList;
+ it('can initially render the password reset form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'reset');
+ initializeLogistrationFactory(this, 'reset');
/* Verify that only password reset form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#login-form',
- '#register-form'
- ];
- assertForms('#password-reset-form', hiddenFormsList);
+ hiddenFormsList = [
+ '#login-form',
+ '#register-form'
+ ];
+ assertForms('#password-reset-form', hiddenFormsList);
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/password_reset_spec.js b/lms/static/js/spec/student_account/password_reset_spec.js
index 43fd551e89..2124d6c57b 100644
--- a/lms/static/js/spec/student_account/password_reset_spec.js
+++ b/lms/static/js/spec/student_account/password_reset_spec.js
@@ -1,147 +1,146 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/PasswordResetModel',
- 'js/student_account/views/PasswordResetView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/PasswordResetModel',
+ 'js/student_account/views/PasswordResetView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, PasswordResetModel, PasswordResetView) {
+ describe('edx.student.account.PasswordResetView', function() {
+ var model = null,
+ view = null,
+ requests = null,
+ EMAIL = 'xsy@edx.org',
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/account/password',
+ fields: [{
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'place@holder.org',
+ instructions: 'Enter your email.',
+ restrictions: {}
+ }]
+ };
- describe('edx.student.account.PasswordResetView', function() {
- var model = null,
- view = null,
- requests = null,
- EMAIL = 'xsy@edx.org',
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/account/password',
- fields: [{
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'place@holder.org',
- instructions: 'Enter your email.',
- restrictions: {}
- }]
- };
-
- var createPasswordResetView = function(that) {
+ var createPasswordResetView = function(that) {
// Initialize the password reset model
- model = new PasswordResetModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new PasswordResetModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the password reset view
- view = new PasswordResetView({
- fields: FORM_DESCRIPTION.fields,
- model: model
- });
+ view = new PasswordResetView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
- };
+ requests = AjaxHelpers.requests(that);
+ };
- var submitEmail = function(validationSuccess) {
+ var submitEmail = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of an email address
- $('#password-reset-email').val(EMAIL);
+ $('#password-reset-email').val(EMAIL);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/password_reset');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('allows the user to request a new password', function() {
- createPasswordResetView(this);
+ it('allows the user to request a new password', function() {
+ createPasswordResetView(this);
// Submit the form, with successful validation
- submitEmail(true);
+ submitEmail(true);
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param({ email: EMAIL })
+ $.param({email: EMAIL})
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that the success message is visible
- expect($('.js-reset-success')).not.toHaveClass('hidden');
+ expect($('.js-reset-success')).not.toHaveClass('hidden');
// Verify that login form has loaded
- expect($('#login-form')).not.toHaveClass('hidden');
+ expect($('#login-form')).not.toHaveClass('hidden');
// Verify that password reset view has been removed
- expect($( view.el ).html().length).toEqual(0);
- });
+ expect($(view.el).html().length).toEqual(0);
+ });
- it('validates the email field', function() {
- createPasswordResetView(this);
+ it('validates the email field', function() {
+ createPasswordResetView(this);
// Submit the form, with successful validation
- submitEmail(true);
+ submitEmail(true);
// Verify that validation of the email field occurred
- expect(view.validate).toHaveBeenCalledWith($('#password-reset-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#password-reset-email')[0]);
// Verify that no submission errors are visible
- expect(view.$errors).toHaveClass('hidden');
- });
+ expect(view.$errors).toHaveClass('hidden');
+ });
- it('displays password reset validation errors', function() {
- createPasswordResetView(this);
+ it('displays password reset validation errors', function() {
+ createPasswordResetView(this);
// Submit the form, with failed validation
- submitEmail(false);
+ submitEmail(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
- });
+ expect(view.$errors).not.toHaveClass('hidden');
+ });
- it('displays an error if the server returns an error while sending a password reset email', function() {
- createPasswordResetView(this);
- submitEmail(true);
+ it('displays an error if the server returns an error while sending a password reset email', function() {
+ createPasswordResetView(this);
+ submitEmail(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// If we try again and succeed, the error should go away
- submitEmail();
+ submitEmail();
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden
- expect(view.$errors).toHaveClass('hidden');
+ expect(view.$errors).toHaveClass('hidden');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/register_spec.js b/lms/static/js/spec/student_account/register_spec.js
index 2363af913e..d6ea9987e6 100644
--- a/lms/static/js/spec/student_account/register_spec.js
+++ b/lms/static/js/spec/student_account/register_spec.js
@@ -1,356 +1,355 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/RegisterModel',
- 'js/student_account/views/RegisterView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/RegisterModel',
+ 'js/student_account/views/RegisterView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, RegisterModel, RegisterView) {
+ describe('edx.student.account.RegisterView', function() {
+ var model = null,
+ view = null,
+ requests = null,
+ authComplete = false,
+ PLATFORM_NAME = 'edX',
+ COURSE_ID = 'edX/DemoX/Fall',
+ USER_DATA = {
+ email: 'xsy@edx.org',
+ name: 'Xsy M. Education',
+ username: 'Xsy',
+ password: 'xsyisawesome',
+ level_of_education: 'p',
+ gender: 'm',
+ year_of_birth: 2014,
+ mailing_address: '141 Portland',
+ goals: 'To boldly learn what no letter of the alphabet has learned before',
+ honor_code: true
+ },
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ },
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/user_api/v1/account/registration/',
+ fields: [
+ {
+ placeholder: 'username@domain.com',
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'email',
+ required: true,
+ instructions: 'Enter your email.',
+ restrictions: {}
+ },
+ {
+ placeholder: 'Jane Doe',
+ name: 'name',
+ label: 'Full Name',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ instructions: 'Enter your username.',
+ restrictions: {}
+ },
+ {
+ placeholder: 'JaneDoe',
+ name: 'username',
+ label: 'Username',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ instructions: 'Enter your username.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'password',
+ label: 'Password',
+ defaultValue: '',
+ type: 'password',
+ required: true,
+ instructions: 'Enter your password.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'level_of_education',
+ label: 'Highest Level of Education Completed',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 'p', name: 'Doctorate'},
+ {value: 'm', name: "Master's or professional degree"},
+ {value: 'b', name: "Bachelor's degree"}
+ ],
+ required: false,
+ instructions: 'Select your education level.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'gender',
+ label: 'Gender',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 'm', name: 'Male'},
+ {value: 'f', name: 'Female'},
+ {value: 'o', name: 'Other'}
+ ],
+ required: false,
+ instructions: 'Select your gender.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'year_of_birth',
+ label: 'Year of Birth',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 1900, name: '1900'},
+ {value: 1950, name: '1950'},
+ {value: 2014, name: '2014'}
+ ],
+ required: false,
+ instructions: 'Select your year of birth.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'mailing_address',
+ label: 'Mailing Address',
+ defaultValue: '',
+ type: 'textarea',
+ required: false,
+ instructions: 'Enter your mailing address.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'goals',
+ label: 'Goals',
+ defaultValue: '',
+ type: 'textarea',
+ required: false,
+ instructions: "If you'd like, tell us why you're interested in edX.",
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'honor_code',
+ label: 'I agree to the
Terms of Service and Honor Code ',
+ defaultValue: '',
+ type: 'checkbox',
+ required: true,
+ instructions: '',
+ restrictions: {}
+ }
+ ]
+ };
- describe('edx.student.account.RegisterView', function() {
- var model = null,
- view = null,
- requests = null,
- authComplete = false,
- PLATFORM_NAME = 'edX',
- COURSE_ID = 'edX/DemoX/Fall',
- USER_DATA = {
- email: 'xsy@edx.org',
- name: 'Xsy M. Education',
- username: 'Xsy',
- password: 'xsyisawesome',
- level_of_education: 'p',
- gender: 'm',
- year_of_birth: 2014,
- mailing_address: '141 Portland',
- goals: 'To boldly learn what no letter of the alphabet has learned before',
- honor_code: true
- },
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
- },
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/user_api/v1/account/registration/',
- fields: [
- {
- placeholder: 'username@domain.com',
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'email',
- required: true,
- instructions: 'Enter your email.',
- restrictions: {}
- },
- {
- placeholder: 'Jane Doe',
- name: 'name',
- label: 'Full Name',
- defaultValue: '',
- type: 'text',
- required: true,
- instructions: 'Enter your username.',
- restrictions: {}
- },
- {
- placeholder: 'JaneDoe',
- name: 'username',
- label: 'Username',
- defaultValue: '',
- type: 'text',
- required: true,
- instructions: 'Enter your username.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'password',
- label: 'Password',
- defaultValue: '',
- type: 'password',
- required: true,
- instructions: 'Enter your password.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'level_of_education',
- label: 'Highest Level of Education Completed',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: "p", name: "Doctorate"},
- {value: "m", name: "Master's or professional degree"},
- {value: "b", name: "Bachelor's degree"}
- ],
- required: false,
- instructions: 'Select your education level.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'gender',
- label: 'Gender',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: "m", name: "Male"},
- {value: "f", name: "Female"},
- {value: "o", name: "Other"}
- ],
- required: false,
- instructions: 'Select your gender.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'year_of_birth',
- label: 'Year of Birth',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: 1900, name: "1900"},
- {value: 1950, name: "1950"},
- {value: 2014, name: "2014"}
- ],
- required: false,
- instructions: 'Select your year of birth.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'mailing_address',
- label: 'Mailing Address',
- defaultValue: '',
- type: 'textarea',
- required: false,
- instructions: 'Enter your mailing address.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'goals',
- label: 'Goals',
- defaultValue: '',
- type: 'textarea',
- required: false,
- instructions: "If you'd like, tell us why you're interested in edX.",
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'honor_code',
- label: 'I agree to the
Terms of Service and Honor Code ',
- defaultValue: '',
- type: 'checkbox',
- required: true,
- instructions: '',
- restrictions: {}
- }
- ]
- };
-
- var createRegisterView = function(that) {
+ var createRegisterView = function(that) {
// Initialize the register model
- model = new RegisterModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new RegisterModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the register view
- view = new RegisterView({
- fields: FORM_DESCRIPTION.fields,
- model: model,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
- });
+ view = new RegisterView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Intercept events from the view
- authComplete = false;
- view.on("auth-complete", function() {
- authComplete = true;
- });
- };
+ authComplete = false;
+ view.on('auth-complete', function() {
+ authComplete = true;
+ });
+ };
- var submitForm = function(validationSuccess) {
+ var submitForm = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of registration form data
- $('#register-email').val(USER_DATA.email);
- $('#register-name').val(USER_DATA.name);
- $('#register-username').val(USER_DATA.username);
- $('#register-password').val(USER_DATA.password);
- $('#register-level_of_education').val(USER_DATA.level_of_education);
- $('#register-gender').val(USER_DATA.gender);
- $('#register-year_of_birth').val(USER_DATA.year_of_birth);
- $('#register-mailing_address').val(USER_DATA.mailing_address);
- $('#register-goals').val(USER_DATA.goals);
+ $('#register-email').val(USER_DATA.email);
+ $('#register-name').val(USER_DATA.name);
+ $('#register-username').val(USER_DATA.username);
+ $('#register-password').val(USER_DATA.password);
+ $('#register-level_of_education').val(USER_DATA.level_of_education);
+ $('#register-gender').val(USER_DATA.gender);
+ $('#register-year_of_birth').val(USER_DATA.year_of_birth);
+ $('#register-mailing_address').val(USER_DATA.mailing_address);
+ $('#register-goals').val(USER_DATA.goals);
// Check the honor code checkbox
- $('#register-honor_code').prop('checked', USER_DATA.honor_code);
+ $('#register-honor_code').prop('checked', USER_DATA.honor_code);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('registers a new user', function() {
- createRegisterView(this);
+ it('registers a new user', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( USER_DATA )
+ $.param(USER_DATA)
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that auth complete is triggered
- expect(authComplete).toBe(true);
+ expect(authComplete).toBe(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
- });
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
- it('sends analytics info containing the enrolled course ID', function() {
- var expectedData;
+ it('sends analytics info containing the enrolled course ID', function() {
+ var expectedData;
- createRegisterView(this);
+ createRegisterView(this);
// Simulate that the user is attempting to enroll in a course
// by setting the course_id query string param.
- spyOn($, 'url').and.callFake(function( param ) {
- if (param === '?course_id') {
- return encodeURIComponent( COURSE_ID );
- }
- });
+ spyOn($, 'url').and.callFake(function(param) {
+ if (param === '?course_id') {
+ return encodeURIComponent(COURSE_ID);
+ }
+ });
// Attempt to register
- submitForm( true );
+ submitForm(true);
// Verify that the client sent the course ID for analytics
- expectedData = {course_id: COURSE_ID};
- $.extend(expectedData, USER_DATA);
+ expectedData = {course_id: COURSE_ID};
+ $.extend(expectedData, USER_DATA);
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( expectedData )
+ $.param(expectedData)
);
- });
+ });
- it('displays third-party auth registration buttons', function() {
- createRegisterView(this);
+ it('displays third-party auth registration buttons', function() {
+ createRegisterView(this);
// Verify that Google and Facebook registration buttons are displayed
- expect($('.button-oa2-google-oauth2')).toBeVisible();
- expect($('.button-oa2-facebook')).toBeVisible();
- });
+ expect($('.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.button-oa2-facebook')).toBeVisible();
+ });
- it('validates registration form fields', function() {
- createRegisterView(this);
+ it('validates registration form fields', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Verify that validation of form fields occurred
- expect(view.validate).toHaveBeenCalledWith($('#register-email')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-name')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-username')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-password')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-name')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-username')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-password')[0]);
// Verify that no submission errors are visible
- expect(view.$errors).toHaveClass('hidden');
+ expect(view.$errors).toHaveClass('hidden');
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
- });
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
- it('displays registration form validation errors', function() {
- createRegisterView(this);
+ it('displays registration form validation errors', function() {
+ createRegisterView(this);
// Submit the form, with failed validation
- submitForm(false);
+ submitForm(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// Expect that auth complete is NOT triggered
- expect(authComplete).toBe(false);
+ expect(authComplete).toBe(false);
// Form button should be re-enabled on error.
- expect(view.$submitButton).not.toHaveAttr('disabled');
- });
+ expect(view.$submitButton).not.toHaveAttr('disabled');
+ });
- it('displays an error if the server returns an error while registering', function() {
- createRegisterView(this);
+ it('displays an error if the server returns an error while registering', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed and that auth complete is NOT triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
// If we try again and succeed, the error should go away
- submitForm();
+ submitForm();
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden and that auth complete is triggered
- expect(view.$errors).toHaveClass('hidden');
- expect(authComplete).toBe(true);
+ expect(view.$errors).toHaveClass('hidden');
+ expect(authComplete).toBe(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/shoppingcart_spec.js b/lms/static/js/spec/student_account/shoppingcart_spec.js
index f786bb96b3..69ed04ba7c 100644
--- a/lms/static/js/spec/student_account/shoppingcart_spec.js
+++ b/lms/static/js/spec/student_account/shoppingcart_spec.js
@@ -2,11 +2,10 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
function(AjaxHelpers, ShoppingCartInterface) {
'use strict';
- describe( 'ShoppingCartInterface', function() {
-
- var COURSE_KEY = "edX/DemoX/Fall",
- ADD_COURSE_URL = "/shoppingcart/add/course/edX/DemoX/Fall/",
- FORWARD_URL = "/shoppingcart/";
+ describe('ShoppingCartInterface', function() {
+ var COURSE_KEY = 'edX/DemoX/Fall',
+ ADD_COURSE_URL = '/shoppingcart/add/course/edX/DemoX/Fall/',
+ FORWARD_URL = '/shoppingcart/';
beforeEach(function() {
// Mock the redirect call
@@ -15,33 +14,33 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
it('adds a course to the cart', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to add a course to the cart
- ShoppingCartInterface.addCourseToCart( COURSE_KEY );
+ ShoppingCartInterface.addCourseToCart(COURSE_KEY);
// Expect that the correct request was made to the server
- AjaxHelpers.expectRequest( requests, 'POST', ADD_COURSE_URL );
+ AjaxHelpers.expectRequest(requests, 'POST', ADD_COURSE_URL);
// Simulate a successful response from the server
- AjaxHelpers.respondWithJson( requests, {} );
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the user was redirected to the shopping cart
- expect( ShoppingCartInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(ShoppingCartInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user on a server error', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to add a course to the cart
- ShoppingCartInterface.addCourseToCart( COURSE_KEY );
+ ShoppingCartInterface.addCourseToCart(COURSE_KEY);
// Simulate an error response from the server
- AjaxHelpers.respondWithError( requests );
+ AjaxHelpers.respondWithError(requests);
// Expect that the user was redirected to the shopping cart
- expect( ShoppingCartInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(ShoppingCartInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
});
}
diff --git a/lms/static/js/spec/student_profile/badge_list_container_spec.js b/lms/static/js/spec/student_profile/badge_list_container_spec.js
index bd4592b2ff..63bd272059 100644
--- a/lms/static/js/spec/student_profile/badge_list_container_spec.js
+++ b/lms/static/js/spec/student_profile/badge_list_container_spec.js
@@ -1,17 +1,16 @@
define([
- 'backbone',
- 'jquery',
- 'underscore',
- 'URI',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'edx-ui-toolkit/js/pagination/paging-collection',
- 'js/spec/student_profile/helpers',
- 'js/student_profile/views/badge_list_container'
- ],
+ 'backbone',
+ 'jquery',
+ 'underscore',
+ 'URI',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'edx-ui-toolkit/js/pagination/paging-collection',
+ 'js/spec/student_profile/helpers',
+ 'js/student_profile/views/badge_list_container'
+],
function(Backbone, $, _, URI, AjaxHelpers, PagingCollection, LearnerProfileHelpers, BadgeListContainer) {
'use strict';
- describe('edx.user.BadgeListContainer', function () {
-
+ describe('edx.user.BadgeListContainer', function() {
var view, requests;
var createView = function(requests, pageNum, badgeListObject) {
@@ -23,7 +22,7 @@ define([
var badgeCollection = new BadgeCollection();
badgeCollection.url = '/api/badges/v1/assertions/user/staff/';
var models = [];
- _.each(_.range(badgeListObject.count), function (idx) {
+ _.each(_.range(badgeListObject.count), function(idx) {
models.push(LearnerProfileHelpers.makeBadge(idx));
});
badgeListObject.results = models;
@@ -40,11 +39,11 @@ define([
return badgeListContainer;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
- it('displays all badges', function () {
+ it('displays all badges', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 1, {
count: 30,
@@ -59,7 +58,7 @@ define([
expect(badges.length).toBe(30);
});
- it('displays placeholder on last page', function () {
+ it('displays placeholder on last page', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 3, {
count: 30,
@@ -74,7 +73,7 @@ define([
expect(placeholder.length).toBe(1);
});
- it('does not display placeholder on first page', function () {
+ it('does not display placeholder on first page', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 1, {
count: 30,
@@ -88,7 +87,6 @@ define([
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(0);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/badge_list_view_spec.js b/lms/static/js/spec/student_profile/badge_list_view_spec.js
index b9a088f3fe..f097100186 100644
--- a/lms/static/js/spec/student_profile/badge_list_view_spec.js
+++ b/lms/static/js/spec/student_profile/badge_list_view_spec.js
@@ -1,29 +1,28 @@
define([
- 'backbone',
- 'jquery',
- 'underscore',
- 'edx-ui-toolkit/js/pagination/paging-collection',
- 'js/spec/student_profile/helpers',
- 'js/student_profile/views/badge_list_view'
- ],
- function (Backbone, $, _, PagingCollection, LearnerProfileHelpers, BadgeListView) {
- "use strict";
- describe("edx.user.BadgeListView", function () {
-
+ 'backbone',
+ 'jquery',
+ 'underscore',
+ 'edx-ui-toolkit/js/pagination/paging-collection',
+ 'js/spec/student_profile/helpers',
+ 'js/student_profile/views/badge_list_view'
+],
+ function(Backbone, $, _, PagingCollection, LearnerProfileHelpers, BadgeListView) {
+ 'use strict';
+ describe('edx.user.BadgeListView', function() {
var view;
- var createView = function (badges, pages, page, hasNextPage) {
+ var createView = function(badges, pages, page, hasNextPage) {
var badgeCollection = new PagingCollection();
- badgeCollection.url = "/api/badges/v1/assertions/user/staff/";
+ badgeCollection.url = '/api/badges/v1/assertions/user/staff/';
var models = [];
- _.each(badges, function (element) {
+ _.each(badges, function(element) {
models.push(new Backbone.Model(element));
});
badgeCollection.models = models;
badgeCollection.length = badges.length;
badgeCollection.currentPage = page;
badgeCollection.totalPages = pages;
- badgeCollection.hasNextPage = function () {
+ badgeCollection.hasNextPage = function() {
return hasNextPage;
};
var badge_list = new BadgeListView({
@@ -33,35 +32,35 @@ define([
return badge_list;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
-
- it("there is a single row if there is only one badge", function () {
+
+ it('there is a single row if there is only one badge', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 1, 1, false);
view.render();
var rows = view.$el.find('div.row');
expect(rows.length).toBe(1);
});
- it("accomplishments placeholder is visible on a last page", function () {
+ it('accomplishments placeholder is visible on a last page', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 2, 2, false);
view.render();
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(1);
});
- it("accomplishments placeholder to be not visible on a first page", function () {
+ it('accomplishments placeholder to be not visible on a first page', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 1, 2, true);
view.render();
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(0);
});
- it("badges are in two columns (checked by counting rows for a known number of badges)", function () {
+ it('badges are in two columns (checked by counting rows for a known number of badges)', function() {
var badges = [];
- _.each(_.range(4), function (item) {
- badges.push(LearnerProfileHelpers.makeBadge(item));
+ _.each(_.range(4), function(item) {
+ badges.push(LearnerProfileHelpers.makeBadge(item));
});
view = createView(badges, 1, 2, true);
view.render();
@@ -70,7 +69,6 @@ define([
var rows = view.$el.find('div.row');
expect(rows.length).toBe(2);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/badge_view_spec.js b/lms/static/js/spec/student_profile/badge_view_spec.js
index d40258fcd7..35ad00ea26 100644
--- a/lms/static/js/spec/student_profile/badge_view_spec.js
+++ b/lms/static/js/spec/student_profile/badge_view_spec.js
@@ -2,13 +2,12 @@ define(['backbone', 'jquery', 'underscore',
'js/spec/student_profile/helpers',
'js/student_profile/views/badge_view'
],
- function (Backbone, $, _, LearnerProfileHelpers, BadgeView) {
- "use strict";
- describe("edx.user.BadgeView", function () {
-
+ function(Backbone, $, _, LearnerProfileHelpers, BadgeView) {
+ 'use strict';
+ describe('edx.user.BadgeView', function() {
var view, badge;
- var createView = function (ownProfile) {
+ var createView = function(ownProfile) {
badge = LearnerProfileHelpers.makeBadge(1);
var options = {
'model': new Backbone.Model(badge),
@@ -23,26 +22,26 @@ define(['backbone', 'jquery', 'underscore',
return view;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
$('.badges-modal').remove();
});
- it("profile of other has no share button", function () {
+ it('profile of other has no share button', function() {
view = createView(false);
expect(view.context.ownProfile).toBeFalsy();
expect(view.$el.find('button.share-button').length).toBe(0);
});
- it("own profile has share button", function () {
+ it('own profile has share button', function() {
view = createView(true);
expect(view.context.ownProfile).toBeTruthy();
expect(view.$el.find('button.share-button').length).toBe(1);
});
- it("click on share button calls createModal function", function () {
+ it('click on share button calls createModal function', function() {
view = createView(true);
- spyOn(view, "createModal");
+ spyOn(view, 'createModal');
view.delegateEvents();
expect(view.context.ownProfile).toBeTruthy();
var shareButton = view.$el.find('button.share-button');
@@ -52,53 +51,52 @@ define(['backbone', 'jquery', 'underscore',
expect(view.createModal).toHaveBeenCalled();
});
- it("click on share button calls shows the dialog", function (done) {
+ it('click on share button calls shows the dialog', function(done) {
view = createView(true);
expect(view.context.ownProfile).toBeTruthy();
var shareButton = view.$el.find('button.share-button');
expect(shareButton.length).toBe(1);
var modalElement = $('.badges-modal');
expect(modalElement.length).toBe(0);
- expect(modalElement.is(":visible")).toBeFalsy();
+ expect(modalElement.is(':visible')).toBeFalsy();
shareButton.click();
// Note: this element should have appeared in the dom during: shareButton.click();
modalElement = $('.badges-modal');
- jasmine.waitUntil(function () {
- return modalElement.is(":visible");
+ jasmine.waitUntil(function() {
+ return modalElement.is(':visible');
}).always(done);
});
- var testBadgeNameIsDisplayed = function (ownProfile) {
+ var testBadgeNameIsDisplayed = function(ownProfile) {
view = createView(ownProfile);
- var badgeDiv = view.$el.find(".badge-name");
+ var badgeDiv = view.$el.find('.badge-name');
expect(badgeDiv.length).toBeTruthy();
expect(badgeDiv.is(':visible')).toBe(true);
expect(_.count(badgeDiv.html(), badge.badge_class.display_name)).toBeTruthy();
};
- it("test badge name is displayed for own profile", function () {
+ it('test badge name is displayed for own profile', function() {
testBadgeNameIsDisplayed(true);
});
- it("test badge name is displayed for other profile", function () {
+ it('test badge name is displayed for other profile', function() {
testBadgeNameIsDisplayed(false);
});
- var testBadgeIconIsDisplayed = function (ownProfile) {
+ var testBadgeIconIsDisplayed = function(ownProfile) {
view = createView(ownProfile);
- var badgeImg = view.$el.find("img.badge");
+ var badgeImg = view.$el.find('img.badge');
expect(badgeImg.length).toBe(1);
expect(badgeImg.attr('src')).toEqual(badge.image_url);
};
- it("test badge icon is displayed for own profile", function () {
+ it('test badge icon is displayed for own profile', function() {
testBadgeIconIsDisplayed(true);
});
- it("test badge icon is displayed for other profile", function () {
+ it('test badge icon is displayed for other profile', function() {
testBadgeIconIsDisplayed(false);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/helpers.js b/lms/static/js/spec/student_profile/helpers.js
index 989cfbafe2..e334923541 100644
--- a/lms/static/js/spec/student_profile/helpers.js
+++ b/lms/static/js/spec/student_profile/helpers.js
@@ -14,11 +14,9 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
expect($($element.find('.image-frame')[0]).attr('src')).toBe(view.imageUrl());
} else if (view.fieldValue()) {
expect(view.fieldValue()).toBe(view.modelValue());
-
} else if ('optionForValue' in view) {
expect($($element.find('.u-field-value .u-field-value-readonly')[0]).text()).toBe(view.displayValue(view.modelValue()));
-
- }else {
+ } else {
expect($($element.find('.u-field-value .u-field-value-readonly')[0]).text()).toBe(view.modelValue());
}
} else {
@@ -27,7 +25,6 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectProfilePrivacyFieldTobeRendered = function(learnerProfileView, othersProfile) {
-
var accountPrivacyElement = learnerProfileView.$('.wrapper-profile-field-account-privacy');
var privacyFieldElement = $(accountPrivacyElement).find('.u-field');
@@ -40,14 +37,13 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectSectionOneTobeRendered = function(learnerProfileView) {
-
var sectionOneFieldElements = $(learnerProfileView.$('.wrapper-profile-section-one')).find('.u-field');
expect(sectionOneFieldElements.length).toBe(4);
expectProfileElementContainsField(sectionOneFieldElements[0], learnerProfileView.options.profileImageFieldView);
expectProfileElementContainsField(sectionOneFieldElements[1], learnerProfileView.options.usernameFieldView);
- _.each(_.rest(sectionOneFieldElements, 2) , function (sectionFieldElement, fieldIndex) {
+ _.each(_.rest(sectionOneFieldElements, 2), function(sectionFieldElement, fieldIndex) {
expectProfileElementContainsField(
sectionFieldElement,
learnerProfileView.options.sectionOneFieldViews[fieldIndex]
@@ -56,13 +52,12 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectSectionTwoTobeRendered = function(learnerProfileView) {
-
var sectionTwoElement = learnerProfileView.$('.wrapper-profile-section-two');
var sectionTwoFieldElements = $(sectionTwoElement).find('.u-field');
expect(sectionTwoFieldElements.length).toBe(learnerProfileView.options.sectionTwoFieldViews.length);
- _.each(sectionTwoFieldElements, function (sectionFieldElement, fieldIndex) {
+ _.each(sectionTwoFieldElements, function(sectionFieldElement, fieldIndex) {
expectProfileElementContainsField(
sectionFieldElement,
learnerProfileView.options.sectionTwoFieldViews[fieldIndex]
@@ -70,13 +65,13 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
});
};
- var expectProfileSectionsAndFieldsToBeRendered = function (learnerProfileView, othersProfile) {
+ var expectProfileSectionsAndFieldsToBeRendered = function(learnerProfileView, othersProfile) {
expectProfilePrivacyFieldTobeRendered(learnerProfileView, othersProfile);
expectSectionOneTobeRendered(learnerProfileView);
expectSectionTwoTobeRendered(learnerProfileView);
};
- var expectLimitedProfileSectionsAndFieldsToBeRendered = function (learnerProfileView, othersProfile) {
+ var expectLimitedProfileSectionsAndFieldsToBeRendered = function(learnerProfileView, othersProfile) {
expectProfilePrivacyFieldTobeRendered(learnerProfileView, othersProfile);
var sectionOneFieldElements = $(learnerProfileView.$('.wrapper-profile-section-one')).find('.u-field');
@@ -140,16 +135,16 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var expectPage = function(learnerProfileView, pageData) {
var badgeListContainer = learnerProfileView.$el.find('#tabpanel-accomplishments');
var index = badgeListContainer.find('span.search-count').text().trim();
- expect(index).toBe("Showing " + (pageData.start + 1) + "-" + (pageData.start + pageData.results.length) +
- " out of " + pageData.count + " total");
- expect(badgeListContainer.find('.current-page').text()).toBe("" + pageData.current_page);
+ expect(index).toBe('Showing ' + (pageData.start + 1) + '-' + (pageData.start + pageData.results.length) +
+ ' out of ' + pageData.count + ' total');
+ expect(badgeListContainer.find('.current-page').text()).toBe('' + pageData.current_page);
_.each(pageData.results, function(badge) {
- expect($(".badge-display:contains(" + badge.badge_class.display_name + ")").length).toBe(1);
+ expect($('.badge-display:contains(' + badge.badge_class.display_name + ')').length).toBe(1);
});
};
var expectBadgeLoadingErrorIsRendered = function(learnerProfileView) {
- var errorMessage = learnerProfileView.$el.find(".badge-set-display").text();
+ var errorMessage = learnerProfileView.$el.find('.badge-set-display').text();
expect(errorMessage).toBe(
'Your request could not be completed. Reload the page and try again. If the issue persists, click the ' +
'Help tab to report the problem.'
@@ -166,7 +161,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var firstPageBadges = {
count: 30,
previous: null,
- next: "/arbitrary/url",
+ next: '/arbitrary/url',
num_pages: 3,
start: 0,
current_page: 1,
@@ -175,8 +170,8 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var secondPageBadges = {
count: 30,
- previous: "/arbitrary/url",
- next: "/arbitrary/url",
+ previous: '/arbitrary/url',
+ next: '/arbitrary/url',
num_pages: 3,
start: 10,
current_page: 2,
@@ -185,7 +180,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var thirdPageBadges = {
count: 30,
- previous: "/arbitrary/url",
+ previous: '/arbitrary/url',
num_pages: 3,
next: null,
start: 20,
@@ -193,20 +188,20 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
results: []
};
- function makeBadge (num) {
+ function makeBadge(num) {
return {
- "badge_class": {
- "slug": "test_slug_" + num,
- "issuing_component": "test_component",
- "display_name": "Test Badge " + num,
- "course_id": null,
- "description": "Yay! It's a test badge.",
- "criteria": "https://example.com/syllabus",
- "image_url": "http://localhost:8000/media/badge_classes/test_lMB9bRw.png"
+ 'badge_class': {
+ 'slug': 'test_slug_' + num,
+ 'issuing_component': 'test_component',
+ 'display_name': 'Test Badge ' + num,
+ 'course_id': null,
+ 'description': "Yay! It's a test badge.",
+ 'criteria': 'https://example.com/syllabus',
+ 'image_url': 'http://localhost:8000/media/badge_classes/test_lMB9bRw.png'
},
- "image_url": "http://example.com/image.png",
- "assertion_url": "http://example.com/example.json",
- "created_at": "2015-12-03T16:25:57.676113Z"
+ 'image_url': 'http://example.com/image.png',
+ 'assertion_url': 'http://example.com/example.json',
+ 'created_at': '2015-12-03T16:25:57.676113Z'
};
}
@@ -223,10 +218,10 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
});
var emptyBadges = {
- "count": 0,
- "previous": null,
- "num_pages": 1,
- "results": []
+ 'count': 0,
+ 'previous': null,
+ 'num_pages': 1,
+ 'results': []
};
return {
diff --git a/lms/static/js/spec/student_profile/learner_profile_factory_spec.js b/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
index 961d818f05..7bc6b23e90 100644
--- a/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
@@ -10,19 +10,18 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
'js/student_profile/views/learner_profile_factory',
'js/views/message_banner'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers, FieldViews,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers, FieldViews,
UserAccountModel, UserPreferencesModel, LearnerProfileView, LearnerProfileFields, LearnerProfilePage) {
'use strict';
- describe("edx.user.LearnerProfileFactory", function () {
-
+ describe('edx.user.LearnerProfileFactory', function() {
var requests;
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
});
- afterEach(function () {
+ afterEach(function() {
Backbone.history.stop();
});
@@ -48,7 +47,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
};
- it("renders the full profile for a user", function() {
+ it('renders the full profile for a user', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true),
@@ -60,7 +59,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("renders the limited profile for undefined 'year_of_birth'", function() {
-
var context = createProfilePage(true, {year_of_birth: '', requires_parental_consent: true}),
learnerProfileView = context.learnerProfileView;
@@ -68,7 +66,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("doesn't show the mode toggle if badges are disabled", function() {
-
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: false}),
@@ -80,7 +77,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("doesn't show the mode toggle if badges fail to fetch", function() {
-
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: false}),
@@ -91,8 +87,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("renders the mode toggle if there are badges", function() {
-
+ it('renders the mode toggle if there are badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -105,8 +100,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectTabbedViewToBeShown(tabbedView);
});
- it("renders the mode toggle if badges enabled but none exist", function() {
-
+ it('renders the mode toggle if badges enabled but none exist', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -119,8 +113,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectTabbedViewToBeShown(tabbedView);
});
- it("displays the badges when the accomplishments toggle is selected", function () {
-
+ it('displays the badges when the accomplishments toggle is selected', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -138,8 +131,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("displays a placeholder on the last page of badges", function () {
-
+ it('displays a placeholder on the last page of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -157,8 +149,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("displays a placeholder when the accomplishments toggle is selected and no badges exist", function () {
-
+ it('displays a placeholder when the accomplishments toggle is selected and no badges exist', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -176,7 +167,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("shows a paginated list of badges", function() {
+ it('shows a paginated list of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -192,7 +183,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectPage(learnerProfileView, LearnerProfileHelpers.firstPageBadges);
});
- it("allows forward and backward navigation of badges", function () {
+ it('allows forward and backward navigation of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -226,8 +217,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
- it("renders the limited profile for under 13 users", function() {
-
+ it('renders the limited profile for under 13 users', function() {
var context = createProfilePage(
true,
{year_of_birth: new Date().getFullYear() - 10, requires_parental_consent: true}
diff --git a/lms/static/js/spec/student_profile/learner_profile_fields_spec.js b/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
index 712f838d5e..013630e351 100644
--- a/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
@@ -8,17 +8,16 @@ define(['backbone',
'js/student_profile/views/learner_profile_fields',
'js/views/message_banner'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, UserAccountModel, LearnerProfileFields,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, UserAccountModel, LearnerProfileFields,
MessageBannerView) {
'use strict';
- describe("edx.user.LearnerProfileFields", function () {
-
+ describe('edx.user.LearnerProfileFields', function() {
var MOCK_YEAR_OF_BIRTH = 1989;
var MOCK_IMAGE_MAX_BYTES = 64;
var MOCK_IMAGE_MIN_BYTES = 16;
- var createImageView = function (options) {
+ var createImageView = function(options) {
var yearOfBirth = _.isUndefined(options.yearOfBirth) ? MOCK_YEAR_OF_BIRTH : options.yearOfBirth;
var imageMaxBytes = _.isUndefined(options.imageMaxBytes) ? MOCK_IMAGE_MAX_BYTES : options.imageMaxBytes;
var imageMinBytes = _.isUndefined(options.imageMinBytes) ? MOCK_IMAGE_MIN_BYTES : options.imageMinBytes;
@@ -41,7 +40,7 @@ define(['backbone',
return new LearnerProfileFields.ProfileImageFieldView({
model: accountSettingsModel,
- valueAttribute: "profile_image",
+ valueAttribute: 'profile_image',
editable: options.ownProfile,
messageView: messageView,
imageMaxBytes: imageMaxBytes,
@@ -51,27 +50,27 @@ define(['backbone',
});
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
TemplateHelpers.installTemplate('templates/student_profile/learner_profile');
TemplateHelpers.installTemplate('templates/fields/field_image');
- TemplateHelpers.installTemplate("templates/fields/message_banner");
+ TemplateHelpers.installTemplate('templates/fields/message_banner');
});
- afterEach(function () {
+ afterEach(function() {
// image_field.js's window.onBeforeUnload breaks Karma in Chrome, clean it up after each test
$(window).off('beforeunload');
});
- var createFakeImageFile = function (size) {
+ var createFakeImageFile = function(size) {
var fileFakeData = 'i63ljc6giwoskyb9x5sw0169bdcmcxr3cdz8boqv0lik971972cmd6yknvcxr5sw0nvc169bdcmcxsdf';
return new Blob(
- [ fileFakeData.substr(0, size) ],
- { type: 'image/jpg' }
+ [fileFakeData.substr(0, size)],
+ {type: 'image/jpg'}
);
};
- var initializeUploader = function (view) {
+ var initializeUploader = function(view) {
view.$('.upload-button-input').fileupload({
url: Helpers.IMAGE_UPLOAD_API_URL,
type: 'POST',
@@ -81,24 +80,22 @@ define(['backbone',
});
};
- describe("ProfileImageFieldView", function () {
-
- var verifyImageUploadButtonMessage = function (view, inProgress) {
+ describe('ProfileImageFieldView', function() {
+ var verifyImageUploadButtonMessage = function(view, inProgress) {
var iconName = inProgress ? 'fa-spinner' : 'fa-camera';
var message = inProgress ? view.titleUploading : view.uploadButtonTitle();
expect(view.$('.upload-button-icon span').attr('class')).toContain(iconName);
expect(view.$('.upload-button-title').text().trim()).toBe(message);
};
- var verifyImageRemoveButtonMessage = function (view, inProgress) {
+ var verifyImageRemoveButtonMessage = function(view, inProgress) {
var iconName = inProgress ? 'fa-spinner' : 'fa-remove';
var message = inProgress ? view.titleRemoving : view.removeButtonTitle();
expect(view.$('.remove-button-icon span').attr('class')).toContain(iconName);
expect(view.$('.remove-button-title').text().trim()).toBe(message);
};
- it("can upload profile image", function() {
-
+ it('can upload profile image', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -143,8 +140,7 @@ define(['backbone',
verifyImageUploadButtonMessage(imageView, false);
});
- it("can remove profile image", function() {
-
+ it('can remove profile image', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -177,7 +173,6 @@ define(['backbone',
});
it("can't remove default profile image", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -193,7 +188,6 @@ define(['backbone',
});
it("can't upload image having size greater than max size", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -221,7 +215,6 @@ define(['backbone',
});
it("can't upload and remove image if parental consent required", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false, yearOfBirth: ''});
imageView.render();
@@ -239,7 +232,6 @@ define(['backbone',
});
it("can't upload and remove image on others profile", function() {
-
var imageView = createImageView({ownProfile: false});
imageView.render();
@@ -256,7 +248,7 @@ define(['backbone',
expect(imageView.clickedRemoveButton).not.toHaveBeenCalled();
});
- it("shows message if we try to navigate away during image upload/remove", function() {
+ it('shows message if we try to navigate away during image upload/remove', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
spyOn(imageView, 'onBeforeUnload');
imageView.render();
@@ -274,7 +266,7 @@ define(['backbone',
expect(imageView.onBeforeUnload).toHaveBeenCalled();
});
- it("shows error message for HTTP 500", function() {
+ it('shows error message for HTTP 500', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
diff --git a/lms/static/js/spec/student_profile/learner_profile_view_spec.js b/lms/static/js/spec/student_profile/learner_profile_view_spec.js
index f455011cc4..518a27c404 100644
--- a/lms/static/js/spec/student_profile/learner_profile_view_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_view_spec.js
@@ -15,15 +15,13 @@ define(['backbone',
'js/student_account/views/account_settings_fields',
'js/views/message_banner'
],
- function (Backbone, $, _, PagingCollection, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers,
+ function(Backbone, $, _, PagingCollection, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers,
FieldViews, UserAccountModel, AccountPreferencesModel, LearnerProfileFields, LearnerProfileView,
BadgeListContainer, AccountSettingsFieldViews, MessageBannerView) {
'use strict';
- describe("edx.user.LearnerProfileView", function () {
-
- var createLearnerProfileView = function (ownProfile, accountPrivacy, profileIsPublic) {
-
+ describe('edx.user.LearnerProfileView', function() {
+ var createLearnerProfileView = function(ownProfile, accountPrivacy, profileIsPublic) {
var accountSettingsModel = new UserAccountModel();
accountSettingsModel.set(Helpers.createAccountSettingsData());
accountSettingsModel.set({'profile_is_public': profileIsPublic});
@@ -42,7 +40,7 @@ define(['backbone',
editable: 'always',
showMessages: false,
title: 'edX learners can see my:',
- valueAttribute: "account_privacy",
+ valueAttribute: 'account_privacy',
options: [
['all_users', 'Full Profile'],
['private', 'Limited Profile']
@@ -57,7 +55,7 @@ define(['backbone',
var profileImageFieldView = new LearnerProfileFields.ProfileImageFieldView({
model: accountSettingsModel,
- valueAttribute: "profile_image",
+ valueAttribute: 'profile_image',
editable: editable,
messageView: messageView,
imageMaxBytes: Helpers.IMAGE_MAX_BYTES,
@@ -67,9 +65,9 @@ define(['backbone',
});
var usernameFieldView = new FieldViews.ReadonlyFieldView({
- model: accountSettingsModel,
- valueAttribute: "username",
- helpMessage: ""
+ model: accountSettingsModel,
+ valueAttribute: 'username',
+ helpMessage: ''
});
var sectionOneFieldViews = [
@@ -80,7 +78,7 @@ define(['backbone',
showMessages: false,
iconName: 'fa-map-marker',
placeholderValue: '',
- valueAttribute: "country",
+ valueAttribute: 'country',
options: Helpers.FIELD_OPTIONS,
helpMessage: ''
}),
@@ -92,7 +90,7 @@ define(['backbone',
showMessages: false,
iconName: 'fa-comment',
placeholderValue: 'Add language',
- valueAttribute: "language_proficiencies",
+ valueAttribute: 'language_proficiencies',
options: Helpers.FIELD_OPTIONS,
helpMessage: ''
})
@@ -104,9 +102,9 @@ define(['backbone',
editable: editable,
showMessages: false,
title: 'About me',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
"what your interests are, why you're taking courses on edX, or what you hope to learn.",
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
messagePosition: 'header'
})
@@ -137,16 +135,15 @@ define(['backbone',
});
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
});
- afterEach(function () {
+ afterEach(function() {
Backbone.history.stop();
});
- it("shows loading error correctly", function() {
-
+ it('shows loading error correctly', function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users');
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -158,8 +155,7 @@ define(['backbone',
Helpers.expectLoadingErrorIsVisible(learnerProfileView, true);
});
- it("renders all fields as expected for self with full access", function() {
-
+ it('renders all fields as expected for self with full access', function() {
var learnerProfileView = createLearnerProfileView(true, 'all_users', true);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -171,8 +167,7 @@ define(['backbone',
LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerProfileView);
});
- it("renders all fields as expected for self with limited access", function() {
-
+ it('renders all fields as expected for self with limited access', function() {
var learnerProfileView = createLearnerProfileView(true, 'private', false);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -184,8 +179,7 @@ define(['backbone',
LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView);
});
- it("renders the fields as expected for others with full access", function() {
-
+ it('renders the fields as expected for others with full access', function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users', true);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -197,8 +191,7 @@ define(['backbone',
LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerProfileView, true);
});
- it("renders the fields as expected for others with limited access", function() {
-
+ it('renders the fields as expected for others with limited access', function() {
var learnerProfileView = createLearnerProfileView(false, 'private', false);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -210,13 +203,13 @@ define(['backbone',
LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView, true);
});
- it("renders an error if the badges can't be fetched", function () {
+ it("renders an error if the badges can't be fetched", function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users', true);
learnerProfileView.options.accountSettingsModel.set({'accomplishments_shared': true});
var requests = AjaxHelpers.requests(this);
learnerProfileView.render();
-
+
LearnerProfileHelpers.breakBadgeLoading(learnerProfileView, requests);
LearnerProfileHelpers.expectBadgeLoadingErrorIsRendered(learnerProfileView);
});
diff --git a/lms/static/js/spec/student_profile/section_two_tab_spec.js b/lms/static/js/spec/student_profile/section_two_tab_spec.js
index a0236b885a..1180bbc3c4 100644
--- a/lms/static/js/spec/student_profile/section_two_tab_spec.js
+++ b/lms/static/js/spec/student_profile/section_two_tab_spec.js
@@ -4,12 +4,10 @@ define(['backbone', 'jquery', 'underscore',
'js/views/fields',
'js/student_account/models/user_account_model'
],
- function (Backbone, $, _, Helpers, SectionTwoTabView, FieldViews, UserAccountModel) {
- "use strict";
- describe("edx.user.SectionTwoTab", function () {
-
- var createSectionTwoView = function (ownProfile, profileIsPublic) {
-
+ function(Backbone, $, _, Helpers, SectionTwoTabView, FieldViews, UserAccountModel) {
+ 'use strict';
+ describe('edx.user.SectionTwoTab', function() {
+ var createSectionTwoView = function(ownProfile, profileIsPublic) {
var accountSettingsModel = new UserAccountModel();
accountSettingsModel.set(Helpers.createAccountSettingsData());
accountSettingsModel.set({'profile_is_public': profileIsPublic});
@@ -23,9 +21,9 @@ define(['backbone', 'jquery', 'underscore',
editable: editable,
showMessages: false,
title: 'About me',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
"what your interests are, why you're taking courses on edX, or what you hope to learn.",
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
messagePosition: 'header'
})
@@ -33,32 +31,32 @@ define(['backbone', 'jquery', 'underscore',
return new SectionTwoTabView({
viewList: sectionTwoFieldViews,
- showFullProfile: function(){
+ showFullProfile: function() {
return profileIsPublic;
},
ownProfile: ownProfile
});
};
- it("full profile displayed for public profile", function () {
+ it('full profile displayed for public profile', function() {
var view = createSectionTwoView(false, true);
view.render();
var bio = view.$el.find('.u-field-bio');
expect(bio.length).toBe(1);
});
-
- it("profile field parts are actually rendered for public profile", function () {
+
+ it('profile field parts are actually rendered for public profile', function() {
var view = createSectionTwoView(false, true);
- _.each(view.options.viewList, function (fieldView) {
- spyOn(fieldView, "render").and.callThrough();
+ _.each(view.options.viewList, function(fieldView) {
+ spyOn(fieldView, 'render').and.callThrough();
});
view.render();
- _.each(view.options.viewList, function (fieldView) {
+ _.each(view.options.viewList, function(fieldView) {
expect(fieldView.render).toHaveBeenCalled();
});
});
- var testPrivateProfile = function (ownProfile, msg_string) {
+ var testPrivateProfile = function(ownProfile, msg_string) {
var view = createSectionTwoView(ownProfile, false);
view.render();
var bio = view.$el.find('.u-field-bio');
@@ -68,45 +66,44 @@ define(['backbone', 'jquery', 'underscore',
expect(_.count(msg.html(), msg_string)).toBeTruthy();
};
- it("no profile when profile is private for other people", function () {
- testPrivateProfile(false, "This learner is currently sharing a limited profile");
+ it('no profile when profile is private for other people', function() {
+ testPrivateProfile(false, 'This learner is currently sharing a limited profile');
});
- it("no profile when profile is private for the user herself", function () {
- testPrivateProfile(true, "You are currently sharing a limited profile");
+ it('no profile when profile is private for the user herself', function() {
+ testPrivateProfile(true, 'You are currently sharing a limited profile');
});
- var testProfilePrivatePartsDoNotRender = function (ownProfile) {
- var view = createSectionTwoView(ownProfile, false);
- _.each(view.options.viewList, function (fieldView) {
- spyOn(fieldView, "render");
+ var testProfilePrivatePartsDoNotRender = function(ownProfile) {
+ var view = createSectionTwoView(ownProfile, false);
+ _.each(view.options.viewList, function(fieldView) {
+ spyOn(fieldView, 'render');
});
view.render();
- _.each(view.options.viewList, function (fieldView) {
+ _.each(view.options.viewList, function(fieldView) {
expect(fieldView.render).not.toHaveBeenCalled();
});
};
- it("profile field parts are not rendered for private profile for owner", function () {
- testProfilePrivatePartsDoNotRender(true);
+ it('profile field parts are not rendered for private profile for owner', function() {
+ testProfilePrivatePartsDoNotRender(true);
});
- it("profile field parts are not rendered for private profile for other people", function () {
- testProfilePrivatePartsDoNotRender(false);
+ it('profile field parts are not rendered for private profile for other people', function() {
+ testProfilePrivatePartsDoNotRender(false);
});
- it("does not allow fields to be edited when visiting a profile for other people", function () {
+ it('does not allow fields to be edited when visiting a profile for other people', function() {
var view = createSectionTwoView(false, true);
var bio = view.options.viewList[0];
- expect(bio.editable).toBe("never");
+ expect(bio.editable).toBe('never');
});
- it("allows fields to be edited when visiting one's own profile", function () {
+ it("allows fields to be edited when visiting one's own profile", function() {
var view = createSectionTwoView(true, true);
var bio = view.options.viewList[0];
- expect(bio.editable).toBe("toggle");
+ expect(bio.editable).toBe('toggle');
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/share_modal_view_spec.js b/lms/static/js/spec/student_profile/share_modal_view_spec.js
index a86bfe4916..68e21b8b5e 100644
--- a/lms/static/js/spec/student_profile/share_modal_view_spec.js
+++ b/lms/static/js/spec/student_profile/share_modal_view_spec.js
@@ -4,14 +4,14 @@ define(['backbone', 'jquery', 'underscore', 'moment',
'js/student_profile/views/share_modal_view',
'jquery.simulate'
],
- function (Backbone, $, _, Moment, Helpers, LearnerProfileHelpers, ShareModalView) {
- "use strict";
- describe("edx.user.ShareModalView", function () {
+ function(Backbone, $, _, Moment, Helpers, LearnerProfileHelpers, ShareModalView) {
+ 'use strict';
+ describe('edx.user.ShareModalView', function() {
var keys = $.simulate.keyCode;
var view;
- var createModalView = function () {
+ var createModalView = function() {
var badge = LearnerProfileHelpers.makeBadge(1);
var context = _.extend(badge, {
'created': new Moment(badge.created),
@@ -20,11 +20,11 @@ define(['backbone', 'jquery', 'underscore', 'moment',
});
return new ShareModalView({
model: new Backbone.Model(context),
- shareButton: $("
")
+ shareButton: $('
')
});
};
- beforeEach(function () {
+ beforeEach(function() {
view = createModalView();
// Attach view to document, otherwise click won't work
view.render();
@@ -33,28 +33,27 @@ define(['backbone', 'jquery', 'underscore', 'moment',
expect(view.$el.is(':visible')).toBe(true);
});
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
- it("modal view closes on escape", function () {
- spyOn(view, "close");
+ it('modal view closes on escape', function() {
+ spyOn(view, 'close');
view.delegateEvents();
expect(view.close).not.toHaveBeenCalled();
- $(view.$el).simulate("keydown", {keyCode: keys.ESCAPE});
+ $(view.$el).simulate('keydown', {keyCode: keys.ESCAPE});
expect(view.close).toHaveBeenCalled();
});
- it("modal view closes click on close", function () {
- spyOn(view, "close");
+ it('modal view closes click on close', function() {
+ spyOn(view, 'close');
view.delegateEvents();
- var $closeButton = view.$el.find("button.close");
+ var $closeButton = view.$el.find('button.close');
expect($closeButton.length).toBe(1);
expect(view.close).not.toHaveBeenCalled();
$closeButton.trigger('click');
expect(view.close).toHaveBeenCalled();
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/image_input_spec.js b/lms/static/js/spec/verify_student/image_input_spec.js
index 2d700ef527..0b8b71908c 100644
--- a/lms/static/js/spec/verify_student/image_input_spec.js
+++ b/lms/static/js/spec/verify_student/image_input_spec.js
@@ -5,48 +5,47 @@ define([
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'js/verify_student/views/image_input_view',
'js/verify_student/models/verification_model'
-], function( $, Backbone, TemplateHelpers, AjaxHelpers, ImageInputView, VerificationModel ) {
+], function($, Backbone, TemplateHelpers, AjaxHelpers, ImageInputView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.ImageInputView', function() {
-
+ describe('edx.verify_student.ImageInputView', function() {
var IMAGE_DATA = 'abcd1234';
var createView = function() {
return new ImageInputView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
model: new VerificationModel({}),
modelAttribute: 'faceImage',
- errorModel: new ( Backbone.Model.extend({}) )(),
- submitButton: $( '#submit_button' ),
+ errorModel: new (Backbone.Model.extend({}))(),
+ submitButton: $('#submit_button')
}).render();
};
- var uploadImage = function( view, fileType ) {
+ var uploadImage = function(view, fileType) {
var deferred = $.Deferred();
// Since image upload is an asynchronous process,
// we need to wait for the upload to complete
// before checking the outcome.
var fakeFile,
- fakeEvent = { target: { files: [] } };
+ fakeEvent = {target: {files: []}};
// If no file type is specified, don't add any files.
// This simulates what happens when the user clicks
// "cancel" after clicking the input.
- if ( fileType !== null) {
+ if (fileType !== null) {
fakeFile = new Blob(
- [ IMAGE_DATA ],
- { type: 'image/' + fileType }
+ [IMAGE_DATA],
+ {type: 'image/' + fileType}
);
- fakeEvent.target.files = [ fakeFile ];
+ fakeEvent.target.files = [fakeFile];
}
// Wait for either a successful upload or an error
- view.on( 'imageCaptured', function() {
+ view.on('imageCaptured', function() {
deferred.resolve();
});
- view.on( 'error', function() {
+ view.on('error', function() {
deferred.resolve();
});
@@ -54,39 +53,39 @@ define([
// It's impossible to trigger this directly due
// to browser security restrictions, so we call
// the handler instead.
- view.handleInputChange( fakeEvent );
+ view.handleInputChange(fakeEvent);
return deferred.promise();
};
- var expectPreview = function( view, fileType ) {
+ var expectPreview = function(view, fileType) {
var previewImage = view.$preview.attr('src');
- if ( fileType ) {
- expect( previewImage ).toContain( 'data:image/' + fileType );
+ if (fileType) {
+ expect(previewImage).toContain('data:image/' + fileType);
} else {
- expect( previewImage ).toEqual( '' );
+ expect(previewImage).toEqual('');
}
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#submit_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#submit_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#submit_button').hasClass('is-disabled'),
+ isDisabled = $('#submit_button').prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
- var expectImageData = function( view, fileType ) {
- var imageData = view.model.get( view.modelAttribute );
- if ( fileType ) {
- expect( imageData ).toContain( 'data:image/' + fileType );
+ var expectImageData = function(view, fileType) {
+ var imageData = view.model.get(view.modelAttribute);
+ if (fileType) {
+ expect(imageData).toContain('data:image/' + fileType);
} else {
- expect( imageData ).toEqual( '' );
+ expect(imageData).toEqual('');
}
};
- var expectError = function( view ) {
- expect( view.errorModel.get('shown') ).toBe(true);
+ var expectError = function(view) {
+ expect(view.errorModel.get('shown')).toBe(true);
};
beforeEach(function() {
@@ -94,52 +93,52 @@ define([
'
' +
'
'
);
- TemplateHelpers.installTemplate( 'templates/verify_student/image_input' );
+ TemplateHelpers.installTemplate('templates/verify_student/image_input');
});
- it( 'initially disables the submit button', function() {
+ it('initially disables the submit button', function() {
createView();
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'uploads a png image', function(done) {
+ it('uploads a png image', function(done) {
var view = createView();
- uploadImage( view, 'png').then(function() {
- expectPreview( view, 'png' );
- expectSubmitEnabled( true );
- expectImageData( view, 'png' );
+ uploadImage(view, 'png').then(function() {
+ expectPreview(view, 'png');
+ expectSubmitEnabled(true);
+ expectImageData(view, 'png');
}).always(done);
});
- it( 'uploads a jpeg image', function(done) {
+ it('uploads a jpeg image', function(done) {
var view = createView();
- uploadImage( view, 'jpeg').then(function() {
- expectPreview( view, 'jpeg' );
- expectSubmitEnabled( true );
- expectImageData( view, 'jpeg' );
+ uploadImage(view, 'jpeg').then(function() {
+ expectPreview(view, 'jpeg');
+ expectSubmitEnabled(true);
+ expectImageData(view, 'jpeg');
}).always(done);
});
- it( 'hides the preview when the user cancels the upload', function(done) {
+ it('hides the preview when the user cancels the upload', function(done) {
var view = createView();
- uploadImage( view, null).then(function() {
- expectPreview( view, null );
- expectSubmitEnabled( false );
- expectImageData( view, null );
+ uploadImage(view, null).then(function() {
+ expectPreview(view, null);
+ expectSubmitEnabled(false);
+ expectImageData(view, null);
}).always(done);
});
- it( 'shows an error if the file type is not supported', function(done) {
+ it('shows an error if the file type is not supported', function(done) {
var view = createView();
- uploadImage( view, 'txt').then(function() {
- expectPreview( view, null );
- expectError( view );
- expectSubmitEnabled( false );
- expectImageData( view, null );
+ uploadImage(view, 'txt').then(function() {
+ expectPreview(view, null);
+ expectError(view);
+ expectSubmitEnabled(false);
+ expectImageData(view, null);
}).always(done);
});
});
diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
index 395b6918e8..fb191e9759 100644
--- a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
+++ b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
@@ -1,12 +1,12 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/make_payment_step_view'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/make_payment_step_view'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) {
'use strict';
var checkPaymentButtons,
@@ -18,8 +18,7 @@ define([
createView,
SERVER_ERROR_MSG = 'An error occurred!';
- describe( 'edx.verify_student.MakePaymentStepView', function() {
-
+ describe('edx.verify_student.MakePaymentStepView', function() {
var STEP_DATA = {
minPrice: '12',
currency: 'usd',
@@ -29,44 +28,44 @@ define([
isABTesting: true
};
- createView = function( stepDataOverrides ) {
+ createView = function(stepDataOverrides) {
var view = new MakePaymentStepView({
- el: $( '#current-step-container' ),
- stepData: _.extend( _.clone( STEP_DATA ), stepDataOverrides ),
- errorModel: new ( Backbone.Model.extend({}) )()
+ el: $('#current-step-container'),
+ stepData: _.extend(_.clone(STEP_DATA), stepDataOverrides),
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
// Stub the payment form submission
- spyOn( view, 'submitForm' ).and.callFake( function() {} );
+ spyOn(view, 'submitForm').and.callFake(function() {});
return view;
};
- expectPriceSelected = function( price ) {
- var sel = $( 'input[name="contribution"]' );
+ expectPriceSelected = function(price) {
+ var sel = $('input[name="contribution"]');
// check that contribution value is same as price given
- expect( sel.length ).toEqual(1);
- expect( sel.val() ).toEqual(price);
+ expect(sel.length).toEqual(1);
+ expect(sel.val()).toEqual(price);
};
- expectPaymentButtonEnabled = function( isEnabled ) {
- var el = $( '.payment-button'),
- appearsDisabled = el.hasClass( 'is-disabled' ),
- isDisabled = el.prop( 'disabled' );
+ expectPaymentButtonEnabled = function(isEnabled) {
+ var el = $('.payment-button'),
+ appearsDisabled = el.hasClass('is-disabled'),
+ isDisabled = el.prop('disabled');
- expect( appearsDisabled ).not.toEqual( isEnabled );
- expect( isDisabled ).not.toEqual( isEnabled );
+ expect(appearsDisabled).not.toEqual(isEnabled);
+ expect(isDisabled).not.toEqual(isEnabled);
};
expectPaymentDisabledBecauseInactive = function() {
- var payButton = $( '.payment-button' );
+ var payButton = $('.payment-button');
// Payment button should be hidden
- expect( payButton.length ).toEqual(0);
+ expect(payButton.length).toEqual(0);
};
- goToPayment = function( requests, kwargs ) {
+ goToPayment = function(requests, kwargs) {
var params = {
contribution: kwargs.amount || '',
course_id: kwargs.courseId || '',
@@ -75,25 +74,25 @@ define([
};
// Click the "go to payment" button
- $( '.payment-button' ).click();
+ $('.payment-button').click();
// Verify that the request was made to the server
AjaxHelpers.expectPostRequest(
- requests, '/verify_student/create_order/', $.param( params )
+ requests, '/verify_student/create_order/', $.param(params)
);
// Simulate the server response
- if ( kwargs.succeeds ) {
+ if (kwargs.succeeds) {
// TODO put fixture responses in the right place
AjaxHelpers.respondWithJson(
requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}}
);
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG);
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- expectPaymentSubmitted = function( view, params ) {
+ expectPaymentSubmitted = function(view, params) {
var form;
expect(view.submitForm).toHaveBeenCalled();
@@ -104,22 +103,22 @@ define([
expect(form.attr('action')).toEqual('http://payment-page-url/');
};
- checkPaymentButtons = function( requests, buttons ) {
- var $el = $( '.payment-button' );
+ checkPaymentButtons = function(requests, buttons) {
+ var $el = $('.payment-button');
expect($el.length).toEqual(_.size(buttons));
- _.each(buttons, function( expectedText, expectedId ) {
- var buttonEl = $( '#' + expectedId),
+ _.each(buttons, function(expectedText, expectedId) {
+ var buttonEl = $('#' + expectedId),
request;
buttonEl.removeAttr('disabled');
- expect( buttonEl.length ).toEqual( 1 );
- expect( buttonEl[0] ).toHaveClass( 'payment-button' );
- expect( buttonEl[0] ).toHaveText( expectedText );
- expect( buttonEl[0] ).toHaveClass( 'action-primary-blue' );
+ expect(buttonEl.length).toEqual(1);
+ expect(buttonEl[0]).toHaveClass('payment-button');
+ expect(buttonEl[0]).toHaveText(expectedText);
+ expect(buttonEl[0]).toHaveClass('action-primary-blue');
buttonEl[0].click();
- expect( buttonEl[0] ).toHaveClass( 'is-selected' );
- expectPaymentButtonEnabled( false );
+ expect(buttonEl[0]).toHaveClass('is-selected');
+ expectPaymentButtonEnabled(false);
request = AjaxHelpers.currentRequest(requests);
expect(request.requestBody.split('&')).toContain('processor=' + expectedId);
AjaxHelpers.respondWithJson(requests, {});
@@ -129,82 +128,81 @@ define([
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/make_payment_step_ab_testing' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/make_payment_step_ab_testing');
});
- it( 'A/B Testing: check Initialize method with AB testing enable ', function() {
+ it('A/B Testing: check Initialize method with AB testing enable ', function() {
var view = createView();
- expect( view.templateName ).toEqual('make_payment_step_ab_testing');
- expect( view.btnClass ).toEqual('action-primary-blue');
-
+ expect(view.templateName).toEqual('make_payment_step_ab_testing');
+ expect(view.btnClass).toEqual('action-primary-blue');
});
- it( 'shows users only minimum price', function() {
+ it('shows users only minimum price', function() {
var view = createView(),
requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice );
- expectPaymentButtonEnabled( true );
- goToPayment( requests, {
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'A/B Testing: provides working payment buttons for a single processor', function() {
+ it('A/B Testing: provides working payment buttons for a single processor', function() {
createView({processors: ['cybersource']});
- checkPaymentButtons( AjaxHelpers.requests(this), {cybersource: 'Checkout'});
+ checkPaymentButtons(AjaxHelpers.requests(this), {cybersource: 'Checkout'});
});
- it( 'A/B Testing: provides working payment buttons for multiple processors', function() {
+ it('A/B Testing: provides working payment buttons for multiple processors', function() {
createView({processors: ['cybersource', 'paypal', 'other']});
- checkPaymentButtons( AjaxHelpers.requests(this), {
+ checkPaymentButtons(AjaxHelpers.requests(this), {
cybersource: 'Checkout',
paypal: 'Checkout with PayPal',
other: 'Checkout with other'
});
});
- it( 'A/B Testing: by default minimum price is selected if no suggested prices are given', function() {
+ it('A/B Testing: by default minimum price is selected if no suggested prices are given', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice);
- expectPaymentButtonEnabled( true );
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'A/B Testing: min price is always selected even if contribution amount is provided', function() {
+ it('A/B Testing: min price is always selected even if contribution amount is provided', function() {
// Pre-select a price NOT in the suggestions
createView({
contributionAmount: '99.99'
});
// Expect that the price is filled in
- expectPriceSelected( STEP_DATA.minPrice );
+ expectPriceSelected(STEP_DATA.minPrice);
});
- it( 'A/B Testing: disables payment for inactive users', function() {
- createView({ isActive: false });
+ it('A/B Testing: disables payment for inactive users', function() {
+ createView({isActive: false});
expectPaymentDisabledBecauseInactive();
});
- it( 'A/B Testing: displays an error if the order could not be created', function() {
- var requests = AjaxHelpers.requests( this ),
+ it('A/B Testing: displays an error if the order could not be created', function() {
+ var requests = AjaxHelpers.requests(this),
view = createView();
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
@@ -212,14 +210,13 @@ define([
});
// Expect that an error is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit order' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit order');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
// Expect that the payment button is re-enabled
- expectPaymentButtonEnabled( true );
+ expectPaymentButtonEnabled(true);
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
index 85fe93d5ca..aea5720205 100644
--- a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
+++ b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
@@ -1,119 +1,118 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/make_payment_step_view'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/make_payment_step_view'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) {
'use strict';
- describe( 'edx.verify_student.MakePaymentStepView', function() {
-
+ describe('edx.verify_student.MakePaymentStepView', function() {
var PAYMENT_PARAMS = {
- orderId: "test-order",
- signature: "abcd1234"
+ orderId: 'test-order',
+ signature: 'abcd1234'
};
var STEP_DATA = {
- minPrice: "12",
- currency: "usd",
- processors: ["test-payment-processor"],
- courseKey: "edx/test/test",
+ minPrice: '12',
+ currency: 'usd',
+ processors: ['test-payment-processor'],
+ courseKey: 'edx/test/test',
courseModeSlug: 'verified'
};
- var SERVER_ERROR_MSG = "An error occurred!";
+ var SERVER_ERROR_MSG = 'An error occurred!';
- var createView = function( stepDataOverrides ) {
+ var createView = function(stepDataOverrides) {
var view = new MakePaymentStepView({
- el: $( '#current-step-container' ),
- stepData: _.extend( _.clone( STEP_DATA ), stepDataOverrides ),
- errorModel: new ( Backbone.Model.extend({}) )()
+ el: $('#current-step-container'),
+ stepData: _.extend(_.clone(STEP_DATA), stepDataOverrides),
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
// Stub the payment form submission
- spyOn( view, 'submitForm' ).and.callFake( function() {} );
+ spyOn(view, 'submitForm').and.callFake(function() {});
return view;
};
- var expectPriceSelected = function( price ) {
- var sel = $( 'input[name="contribution"]' );
+ var expectPriceSelected = function(price) {
+ var sel = $('input[name="contribution"]');
// check that contribution value is same as price given
- expect( sel.length ).toEqual(1);
- expect( sel.val() ).toEqual(price);
+ expect(sel.length).toEqual(1);
+ expect(sel.val()).toEqual(price);
};
- var expectPaymentButtonEnabled = function( isEnabled ) {
- var el = $( '.payment-button'),
- appearsDisabled = el.hasClass( 'is-disabled' ),
- isDisabled = el.prop( 'disabled' );
+ var expectPaymentButtonEnabled = function(isEnabled) {
+ var el = $('.payment-button'),
+ appearsDisabled = el.hasClass('is-disabled'),
+ isDisabled = el.prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
var expectPaymentDisabledBecauseInactive = function() {
- var payButton = $( '.payment-button' );
+ var payButton = $('.payment-button');
// Payment button should be hidden
- expect( payButton.length ).toEqual(0);
+ expect(payButton.length).toEqual(0);
};
- var goToPayment = function( requests, kwargs ) {
+ var goToPayment = function(requests, kwargs) {
var params = {
- contribution: kwargs.amount || "",
- course_id: kwargs.courseId || "",
- processor: kwargs.processor || "",
- sku: kwargs.sku || ""
+ contribution: kwargs.amount || '',
+ course_id: kwargs.courseId || '',
+ processor: kwargs.processor || '',
+ sku: kwargs.sku || ''
};
// Click the "go to payment" button
- $( '.payment-button' ).click();
+ $('.payment-button').click();
// Verify that the request was made to the server
AjaxHelpers.expectPostRequest(
- requests, "/verify_student/create_order/", $.param( params )
+ requests, '/verify_student/create_order/', $.param(params)
);
// Simulate the server response
- if ( kwargs.succeeds ) {
+ if (kwargs.succeeds) {
// TODO put fixture responses in the right place
- AjaxHelpers.respondWithJson( requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}} );
+ AjaxHelpers.respondWithJson(requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}});
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG);
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- var expectPaymentSubmitted = function( view, params ) {
+ var expectPaymentSubmitted = function(view, params) {
var form;
expect(view.submitForm).toHaveBeenCalled();
form = view.submitForm.calls.mostRecent().args[0];
expect(form.serialize()).toEqual($.param(params));
- expect(form.attr('method')).toEqual("POST");
+ expect(form.attr('method')).toEqual('POST');
expect(form.attr('action')).toEqual('http://payment-page-url/');
};
- var checkPaymentButtons = function( requests, buttons ) {
- var $el = $( '.payment-button' );
+ var checkPaymentButtons = function(requests, buttons) {
+ var $el = $('.payment-button');
expect($el.length).toEqual(_.size(buttons));
- _.each(buttons, function( expectedText, expectedId ) {
- var buttonEl = $( '#' + expectedId),
+ _.each(buttons, function(expectedText, expectedId) {
+ var buttonEl = $('#' + expectedId),
request;
buttonEl.removeAttr('disabled');
- expect( buttonEl.length ).toEqual( 1 );
- expect( buttonEl[0] ).toHaveClass( 'payment-button' );
- expect( buttonEl[0] ).toHaveClass( 'action-primary' );
- expect( buttonEl[0] ).toHaveText( expectedText );
+ expect(buttonEl.length).toEqual(1);
+ expect(buttonEl[0]).toHaveClass('payment-button');
+ expect(buttonEl[0]).toHaveClass('action-primary');
+ expect(buttonEl[0]).toHaveText(expectedText);
buttonEl[0].click();
- expect( buttonEl[0] ).toHaveClass( 'is-selected' );
- expectPaymentButtonEnabled( false );
+ expect(buttonEl[0]).toHaveClass('is-selected');
+ expectPaymentButtonEnabled(false);
request = AjaxHelpers.currentRequest(requests);
expect(request.requestBody.split('&')).toContain('processor=' + expectedId);
AjaxHelpers.respondWithJson(requests, {});
@@ -123,31 +122,31 @@ define([
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/make_payment_step' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/make_payment_step');
});
- it( 'shows users only minimum price', function() {
+ it('shows users only minimum price', function() {
var view = createView({}),
requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice );
- expectPaymentButtonEnabled( true );
- goToPayment( requests, {
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it ('view containing verification msg when verification deadline is set and user is active', function() {
+ it('view containing verification msg when verification deadline is set and user is active', function() {
var verificationDeadlineDateFormat = 'Aug 14, 2016 at 23:59 UTC';
createView({
userEmail: 'test@example.com',
requirements: {
- isVisible:true
+ isVisible: true
},
verificationDeadline: verificationDeadlineDateFormat,
isActive: true
@@ -164,11 +163,11 @@ define([
).toEqual(1);
});
- it ('view containing user email when verification deadline is set and user is not active', function() {
+ it('view containing user email when verification deadline is set and user is not active', function() {
createView({
userEmail: 'test@example.com',
requirements: {
- isVisible:true
+ isVisible: true
},
verificationDeadline: true,
isActive: false
@@ -177,61 +176,61 @@ define([
expect($('p.instruction-info:contains("test@example.com")').length).toEqual(1);
});
- it ('view containing user email', function() {
- createView({userEmail: 'test@example.com', requirements: {isVisible:true}, isActive: false});
+ it('view containing user email', function() {
+ createView({userEmail: 'test@example.com', requirements: {isVisible: true}, isActive: false});
expect($('p.instruction-info:contains("test@example.com")').length).toEqual(1);
});
- it( 'provides working payment buttons for a single processor', function() {
+ it('provides working payment buttons for a single processor', function() {
createView({processors: ['cybersource']});
- checkPaymentButtons( AjaxHelpers.requests(this), {cybersource: "Checkout"});
+ checkPaymentButtons(AjaxHelpers.requests(this), {cybersource: 'Checkout'});
});
- it( 'provides working payment buttons for multiple processors', function() {
+ it('provides working payment buttons for multiple processors', function() {
createView({processors: ['cybersource', 'paypal', 'other']});
- checkPaymentButtons( AjaxHelpers.requests(this), {
- cybersource: "Checkout",
- paypal: "Checkout with PayPal",
- other: "Checkout with other"
+ checkPaymentButtons(AjaxHelpers.requests(this), {
+ cybersource: 'Checkout',
+ paypal: 'Checkout with PayPal',
+ other: 'Checkout with other'
});
});
- it( 'by default minimum price is selected if no suggested prices are given', function() {
+ it('by default minimum price is selected if no suggested prices are given', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice);
- expectPaymentButtonEnabled( true );
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'min price is always selected even if contribution amount is provided', function() {
+ it('min price is always selected even if contribution amount is provided', function() {
// Pre-select a price NOT in the suggestions
createView({
contributionAmount: '99.99'
});
// Expect that the price is filled in
- expectPriceSelected( STEP_DATA.minPrice );
+ expectPriceSelected(STEP_DATA.minPrice);
});
- it( 'disables payment for inactive users', function() {
- createView({ isActive: false });
+ it('disables payment for inactive users', function() {
+ createView({isActive: false});
expectPaymentDisabledBecauseInactive();
});
- it( 'displays an error if the order could not be created', function() {
- var requests = AjaxHelpers.requests( this ),
+ it('displays an error if the order could not be created', function() {
+ var requests = AjaxHelpers.requests(this),
view = createView({});
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
@@ -239,15 +238,15 @@ define([
});
// Expect that an error is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit order' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit order');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
// Expect that the payment button is re-enabled
- expectPaymentButtonEnabled( true );
+ expectPaymentButtonEnabled(true);
});
- it('displays an error if no payment processors are available', function () {
+ it('displays an error if no payment processors are available', function() {
var view = createView({processors: []});
expect(view.errorModel.get('shown')).toBe(true);
expect(view.errorModel.get('errorTitle')).toEqual(
@@ -257,12 +256,11 @@ define([
'Try the transaction again in a few minutes.'
);
});
- it( 'check Initialize method without AB testing ', function() {
+ it('check Initialize method without AB testing ', function() {
var view = createView();
- expect( view.templateName ).toEqual('make_payment_step');
- expect( view.btnClass ).toEqual('action-primary');
+ expect(view.templateName).toEqual('make_payment_step');
+ expect(view.btnClass).toEqual('action-primary');
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
index 53f4b1fd8b..f8861f9e22 100644
--- a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
+++ b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
@@ -1,9 +1,8 @@
define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/views/pay_and_verify_view'],
- function( $, TemplateHelpers, PayAndVerifyView ) {
+ function($, TemplateHelpers, PayAndVerifyView) {
'use strict';
- describe( 'edx.verify_student.PayAndVerifyView', function() {
-
+ describe('edx.verify_student.PayAndVerifyView', function() {
var TEMPLATES = [
'enrollment_confirmation_step',
'error',
@@ -18,52 +17,52 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
];
var INTRO_STEP = {
- name: "intro-step",
- title: "Intro"
+ name: 'intro-step',
+ title: 'Intro'
};
var DISPLAY_STEPS_FOR_PAYMENT = [
{
- name: "make-payment-step",
- title: "Make Payment"
+ name: 'make-payment-step',
+ title: 'Make Payment'
},
{
- name: "payment-confirmation-step",
- title: "Payment Confirmation"
+ name: 'payment-confirmation-step',
+ title: 'Payment Confirmation'
}
];
var DISPLAY_STEPS_FOR_VERIFICATION = [
{
- name: "face-photo-step",
- title: "Take Face Photo"
+ name: 'face-photo-step',
+ title: 'Take Face Photo'
},
{
- name: "id-photo-step",
- title: "ID Photo"
+ name: 'id-photo-step',
+ title: 'ID Photo'
},
{
- name: "review-photos-step",
- title: "Review Photos"
+ name: 'review-photos-step',
+ title: 'Review Photos'
},
{
- name: "enrollment-confirmation-step",
- title: "Enrollment Confirmation"
+ name: 'enrollment-confirmation-step',
+ title: 'Enrollment Confirmation'
}
];
- var createView = function( displaySteps, currentStep ) {
+ var createView = function(displaySteps, currentStep) {
return new PayAndVerifyView({
displaySteps: displaySteps,
currentStep: currentStep,
- errorModel: new ( Backbone.Model.extend({}) )()
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
};
- var expectStepRendered = function( stepName ) {
+ var expectStepRendered = function(stepName) {
// Expect that the step container div rendered
- expect( $( '.' + stepName ).length > 0 ).toBe( true );
+ expect($('.' + stepName).length > 0).toBe(true);
};
beforeEach(function() {
@@ -71,12 +70,12 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
navigator.getUserMedia = jasmine.createSpy();
setFixtures('
');
- $.each( TEMPLATES, function( index, templateName ) {
- TemplateHelpers.installTemplate('templates/verify_student/' + templateName );
+ $.each(TEMPLATES, function(index, templateName) {
+ TemplateHelpers.installTemplate('templates/verify_student/' + templateName);
});
});
- it( 'renders payment and verification steps', function() {
+ it('renders payment and verification steps', function() {
// Create the view, starting on the first step
var view = createView(
DISPLAY_STEPS_FOR_PAYMENT.concat(DISPLAY_STEPS_FOR_VERIFICATION),
@@ -107,7 +106,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
expectStepRendered('enrollment-confirmation-step');
});
- it( 'renders intro and verification steps', function() {
+ it('renders intro and verification steps', function() {
var view = createView(
[INTRO_STEP].concat(DISPLAY_STEPS_FOR_VERIFICATION),
'intro-step'
@@ -130,7 +129,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
expectStepRendered('enrollment-confirmation-step');
});
- it( 'starts from a later step', function() {
+ it('starts from a later step', function() {
// Start from the payment confirmation step
var view = createView(
DISPLAY_STEPS_FOR_PAYMENT.concat(DISPLAY_STEPS_FOR_VERIFICATION),
@@ -143,10 +142,9 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
// Try moving to the next step
view.nextStep();
expectStepRendered('face-photo-step');
-
});
- it( 'jumps to a particular step', function() {
+ it('jumps to a particular step', function() {
// Start on the review photos step
var view = createView(
DISPLAY_STEPS_FOR_VERIFICATION,
@@ -156,7 +154,6 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
// Jump back to the face photo step
view.goToStep('face-photo-step');
expectStepRendered('face-photo-step');
-
});
});
}
diff --git a/lms/static/js/spec/verify_student/reverify_view_spec.js b/lms/static/js/spec/verify_student/reverify_view_spec.js
index e932ea116f..97edebdc69 100644
--- a/lms/static/js/spec/verify_student/reverify_view_spec.js
+++ b/lms/static/js/spec/verify_student/reverify_view_spec.js
@@ -3,27 +3,26 @@
**/
define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/views/review_photos_step_view',
'js/verify_student/views/reverify_view'],
- function( $, TemplateHelpers, ReviewPhotosStepView, ReverifyView ) {
+ function($, TemplateHelpers, ReviewPhotosStepView, ReverifyView) {
'use strict';
- describe( 'edx.verify_student.ReverifyView', function() {
-
+ describe('edx.verify_student.ReverifyView', function() {
var TEMPLATES = [
- "webcam_photo",
- "image_input",
- "error",
- "face_photo_step",
- "id_photo_step",
- "review_photos_step",
- "reverify_success_step"
+ 'webcam_photo',
+ 'image_input',
+ 'error',
+ 'face_photo_step',
+ 'id_photo_step',
+ 'review_photos_step',
+ 'reverify_success_step'
];
var STEP_INFO = {
'face-photo-step': {
- platformName: 'edX',
+ platformName: 'edX'
},
'id-photo-step': {
- platformName: 'edX',
+ platformName: 'edX'
},
'review-photos-step': {
fullName: 'John Doe',
@@ -38,9 +37,9 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
return new ReverifyView({stepInfo: STEP_INFO}).render();
};
- var expectStepRendered = function( stepName ) {
+ var expectStepRendered = function(stepName) {
// Expect that the step container div rendered
- expect( $( '.' + stepName ).length > 0 ).toBe( true );
+ expect($('.' + stepName).length > 0).toBe(true);
};
@@ -49,12 +48,12 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
navigator.getUserMedia = jasmine.createSpy();
setFixtures('
');
- $.each( TEMPLATES, function( index, templateName ) {
- TemplateHelpers.installTemplate('templates/verify_student/' + templateName );
+ $.each(TEMPLATES, function(index, templateName) {
+ TemplateHelpers.installTemplate('templates/verify_student/' + templateName);
});
});
- it( 'renders verification steps', function() {
+ it('renders verification steps', function() {
var view = createView();
// Go through the flow, verifying that each step renders
diff --git a/lms/static/js/spec/verify_student/review_photos_step_view_spec.js b/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
index 8b63bf5daf..3b5cf6dfc3 100644
--- a/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
+++ b/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
@@ -1,77 +1,76 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/review_photos_step_view',
- 'js/verify_student/models/verification_model'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, ReviewPhotosStepView, VerificationModel ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/review_photos_step_view',
+ 'js/verify_student/models/verification_model'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, ReviewPhotosStepView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.ReviewPhotosStepView', function() {
-
+ describe('edx.verify_student.ReviewPhotosStepView', function() {
var STEP_DATA = {},
- FULL_NAME = "Test User",
- FACE_IMAGE = "abcd1234",
- PHOTO_ID_IMAGE = "efgh56789",
- SERVER_ERROR_MSG = "An error occurred!";
+ FULL_NAME = 'Test User',
+ FACE_IMAGE = 'abcd1234',
+ PHOTO_ID_IMAGE = 'efgh56789',
+ SERVER_ERROR_MSG = 'An error occurred!';
var createView = function() {
return new ReviewPhotosStepView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
stepData: STEP_DATA,
model: new VerificationModel({
faceImage: FACE_IMAGE,
identificationImage: PHOTO_ID_IMAGE
}),
- errorModel: new ( Backbone.Model.extend({}) )()
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
};
- var submitPhotos = function( requests, expectedParams, succeeds ) {
+ var submitPhotos = function(requests, expectedParams, succeeds) {
// Submit the photos
- $( '#next_step_button' ).click();
+ $('#next_step_button').click();
// Expect a request to the server
AjaxHelpers.expectRequest(
- requests, "POST", "/verify_student/submit-photos/",
- $.param( expectedParams )
+ requests, 'POST', '/verify_student/submit-photos/',
+ $.param(expectedParams)
);
// Simulate the server response
- if ( succeeds ) {
- AjaxHelpers.respondWithJson( requests, {url: '/arbitrary-url/'} );
+ if (succeeds) {
+ AjaxHelpers.respondWithJson(requests, {url: '/arbitrary-url/'});
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG );
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- var setFullName = function( fullName ) {
- $('#new-name').val( fullName );
+ var setFullName = function(fullName) {
+ $('#new-name').val(fullName);
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#next_step_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#next_step_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#next_step_button').hasClass('is-disabled'),
+ isDisabled = $('#next_step_button').prop('disabled');
- expect( !appearsDisabled ).toBe( isEnabled );
- expect( !isDisabled ).toBe( isEnabled );
+ expect(!appearsDisabled).toBe(isEnabled);
+ expect(!isDisabled).toBe(isEnabled);
};
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/review_photos_step' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/review_photos_step');
});
- it( 'allows the user to change her full name', function() {
- var requests = AjaxHelpers.requests( this );
+ it('allows the user to change her full name', function() {
+ var requests = AjaxHelpers.requests(this);
createView();
- setFullName( FULL_NAME );
+ setFullName(FULL_NAME);
submitPhotos(
requests,
{
@@ -83,8 +82,8 @@ define([
);
});
- it( 'submits photos for verification', function() {
- var requests = AjaxHelpers.requests( this );
+ it('submits photos for verification', function() {
+ var requests = AjaxHelpers.requests(this);
createView();
submitPhotos(
@@ -98,12 +97,12 @@ define([
// Expect that submission is disabled to prevent
// duplicate submission.
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'displays an error if photo submission fails', function() {
+ it('displays an error if photo submission fails', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
submitPhotos(
requests,
@@ -116,14 +115,13 @@ define([
// Expect the submit button is re-enabled to allow
// the user to retry.
- expectSubmitEnabled( true );
+ expectSubmitEnabled(true);
// Expect that an error message is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit photos' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit photos');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/webcam_photo_view_spec.js b/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
index 28b45d7cc3..d32b92e5b2 100644
--- a/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
+++ b/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
@@ -1,19 +1,18 @@
define([
- 'jquery',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/verify_student/views/webcam_photo_view',
- 'js/verify_student/models/verification_model'
- ],
- function( $, Backbone, TemplateHelpers, AjaxHelpers, WebcamPhotoView, VerificationModel ) {
+ 'jquery',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/verify_student/views/webcam_photo_view',
+ 'js/verify_student/models/verification_model'
+],
+ function($, Backbone, TemplateHelpers, AjaxHelpers, WebcamPhotoView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.WebcamPhotoView', function() {
-
- var IMAGE_DATA = "abcd1234",
- VIDEO_ERROR_TITLE = "video capture error",
- VIDEO_ERROR_MSG = "video error msg";
+ describe('edx.verify_student.WebcamPhotoView', function() {
+ var IMAGE_DATA = 'abcd1234',
+ VIDEO_ERROR_TITLE = 'video capture error',
+ VIDEO_ERROR_MSG = 'video error msg';
/**
* For the purposes of these tests, we stub out the backend
@@ -25,59 +24,58 @@ define([
* cover the HTML5 / Flash webcam integration. We will need
* cross-browser manual testing to verify that this works correctly.
*/
- var StubBackend = function( name, isSupported, snapshotSuccess ) {
-
- if ( _.isUndefined( isSupported ) ) {
+ var StubBackend = function(name, isSupported, snapshotSuccess) {
+ if (_.isUndefined(isSupported)) {
isSupported = true;
}
- if ( _.isUndefined( snapshotSuccess ) ) {
+ if (_.isUndefined(snapshotSuccess)) {
snapshotSuccess = true;
}
return {
name: name,
initialize: function() {},
- isSupported: function() { return isSupported; },
+ isSupported: function() { return isSupported; },
snapshot: function() { return snapshotSuccess; },
getImageData: function() { return IMAGE_DATA; },
reset: function() {}
};
};
- var createView = function( backendStub ) {
+ var createView = function(backendStub) {
return new WebcamPhotoView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
model: new VerificationModel({}),
modelAttribute: 'faceImage',
- errorModel: new ( Backbone.Model.extend({}) )(),
- submitButton: $( '#submit_button' ),
+ errorModel: new (Backbone.Model.extend({}))(),
+ submitButton: $('#submit_button'),
backend: backendStub
}).render();
};
var takeSnapshot = function() {
- $( '#webcam_capture_button' ).click();
+ $('#webcam_capture_button').click();
};
var resetWebcam = function() {
- $( '#webcam_reset_button' ).click();
+ $('#webcam_reset_button').click();
};
- var expectButtonShown = function( obj ) {
- var resetButton = $( '#webcam_reset_button' ),
- captureButton = $( '#webcam_capture_button' );
+ var expectButtonShown = function(obj) {
+ var resetButton = $('#webcam_reset_button'),
+ captureButton = $('#webcam_capture_button');
- expect( captureButton.hasClass( 'is-hidden') ).toBe( !obj.snapshot );
- expect( resetButton.hasClass( 'is-hidden') ).toBe( !obj.reset );
+ expect(captureButton.hasClass('is-hidden')).toBe(!obj.snapshot);
+ expect(resetButton.hasClass('is-hidden')).toBe(!obj.reset);
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#submit_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#submit_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#submit_button').hasClass('is-disabled'),
+ isDisabled = $('#submit_button').prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
beforeEach(function() {
@@ -87,14 +85,14 @@ define([
'
' +
'
'
);
- TemplateHelpers.installTemplate( 'templates/verify_student/webcam_photo' );
+ TemplateHelpers.installTemplate('templates/verify_student/webcam_photo');
});
- it( 'takes a snapshot', function() {
- var view = createView( new StubBackend( "html5" ) );
+ it('takes a snapshot', function() {
+ var view = createView(new StubBackend('html5'));
// Spy on the backend
- spyOn( view.backend, 'snapshot' ).and.callThrough();
+ spyOn(view.backend, 'snapshot').and.callThrough();
// Initially, only the snapshot button is shown
expectButtonShown({
@@ -102,57 +100,57 @@ define([
reset: false
});
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
// Take the snapshot
takeSnapshot();
// Expect that the backend was used to take the snapshot
- expect( view.backend.snapshot ).toHaveBeenCalled();
+ expect(view.backend.snapshot).toHaveBeenCalled();
// Expect that buttons were updated
expectButtonShown({
snapshot: false,
reset: true
});
- expectSubmitEnabled( true );
+ expectSubmitEnabled(true);
// Expect that the image data was saved to the model
- expect( view.model.get( 'faceImage' ) ).toEqual( IMAGE_DATA );
+ expect(view.model.get('faceImage')).toEqual(IMAGE_DATA);
});
- it( 'resets the camera', function() {
- var view = createView( new StubBackend( "html5" ) );
+ it('resets the camera', function() {
+ var view = createView(new StubBackend('html5'));
// Spy on the backend
- spyOn( view.backend, 'reset' ).and.callThrough();
+ spyOn(view.backend, 'reset').and.callThrough();
// Take the snapshot, then reset
takeSnapshot();
resetWebcam();
// Expect that the backend was reset
- expect( view.backend.reset ).toHaveBeenCalled();
+ expect(view.backend.reset).toHaveBeenCalled();
// Expect that we're back to the initial button shown state
expectButtonShown({
snapshot: true,
reset: false
});
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
// Expect that the image data is wiped from the model
- expect( view.model.get( 'faceImage' ) ).toEqual( "" );
+ expect(view.model.get('faceImage')).toEqual('');
});
- it( 'displays an error if the snapshot fails', function() {
- var view = createView( new StubBackend( "html5", true, false ) );
+ it('displays an error if the snapshot fails', function() {
+ var view = createView(new StubBackend('html5', true, false));
// Take a snapshot
takeSnapshot();
// Do NOT expect an error displayed
- expect( view.errorModel.get( 'shown' ) ).not.toBe( true );
+ expect(view.errorModel.get('shown')).not.toBe(true);
// Expect that the capture button is still enabled
// so the user can retry.
@@ -163,31 +161,29 @@ define([
// Expect that submit is NOT enabled, since the user didn't
// successfully take a snapshot.
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'displays an error triggered by the backend', function() {
- var view = createView( new StubBackend( "html5") );
+ it('displays an error triggered by the backend', function() {
+ var view = createView(new StubBackend('html5'));
// Simulate an error triggered by the backend
// This could occur at any point, including
// while the video capture is being set up.
- view.backend.trigger( 'error', VIDEO_ERROR_TITLE, VIDEO_ERROR_MSG );
+ view.backend.trigger('error', VIDEO_ERROR_TITLE, VIDEO_ERROR_MSG);
// Verify that the error is displayed
- expect( view.errorModel.get( 'errorTitle' ) ).toEqual( VIDEO_ERROR_TITLE );
- expect( view.errorModel.get( 'errorMsg' ) ).toEqual( VIDEO_ERROR_MSG );
- expect( view.errorModel.get( 'shown' ) ).toBe( true );
+ expect(view.errorModel.get('errorTitle')).toEqual(VIDEO_ERROR_TITLE);
+ expect(view.errorModel.get('errorMsg')).toEqual(VIDEO_ERROR_MSG);
+ expect(view.errorModel.get('shown')).toBe(true);
// Expect that buttons are hidden
expectButtonShown({
snapshot: false,
reset: false
});
- expectSubmitEnabled( false );
-
+ expectSubmitEnabled(false);
});
-
});
}
);
diff --git a/lms/static/js/spec/views/fields_helpers.js b/lms/static/js/spec/views/fields_helpers.js
index dad147c248..3d4e6eef21 100644
--- a/lms/static/js/spec/views/fields_helpers.js
+++ b/lms/static/js/spec/views/fields_helpers.js
@@ -1,12 +1,12 @@
define(['backbone',
'jquery',
'underscore',
- 'edx-ui-toolkit/js/utils/html-utils',
+ 'edx-ui-toolkit/js/utils/html-utils',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers',
'js/views/fields',
'string_utils'],
- function (Backbone, $, _, HtmlUtils, AjaxHelpers, TemplateHelpers, FieldViews) {
+ function(Backbone, $, _, HtmlUtils, AjaxHelpers, TemplateHelpers, FieldViews) {
'use strict';
var API_URL = '/api/end_point/v1';
@@ -27,7 +27,7 @@ define(['backbone',
url: API_URL
});
- var createFieldData = function (fieldType, fieldData) {
+ var createFieldData = function(fieldType, fieldData) {
var data = {
model: fieldData.model || new UserAccountModel({}),
title: fieldData.title || 'Field Title',
@@ -37,16 +37,16 @@ define(['backbone',
};
switch (fieldType) {
- case FieldViews.DropdownFieldView:
- data['required'] = fieldData.required || false;
- data['options'] = fieldData.options || SELECT_OPTIONS;
- break;
- case FieldViews.LinkFieldView:
- case FieldViews.PasswordFieldView:
- data['linkTitle'] = fieldData.linkTitle || "Link Title";
- data['linkHref'] = fieldData.linkHref || "/path/to/resource";
- data['emailAttribute'] = 'email';
- break;
+ case FieldViews.DropdownFieldView:
+ data['required'] = fieldData.required || false;
+ data['options'] = fieldData.options || SELECT_OPTIONS;
+ break;
+ case FieldViews.LinkFieldView:
+ case FieldViews.PasswordFieldView:
+ data['linkTitle'] = fieldData.linkTitle || 'Link Title';
+ data['linkHref'] = fieldData.linkHref || '/path/to/resource';
+ data['emailAttribute'] = 'email';
+ break;
}
_.extend(data, fieldData);
@@ -57,10 +57,10 @@ define(['backbone',
var createErrorMessage = function(attribute, user_message) {
var field_errors = {};
field_errors[attribute] = {
- "user_message": user_message
+ 'user_message': user_message
};
return {
- "field_errors": field_errors
+ 'field_errors': field_errors
};
};
@@ -87,8 +87,7 @@ define(['backbone',
);
};
- var verifyMessageUpdates = function (view, data, timerCallback) {
-
+ var verifyMessageUpdates = function(view, data, timerCallback) {
var message = 'Here to help!';
view.showHelpMessage(message);
@@ -118,7 +117,7 @@ define(['backbone',
expectMessageContains(view, view.indicators.error);
};
- var verifySuccessMessageReset = function (view) {
+ var verifySuccessMessageReset = function(view) {
view.showHelpMessage();
expectMessageContains(view, view.helpMessage);
view.showSuccessMessage();
@@ -130,12 +129,12 @@ define(['backbone',
view.showSuccessMessage();
expectMessageContains(view, view.indicators.success);
// But if we change the message, it should not get reset.
- view.showHelpMessage("Do not reset this!");
+ view.showHelpMessage('Do not reset this!');
jasmine.clock().tick(7000);
- expectMessageContains(view, "Do not reset this!");
+ expectMessageContains(view, 'Do not reset this!');
};
- var verifyPersistence = function (fieldClass, requests) {
+ var verifyPersistence = function(fieldClass, requests) {
var fieldData = createFieldData(fieldClass, {
title: 'Username',
valueAttribute: 'username',
@@ -148,16 +147,16 @@ define(['backbone',
var valueInputSelector;
switch (fieldClass) {
- case FieldViews.TextFieldView:
- valueInputSelector = '.u-field-value > input';
- break;
- case FieldViews.DropdownFieldView:
- valueInputSelector = '.u-field-value > select';
- _.extend(fieldData, {validValue: SELECT_OPTIONS[0][0]});
- break;
- case FieldViews.TextareaFieldView:
- valueInputSelector = '.u-field-value > textarea';
- break;
+ case FieldViews.TextFieldView:
+ valueInputSelector = '.u-field-value > input';
+ break;
+ case FieldViews.DropdownFieldView:
+ valueInputSelector = '.u-field-value > select';
+ _.extend(fieldData, {validValue: SELECT_OPTIONS[0][0]});
+ break;
+ case FieldViews.TextareaFieldView:
+ valueInputSelector = '.u-field-value > textarea';
+ break;
}
view.$(valueInputSelector).val(fieldData.validValue).change();
@@ -166,7 +165,7 @@ define(['backbone',
AjaxHelpers.expectNoRequests(requests);
};
- var verifyEditableField = function (view, data, requests) {
+ var verifyEditableField = function(view, data, requests) {
var request_data = {};
var url = view.model.url;
@@ -241,19 +240,19 @@ define(['backbone',
}
};
- var verifyTextField = function (view, data, requests) {
+ var verifyTextField = function(view, data, requests) {
verifyEditableField(view, _.extend({
- valueSelector: '.u-field-value',
- valueInputSelector: '.u-field-value > input'
- }, data),
+ valueSelector: '.u-field-value',
+ valueInputSelector: '.u-field-value > input'
+ }, data),
requests);
};
- var verifyDropDownField = function (view, data, requests) {
+ var verifyDropDownField = function(view, data, requests) {
verifyEditableField(view, _.extend({
- valueSelector: '.u-field-value',
- valueInputSelector: '.u-field-value > select'
- }, data
+ valueSelector: '.u-field-value',
+ valueInputSelector: '.u-field-value > select'
+ }, data
), requests);
};
diff --git a/lms/static/js/spec/views/fields_spec.js b/lms/static/js/spec/views/fields_spec.js
index ce8c2291c0..f574d4c60f 100644
--- a/lms/static/js/spec/views/fields_spec.js
+++ b/lms/static/js/spec/views/fields_spec.js
@@ -1,14 +1,13 @@
define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers', 'js/views/fields', 'js/spec/views/fields_helpers',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers) {
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers) {
'use strict';
var USERNAME = 'Legolas',
BIO = "My Name is Theon Greyjoy. I'm member of House Greyjoy";
- describe("edx.FieldViews", function () {
-
+ describe('edx.FieldViews', function() {
var requests,
timerCallback,
dropdownSelectClass = '.u-field-value > select',
@@ -23,7 +22,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
FieldViews.TextareaFieldView
];
- beforeEach(function () {
+ beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.clock().install();
});
@@ -32,10 +31,8 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
jasmine.clock().uninstall();
});
- it("updates messages correctly for all fields", function() {
-
+ it('updates messages correctly for all fields', function() {
for (var i = 0; i < fieldViewClasses.length; i++) {
-
var fieldViewClass = fieldViewClasses[i];
var fieldData = FieldViewsSpecHelpers.createFieldData(fieldViewClass, {
title: 'Username',
@@ -48,8 +45,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
}
});
- it("resets to help message some time after success message is set", function() {
-
+ it('resets to help message some time after success message is set', function() {
for (var i = 0; i < fieldViewClasses.length; i++) {
var fieldViewClass = fieldViewClasses[i];
var fieldData = FieldViewsSpecHelpers.createFieldData(fieldViewClass, {
@@ -63,8 +59,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
}
});
- it("sends a PATCH request when saveAttributes is called", function() {
-
+ it('sends a PATCH request when saveAttributes is called', function() {
requests = AjaxHelpers.requests(this);
var fieldViewClass = FieldViews.EditableFieldView;
@@ -88,7 +83,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(request.requestBody).toBe('{"language":"ur"}');
});
- it("correctly renders and updates ReadonlyFieldView", function() {
+ it('correctly renders and updates ReadonlyFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.ReadonlyFieldView, {
title: 'Username',
valueAttribute: 'username',
@@ -103,8 +98,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.fieldValue()).toBe('bookworm');
});
- it("correctly renders, updates and persists changes to TextFieldView when editable == always", function() {
-
+ it('correctly renders, updates and persists changes to TextFieldView when editable == always', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.TextFieldView, {
@@ -122,13 +116,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: 'My Name',
invalidValue1: 'Your Name',
invalidValue2: 'Her Name',
- validationError: "Think again!",
+ validationError: 'Think again!',
defaultValue: ''
}, requests);
});
- it("correctly renders and updates DropdownFieldView when editable == never", function() {
-
+ it('correctly renders and updates DropdownFieldView when editable == never', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -166,8 +159,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$(dropdownButtonClass).length).toBe(0);
});
- it("correctly renders, updates and persists changes to DropdownFieldView when editable == always", function() {
-
+ it('correctly renders, updates and persists changes to DropdownFieldView when editable == always', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -185,13 +177,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: FieldViewsSpecHelpers.SELECT_OPTIONS[0][0],
invalidValue1: FieldViewsSpecHelpers.SELECT_OPTIONS[1][0],
invalidValue2: FieldViewsSpecHelpers.SELECT_OPTIONS[2][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
- it("correctly renders, updates and persists changes to DropdownFieldView when editable == toggle", function() {
-
+ it('correctly renders, updates and persists changes to DropdownFieldView when editable == toggle', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -211,12 +202,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: FieldViewsSpecHelpers.SELECT_OPTIONS[0][0],
invalidValue1: FieldViewsSpecHelpers.SELECT_OPTIONS[1][0],
invalidValue2: FieldViewsSpecHelpers.SELECT_OPTIONS[2][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
- it("only shows empty option in DropdownFieldView if required is false or model value is not set", function() {
+ it('only shows empty option in DropdownFieldView if required is false or model value is not set', function() {
requests = AjaxHelpers.requests(this);
var editableOptions = ['toggle', 'always'];
@@ -226,7 +217,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
valueAttribute: 'drop-down',
helpMessage: 'edX drop down',
editable: editable,
- required:true,
+ required: true,
persistChanges: true
});
var view = new FieldViews.DropdownFieldView(fieldData).render();
@@ -249,13 +240,13 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
});
- it("correctly renders and updates TextAreaFieldView when editable == never", function() {
+ it('correctly renders and updates TextAreaFieldView when editable == never', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.TextareaFieldView, {
title: 'About me',
valueAttribute: 'bio',
helpMessage: 'Wicked is good',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
- "what your interests are, why you’re taking courses on edX, or what you hope to learn.",
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
+ 'what your interests are, why you’re taking courses on edX, or what you hope to learn.',
editable: 'never',
persistChanges: true,
messagePosition: 'header'
@@ -278,8 +269,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$(textareaLinkClass).length).toBe(0);
});
- it("correctly renders, updates and persists changes to TextAreaFieldView when editable == toggle", function() {
-
+ it('correctly renders, updates and persists changes to TextAreaFieldView when editable == toggle', function() {
requests = AjaxHelpers.requests(this);
var valueInputSelector = '.u-field-value > textarea';
@@ -287,8 +277,8 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
title: 'About me',
valueAttribute: 'bio',
helpMessage: 'Wicked is good',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
- "what your interests are, why you’re taking courses on edX, or what you hope to learn.",
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
+ 'what your interests are, why you’re taking courses on edX, or what you hope to learn.',
editable: 'toggle',
persistChanges: true,
messagePosition: 'header'
@@ -322,7 +312,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.fieldValue()).toBe(fieldData.placeholderValue);
});
- it("correctly renders LinkFieldView", function() {
+ it('correctly renders LinkFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
title: 'Title',
linkTitle: 'Link title',
@@ -335,7 +325,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$('.u-field-value > a .u-field-link-title-' + view.options.valueAttribute).text().trim()).toBe(fieldData.linkTitle);
});
- it("correctly renders LinkFieldView", function() {
+ it('correctly renders LinkFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
title: 'Title',
linkTitle: 'Link title',
diff --git a/lms/static/js/spec/views/file_uploader_spec.js b/lms/static/js/spec/views/file_uploader_spec.js
index c530163583..14203e9717 100644
--- a/lms/static/js/spec/views/file_uploader_spec.js
+++ b/lms/static/js/spec/views/file_uploader_spec.js
@@ -1,24 +1,24 @@
define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/template_helpers',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/models/notification', 'string_utils'],
- function (Backbone, $, FileUploaderView, TemplateHelpers, AjaxHelpers, NotificationModel) {
- describe("FileUploaderView", function () {
+ function(Backbone, $, FileUploaderView, TemplateHelpers, AjaxHelpers, NotificationModel) {
+ describe('FileUploaderView', function() {
var verifyTitle, verifyInputLabel, verifyInputTip, verifySubmitButton, verifyExtensions, verifyText,
verifyFileUploadOption, verifyNotificationMessage, verifySubmitButtonEnabled, mimicUpload,
- respondWithSuccess, respondWithError, fileUploaderView, url="http://test_url/";
+ respondWithSuccess, respondWithError, fileUploaderView, url = 'http://test_url/';
- verifyText = function (css, expectedText) {
+ verifyText = function(css, expectedText) {
expect(fileUploaderView.$(css).text().trim()).toBe(expectedText);
};
- verifyTitle = function (expectedTitle) { verifyText('.form-title', expectedTitle); };
+ verifyTitle = function(expectedTitle) { verifyText('.form-title', expectedTitle); };
- verifyInputLabel = function (expectedLabel) { verifyText('.field-label', expectedLabel); };
+ verifyInputLabel = function(expectedLabel) { verifyText('.field-label', expectedLabel); };
- verifyInputTip = function (expectedTip) { verifyText('.tip', expectedTip); };
+ verifyInputTip = function(expectedTip) { verifyText('.tip', expectedTip); };
- verifySubmitButton = function (expectedButton) { verifyText('.submit-file-button', expectedButton); };
+ verifySubmitButton = function(expectedButton) { verifyText('.submit-file-button', expectedButton); };
- verifyExtensions = function (expectedExtensions) {
+ verifyExtensions = function(expectedExtensions) {
var acceptAttribute = fileUploaderView.$('input.input-file').attr('accept');
if (expectedExtensions) {
expect(acceptAttribute).toBe(expectedExtensions);
@@ -28,25 +28,25 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
}
};
- verifySubmitButtonEnabled = function (expectedEnabled) {
+ verifySubmitButtonEnabled = function(expectedEnabled) {
var submitButton = fileUploaderView.$('.submit-file-button');
if (expectedEnabled) {
- expect(submitButton).not.toHaveClass("is-disabled");
+ expect(submitButton).not.toHaveClass('is-disabled');
}
else {
- expect(submitButton).toHaveClass("is-disabled");
+ expect(submitButton).toHaveClass('is-disabled');
}
};
- verifyFileUploadOption = function (option, expectedValue) {
+ verifyFileUploadOption = function(option, expectedValue) {
expect(fileUploaderView.$('#file-upload-form').fileupload('option', option)).toBe(expectedValue);
};
- verifyNotificationMessage = function (expectedMessage, type) {
+ verifyNotificationMessage = function(expectedMessage, type) {
verifyText('.file-upload-form-result .message-' + type + ' .message-title', expectedMessage);
};
- mimicUpload = function (test) {
+ mimicUpload = function(test) {
var requests = AjaxHelpers.requests(test);
var param = {files: [{name: 'upload_file.txt'}]};
@@ -59,11 +59,11 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
return requests;
};
- respondWithSuccess = function (requests) {
+ respondWithSuccess = function(requests) {
AjaxHelpers.respondWithJson(requests, {});
};
- respondWithError = function (requests, errorMessage) {
+ respondWithError = function(requests, errorMessage) {
if (errorMessage) {
AjaxHelpers.respondWithError(requests, 500, {error: errorMessage});
}
@@ -72,98 +72,98 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
}
};
- beforeEach(function () {
- setFixtures("
");
+ beforeEach(function() {
+ setFixtures('
');
TemplateHelpers.installTemplate('templates/file-upload');
TemplateHelpers.installTemplate('templates/instructor/instructor_dashboard_2/notification');
fileUploaderView = new FileUploaderView({url: url}).render();
});
- it('has default values', function () {
- verifyTitle("");
- verifyInputLabel("");
- verifyInputTip("");
- verifySubmitButton("Upload File");
+ it('has default values', function() {
+ verifyTitle('');
+ verifyInputLabel('');
+ verifyInputTip('');
+ verifySubmitButton('Upload File');
verifyExtensions(null);
verifySubmitButtonEnabled(false);
});
- it ('can set text values and extensions', function () {
+ it('can set text values and extensions', function() {
fileUploaderView = new FileUploaderView({
- title: "file upload title",
- inputLabel: "test label",
- inputTip: "test tip",
- submitButtonText: "upload button text",
- extensions: ".csv,.txt"
+ title: 'file upload title',
+ inputLabel: 'test label',
+ inputTip: 'test tip',
+ submitButtonText: 'upload button text',
+ extensions: '.csv,.txt'
}).render();
- verifyTitle("file upload title");
- verifyInputLabel("test label");
- verifyInputTip("test tip");
- verifySubmitButton("upload button text");
- verifyExtensions(".csv,.txt");
+ verifyTitle('file upload title');
+ verifyInputLabel('test label');
+ verifyInputTip('test tip');
+ verifySubmitButton('upload button text');
+ verifyExtensions('.csv,.txt');
});
- it ('can store upload URL', function () {
+ it('can store upload URL', function() {
expect(fileUploaderView.$('#file-upload-form').attr('action')).toBe(url);
});
- it ('sets autoUpload to false', function () {
+ it('sets autoUpload to false', function() {
verifyFileUploadOption('autoUpload', false);
});
- it ('sets replaceFileInput to false', function () {
+ it('sets replaceFileInput to false', function() {
verifyFileUploadOption('replaceFileInput', false);
});
- it ('handles errors with default message', function () {
+ it('handles errors with default message', function() {
var requests = mimicUpload(this);
respondWithError(requests);
- verifyNotificationMessage("Your upload of 'upload_file.txt' failed.", "error");
+ verifyNotificationMessage("Your upload of 'upload_file.txt' failed.", 'error');
});
- it ('handles errors with custom message', function () {
+ it('handles errors with custom message', function() {
fileUploaderView = new FileUploaderView({
url: url,
- errorNotification: function (file, event, data) {
+ errorNotification: function(file, event, data) {
var message = interpolate_text("Custom error for '{file}'", {file: file});
return new NotificationModel({
- type: "customized",
+ type: 'customized',
title: message
});
}
}).render();
var requests = mimicUpload(this);
- respondWithError(requests, "server error");
- verifyNotificationMessage("Custom error for 'upload_file.txt'", "customized");
+ respondWithError(requests, 'server error');
+ verifyNotificationMessage("Custom error for 'upload_file.txt'", 'customized');
});
- it ('handles server error message', function () {
+ it('handles server error message', function() {
var requests = mimicUpload(this);
- respondWithError(requests, "server error");
- verifyNotificationMessage("server error", "error");
+ respondWithError(requests, 'server error');
+ verifyNotificationMessage('server error', 'error');
});
- it ('handles success with default message', function () {
+ it('handles success with default message', function() {
var requests = mimicUpload(this);
respondWithSuccess(requests);
- verifyNotificationMessage("Your upload of 'upload_file.txt' succeeded.", "confirmation");
+ verifyNotificationMessage("Your upload of 'upload_file.txt' succeeded.", 'confirmation');
});
- it ('handles success with custom message', function () {
+ it('handles success with custom message', function() {
fileUploaderView = new FileUploaderView({
url: url,
- successNotification: function (file, event, data) {
+ successNotification: function(file, event, data) {
var message = interpolate_text("Custom success message for '{file}'", {file: file});
return new NotificationModel({
- type: "customized",
+ type: 'customized',
title: message
});
}
}).render();
var requests = mimicUpload(this);
respondWithSuccess(requests);
- verifyNotificationMessage("Custom success message for 'upload_file.txt'", "customized");
+ verifyNotificationMessage("Custom success message for 'upload_file.txt'", 'customized');
});
});
});
diff --git a/lms/static/js/spec/views/message_banner_spec.js b/lms/static/js/spec/views/message_banner_spec.js
index 109902aace..cdbf01bdfe 100644
--- a/lms/static/js/spec/views/message_banner_spec.js
+++ b/lms/static/js/spec/views/message_banner_spec.js
@@ -1,14 +1,13 @@
define(['backbone', 'jquery', 'underscore',
'common/js/spec_helpers/template_helpers', 'js/views/message_banner'
],
- function (Backbone, $, _, TemplateHelpers, MessageBannerView) {
+ function(Backbone, $, _, TemplateHelpers, MessageBannerView) {
'use strict';
- describe("MessageBannerView", function () {
-
- beforeEach(function () {
+ describe('MessageBannerView', function() {
+ beforeEach(function() {
setFixtures('
');
- TemplateHelpers.installTemplate("templates/fields/message_banner");
+ TemplateHelpers.installTemplate('templates/fields/message_banner');
});
it('renders message correctly', function() {
diff --git a/lms/static/js/spec/views/notification_spec.js b/lms/static/js/spec/views/notification_spec.js
index 6c6fe45d10..78838be8df 100644
--- a/lms/static/js/spec/views/notification_spec.js
+++ b/lms/static/js/spec/views/notification_spec.js
@@ -1,9 +1,9 @@
define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification', 'common/js/spec_helpers/template_helpers'],
- function (Backbone, $, NotificationModel, NotificationView, TemplateHelpers) {
- describe("NotificationView", function () {
+ function(Backbone, $, NotificationModel, NotificationView, TemplateHelpers) {
+ describe('NotificationView', function() {
var createNotification, verifyTitle, verifyMessage, verifyDetails, verifyAction, notificationView;
- createNotification = function (modelVals) {
+ createNotification = function(modelVals) {
var notificationModel = new NotificationModel(modelVals);
notificationView = new NotificationView({
model: notificationModel
@@ -12,23 +12,23 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
return notificationView;
};
- verifyTitle = function (expectedTitle) {
+ verifyTitle = function(expectedTitle) {
expect(notificationView.$('.message-title').text().trim()).toBe(expectedTitle);
};
- verifyMessage = function (expectedMessage) {
+ verifyMessage = function(expectedMessage) {
expect(notificationView.$('.message-copy').text().trim()).toBe(expectedMessage);
};
- verifyDetails = function (expectedDetails) {
+ verifyDetails = function(expectedDetails) {
var details = notificationView.$('.summary-item');
expect(details.length).toBe(expectedDetails.length);
- details.each(function (index) {
- expect($(this).text().trim()).toBe(expectedDetails[index]);
+ details.each(function(index) {
+ expect($(this).text().trim()).toBe(expectedDetails[index]);
});
};
- verifyAction = function (expectedActionText) {
+ verifyAction = function(expectedActionText) {
var actionButton = notificationView.$('.action-primary');
if (expectedActionText) {
expect(actionButton.text().trim()).toBe(expectedActionText);
@@ -38,12 +38,12 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
}
};
- beforeEach(function () {
- setFixtures("
");
+ beforeEach(function() {
+ setFixtures('
');
TemplateHelpers.installTemplate('templates/instructor/instructor_dashboard_2/notification');
});
- it('has default values', function () {
+ it('has default values', function() {
createNotification({});
expect(notificationView.$('div.message')).toHaveClass('message-confirmation');
verifyTitle('');
@@ -51,44 +51,44 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
verifyAction(null);
});
- it('can use an error type', function () {
+ it('can use an error type', function() {
createNotification({type: 'error'});
expect(notificationView.$('div.message')).toHaveClass('message-error');
expect(notificationView.$('div.message')).not.toHaveClass('message-confirmation');
});
- it('can specify a title', function () {
+ it('can specify a title', function() {
createNotification({title: 'notification title'});
verifyTitle('notification title');
});
- it('can specify a message', function () {
+ it('can specify a message', function() {
createNotification({message: 'This is a dummy message'});
verifyMessage('This is a dummy message');
});
- it('can specify details', function () {
+ it('can specify details', function() {
var expectedDetails = ['detail 1', 'detail 2'];
createNotification({details: expectedDetails});
verifyDetails(expectedDetails);
});
- it ('shows an action button if text and callback are provided', function () {
- createNotification({actionText: 'action text', actionCallback: function () {}});
+ it('shows an action button if text and callback are provided', function() {
+ createNotification({actionText: 'action text', actionCallback: function() {}});
verifyAction('action text');
});
- it ('shows an action button if only text is provided', function () {
+ it('shows an action button if only text is provided', function() {
createNotification({actionText: 'action text'});
verifyAction('action text');
});
- it ('does not show an action button if text is not provided', function () {
- createNotification({actionCallback: function () {}});
+ it('does not show an action button if text is not provided', function() {
+ createNotification({actionCallback: function() {}});
verifyAction(null);
});
- it ('triggers the callback when the action button is clicked', function () {
+ it('triggers the callback when the action button is clicked', function() {
var actionCallback = jasmine.createSpy('Spy on callback');
var view = createNotification({actionText: 'action text', actionCallback: actionCallback});
notificationView.$('button.action-primary').click();
diff --git a/lms/static/js/split.js b/lms/static/js/split.js
index 50a3bbde07..e6d2714ba3 100644
--- a/lms/static/js/split.js
+++ b/lms/static/js/split.js
@@ -33,30 +33,29 @@
var _split; // instead of split for a less common name; avoid conflict
// Avoid running twice; that would break the `nativeSplit` reference
-_split = _split || function (undef) {
-
+_split = _split || function(undef) {
var nativeSplit = String.prototype.split,
- compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group
+ compliantExecNpcg = /()??/.exec('')[1] === undef, // NPCG: nonparticipating capturing group
self;
- self = function (str, separator, limit) {
+ self = function(str, separator, limit) {
// If `separator` is not a regex, use `nativeSplit`
- if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
+ if (Object.prototype.toString.call(separator) !== '[object RegExp]') {
return nativeSplit.call(str, separator, limit);
}
var output = [],
- flags = (separator.ignoreCase ? "i" : "") +
- (separator.multiline ? "m" : "") +
- (separator.extended ? "x" : "") + // Proposed for ES6
- (separator.sticky ? "y" : ""), // Firefox 3+
+ flags = (separator.ignoreCase ? 'i' : '') +
+ (separator.multiline ? 'm' : '') +
+ (separator.extended ? 'x' : '') + // Proposed for ES6
+ (separator.sticky ? 'y' : ''), // Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
- separator = new RegExp(separator.source, flags + "g"),
+ separator = new RegExp(separator.source, flags + 'g'),
separator2, match, lastIndex, lastLength;
- str += ""; // Type-convert
+ str += ''; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
- separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
+ separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
@@ -76,7 +75,7 @@ _split = _split || function (undef) {
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
- match[0].replace(separator2, function () {
+ match[0].replace(separator2, function() {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undef) {
match[i] = undef;
@@ -98,8 +97,8 @@ _split = _split || function (undef) {
}
}
if (lastLastIndex === str.length) {
- if (lastLength || !separator.test("")) {
- output.push("");
+ if (lastLength || !separator.test('')) {
+ output.push('');
}
} else {
output.push(str.slice(lastLastIndex));
@@ -108,11 +107,10 @@ _split = _split || function (undef) {
};
// For convenience
- String.prototype.split = function (separator, limit) {
+ String.prototype.split = function(separator, limit) {
return self(this, separator, limit);
};
- return self;
-
+ return self;
}();
diff --git a/lms/static/js/staff_debug_actions.js b/lms/static/js/staff_debug_actions.js
index ef77a416cf..b7ae3705ce 100644
--- a/lms/static/js/staff_debug_actions.js
+++ b/lms/static/js/staff_debug_actions.js
@@ -1,128 +1,125 @@
// Build StaffDebug object
-var StaffDebug = (function (){
-
- get_current_url = function() {
- return window.location.pathname;
- };
-
- get_url = function(action){
- var pathname = this.get_current_url();
- var url = pathname.substr(0,pathname.indexOf('/courseware')) + '/instructor/api/' + action;
- return url;
- };
-
- sanitized_string = function(string) {
- return string.replace(/[.*+?^:${}()|[\]\\]/g, "\\$&");
- };
-
- get_user = function(locname){
- locname = sanitized_string(locname);
- var uname = $('#sd_fu_' + locname).val();
- if (uname===""){
- uname = $('#sd_fu_' + locname).attr('placeholder');
- }
- return uname;
- };
-
- do_idash_action = function(action){
- var pdata = {
- 'problem_to_reset': action.location,
- 'unique_student_identifier': get_user(action.locationName),
- 'delete_module': action.delete_module
+var StaffDebug = (function() {
+ get_current_url = function() {
+ return window.location.pathname;
};
- $.ajax({
- type: "POST",
- url: get_url(action.method),
- data: pdata,
- success: function(data){
- var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
+
+ get_url = function(action) {
+ var pathname = this.get_current_url();
+ var url = pathname.substr(0, pathname.indexOf('/courseware')) + '/instructor/api/' + action;
+ return url;
+ };
+
+ sanitized_string = function(string) {
+ return string.replace(/[.*+?^:${}()|[\]\\]/g, '\\$&');
+ };
+
+ get_user = function(locname) {
+ locname = sanitized_string(locname);
+ var uname = $('#sd_fu_' + locname).val();
+ if (uname === '') {
+ uname = $('#sd_fu_' + locname).attr('placeholder');
+ }
+ return uname;
+ };
+
+ do_idash_action = function(action) {
+ var pdata = {
+ 'problem_to_reset': action.location,
+ 'unique_student_identifier': get_user(action.locationName),
+ 'delete_module': action.delete_module
+ };
+ $.ajax({
+ type: 'POST',
+ url: get_url(action.method),
+ data: pdata,
+ success: function(data) {
+ var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
{user: data.student}
);
- var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
+ var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
{text: text}
);
- $("#result_"+sanitized_string(action.locationName)).html(html);
- },
- error: function(request, status, error) {
- var response_json;
- try {
- response_json = $.parseJSON(request.responseText);
- } catch(e) {
- response_json = { error: gettext('Unknown Error Occurred.') };
- }
- var text = _.template('{error_msg} {error}', {interpolate: /\{(.+?)\}/g})(
- {
- error_msg: action.error_msg,
- error: response_json.error
+ $('#result_' + sanitized_string(action.locationName)).html(html);
+ },
+ error: function(request, status, error) {
+ var response_json;
+ try {
+ response_json = $.parseJSON(request.responseText);
+ } catch (e) {
+ response_json = {error: gettext('Unknown Error Occurred.')};
}
+ var text = _.template('{error_msg} {error}', {interpolate: /\{(.+?)\}/g})(
+ {
+ error_msg: action.error_msg,
+ error: response_json.error
+ }
);
- var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
+ var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
{text: text}
);
- $("#result_"+sanitized_string(action.locationName)).html(html);
+ $('#result_' + sanitized_string(action.locationName)).html(html);
+ },
+ dataType: 'json'
+ });
+ };
- },
- dataType: 'json'
- });
- };
+ reset = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'reset_student_attempts',
+ success_msg: gettext('Successfully reset the attempts for user {user}'),
+ error_msg: gettext('Failed to reset attempts.'),
+ delete_module: false
+ });
+ };
- reset = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'reset_student_attempts',
- success_msg: gettext('Successfully reset the attempts for user {user}'),
- error_msg: gettext('Failed to reset attempts.'),
- delete_module: false
- });
- };
+ sdelete = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'reset_student_attempts',
+ success_msg: gettext('Successfully deleted student state for user {user}'),
+ error_msg: gettext('Failed to delete student state.'),
+ delete_module: true
+ });
+ };
- sdelete = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'reset_student_attempts',
- success_msg: gettext('Successfully deleted student state for user {user}'),
- error_msg: gettext('Failed to delete student state.'),
- delete_module: true
- });
- };
+ rescore = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'rescore_problem',
+ success_msg: gettext('Successfully rescored problem for user {user}'),
+ error_msg: gettext('Failed to rescore problem.'),
+ delete_module: false
+ });
+ };
- rescore = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'rescore_problem',
- success_msg: gettext('Successfully rescored problem for user {user}'),
- error_msg: gettext('Failed to rescore problem.'),
- delete_module: false
- });
- };
-
- return {
- reset: reset,
- sdelete: sdelete,
- rescore: rescore,
- do_idash_action: do_idash_action,
- get_current_url: get_current_url,
- get_url: get_url,
- get_user: get_user,
- sanitized_string:sanitized_string
- }; })();
+ return {
+ reset: reset,
+ sdelete: sdelete,
+ rescore: rescore,
+ do_idash_action: do_idash_action,
+ get_current_url: get_current_url,
+ get_url: get_url,
+ get_user: get_user,
+ sanitized_string: sanitized_string
+ }; })();
// Register click handlers
$(document).ready(function() {
-
var $courseContent = $('.course-content');
- $courseContent.on("click", '.staff-debug-reset', function() {
+ $courseContent.on('click', '.staff-debug-reset', function() {
StaffDebug.reset($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
- $courseContent.on("click", '.staff-debug-sdelete', function() {
+ $courseContent.on('click', '.staff-debug-sdelete', function() {
StaffDebug.sdelete($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
- $courseContent.on("click", '.staff-debug-rescore', function() {
+ $courseContent.on('click', '.staff-debug-rescore', function() {
StaffDebug.rescore($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
diff --git a/lms/static/js/sticky_filter.js b/lms/static/js/sticky_filter.js
index 895f024eb2..cb112e17d9 100644
--- a/lms/static/js/sticky_filter.js
+++ b/lms/static/js/sticky_filter.js
@@ -1,14 +1,14 @@
$(function() {
- if ($('.filter nav').length > 0) {
- var offset = $('.filter nav').offset().top;
+ if ($('.filter nav').length > 0) {
+ var offset = $('.filter nav').offset().top;
- $(window).scroll(function() {
- if (offset <= window.pageYOffset) {
- return $('.filter nav').addClass('fixed-top');
- }
- else if (offset >= window.pageYOffset) {
- return $('.filter nav').removeClass('fixed-top');
- }
- });
- }
+ $(window).scroll(function() {
+ if (offset <= window.pageYOffset) {
+ return $('.filter nav').addClass('fixed-top');
+ }
+ else if (offset >= window.pageYOffset) {
+ return $('.filter nav').removeClass('fixed-top');
+ }
+ });
+ }
});
diff --git a/lms/static/js/student_account/account.js b/lms/static/js/student_account/account.js
index e05339663d..89d5c4c759 100644
--- a/lms/static/js/student_account/account.js
+++ b/lms/static/js/student_account/account.js
@@ -44,7 +44,7 @@ var edx = edx || {};
model.trigger('sync');
})
.fail(function() {
- var error = gettext("The data could not be saved.");
+ var error = gettext('The data could not be saved.');
model.trigger('error', error);
});
},
@@ -55,10 +55,10 @@ var edx = edx || {};
if (attrs.email.length < this.EMAIL_MIN_LENGTH ||
attrs.email.length > this.EMAIL_MAX_LENGTH ||
!this.EMAIL_REGEX.test(attrs.email)
- ) { errors.email = gettext("Please enter a valid email address"); }
+ ) { errors.email = gettext('Please enter a valid email address'); }
if (attrs.password.length < this.PASSWORD_MIN_LENGTH || attrs.password.length > this.PASSWORD_MAX_LENGTH) {
- errors.password = gettext("Please enter a valid password");
+ errors.password = gettext('Please enter a valid password');
}
if (!$.isEmptyObject(errors)) {
@@ -125,7 +125,7 @@ var edx = edx || {};
.done(function() {
self.$passwordResetStatus
.addClass('success')
- .text(gettext("Password reset email sent. Follow the link in the email to change your password."));
+ .text(gettext('Password reset email sent. Follow the link in the email to change your password.'));
})
.fail(function() {
self.$passwordResetStatus
@@ -159,25 +159,25 @@ var edx = edx || {};
sync: function() {
this.$requestStatus
.addClass('success')
- .text(gettext("Please check your email to confirm the change"));
+ .text(gettext('Please check your email to confirm the change'));
},
clearStatus: function() {
this.$emailStatus
.removeClass('validation-error')
- .text("");
+ .text('');
this.$passwordStatus
.removeClass('validation-error')
- .text("");
+ .text('');
this.$requestStatus
.removeClass('error')
- .text("");
+ .text('');
this.$passwordResetStatus
.removeClass('error')
- .text("");
+ .text('');
}
});
@@ -188,5 +188,4 @@ var edx = edx || {};
} catch (e) {
// TODO: handle exception
}
-
})(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/student_account/emailoptin.js b/lms/static/js/student_account/emailoptin.js
index 20b6d9b306..df0240f4c5 100644
--- a/lms/static/js/student_account/emailoptin.js
+++ b/lms/static/js/student_account/emailoptin.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var EmailOptInInterface = {
urls: {
@@ -18,7 +17,7 @@
* @param {string} courseKey Slash-separated course key.
* @param {string} emailOptIn The preference to opt in or out of organization emails.
*/
- setPreference: function( courseKey, emailOptIn ) {
+ setPreference: function(courseKey, emailOptIn) {
return $.ajax({
url: this.urls.emailOptInUrl,
type: 'POST',
diff --git a/lms/static/js/student_account/enrollment.js b/lms/static/js/student_account/enrollment.js
index ecd668f1ae..596fa3e373 100644
--- a/lms/static/js/student_account/enrollment.js
+++ b/lms/static/js/student_account/enrollment.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var EnrollmentInterface = {
urls: {
- baskets: '/api/commerce/v0/baskets/',
+ baskets: '/api/commerce/v0/baskets/'
},
headers: {
@@ -17,7 +16,7 @@
* @param {string} courseKey Slash-separated course key.
* @param {string} redirectUrl The URL to redirect to once enrollment completes.
*/
- enroll: function( courseKey, redirectUrl ) {
+ enroll: function(courseKey, redirectUrl) {
var data_obj = {course_id: courseKey},
data = JSON.stringify(data_obj);
@@ -28,25 +27,25 @@
data: data,
headers: this.headers,
context: this
- }).fail(function( jqXHR ) {
+ }).fail(function(jqXHR) {
var responseData = JSON.parse(jqXHR.responseText);
- if ( jqXHR.status === 403 && responseData.user_message_url ) {
+ if (jqXHR.status === 403 && responseData.user_message_url) {
// Check if we've been blocked from the course
// because of country access rules.
// If so, redirect to a page explaining to the user
// why they were blocked.
- this.redirect( responseData.user_message_url );
+ this.redirect(responseData.user_message_url);
} else {
// Otherwise, redirect the user to the next page.
- if ( redirectUrl ) {
- this.redirect( redirectUrl );
+ if (redirectUrl) {
+ this.redirect(redirectUrl);
}
}
}).done(function() {
// If we successfully enrolled, redirect the user
// to the next page (usually the student dashboard or payment flow)
- if ( redirectUrl ) {
- this.redirect( redirectUrl );
+ if (redirectUrl) {
+ this.redirect(redirectUrl);
}
});
},
diff --git a/lms/static/js/student_account/logistration_factory.js b/lms/static/js/student_account/logistration_factory.js
index 88ec6b1fba..f79ea9994f 100644
--- a/lms/static/js/student_account/logistration_factory.js
+++ b/lms/static/js/student_account/logistration_factory.js
@@ -1,9 +1,9 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'js/student_account/views/AccessView'
- ],
+ 'jquery',
+ 'js/student_account/views/AccessView'
+ ],
function($, AccessView) {
return function(options) {
var $logistrationElement = $('#login-and-registration-container');
diff --git a/lms/static/js/student_account/models/LoginModel.js b/lms/static/js/student_account/models/LoginModel.js
index 6fcce3774d..1d2eb9df6f 100644
--- a/lms/static/js/student_account/models/LoginModel.js
+++ b/lms/static/js/student_account/models/LoginModel.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'jquery',
'backbone',
'jquery.url'
- ], function ($, Backbone) {
-
+ ], function($, Backbone) {
return Backbone.Model.extend({
defaults: {
email: '',
@@ -16,12 +15,12 @@
ajaxType: '',
urlRoot: '',
- initialize: function (attributes, options) {
+ initialize: function(attributes, options) {
this.ajaxType = options.method;
this.urlRoot = options.url;
},
- sync: function (method, model) {
+ sync: function(method, model) {
var headers = {'X-CSRFToken': $.cookie('csrftoken')},
data = {},
analytics,
@@ -44,10 +43,10 @@
type: model.ajaxType,
data: data,
headers: headers,
- success: function () {
+ success: function() {
model.trigger('sync');
},
- error: function (error) {
+ error: function(error) {
model.trigger('error', error);
}
});
diff --git a/lms/static/js/student_account/models/PasswordResetModel.js b/lms/static/js/student_account/models/PasswordResetModel.js
index a6ebf0b97d..2e127be7d9 100644
--- a/lms/static/js/student_account/models/PasswordResetModel.js
+++ b/lms/static/js/student_account/models/PasswordResetModel.js
@@ -1,39 +1,38 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'backbone'],
function($, Backbone) {
+ return Backbone.Model.extend({
+ defaults: {
+ email: ''
+ },
+ ajaxType: '',
+ urlRoot: '',
- return Backbone.Model.extend({
- defaults: {
- email: ''
- },
- ajaxType: '',
- urlRoot: '',
+ initialize: function(attributes, options) {
+ this.ajaxType = options.method;
+ this.urlRoot = options.url;
+ },
- initialize: function( attributes, options ) {
- this.ajaxType = options.method;
- this.urlRoot = options.url;
- },
-
- sync: function( method, model ) {
- var headers = {
- 'X-CSRFToken': $.cookie('csrftoken')
- };
+ sync: function(method, model) {
+ var headers = {
+ 'X-CSRFToken': $.cookie('csrftoken')
+ };
// Only expects an email address.
- $.ajax({
- url: model.urlRoot,
- type: model.ajaxType,
- data: model.attributes,
- headers: headers,
- success: function() {
- model.trigger('sync');
- },
- error: function( error ) {
- model.trigger('error', error);
- }
- });
- }
+ $.ajax({
+ url: model.urlRoot,
+ type: model.ajaxType,
+ data: model.attributes,
+ headers: headers,
+ success: function() {
+ model.trigger('sync');
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/models/RegisterModel.js b/lms/static/js/student_account/models/RegisterModel.js
index fa30beb1ef..136f429191 100644
--- a/lms/static/js/student_account/models/RegisterModel.js
+++ b/lms/static/js/student_account/models/RegisterModel.js
@@ -1,56 +1,55 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'backbone', 'jquery.url'],
function($, Backbone) {
+ return Backbone.Model.extend({
+ defaults: {
+ email: '',
+ name: '',
+ username: '',
+ password: '',
+ level_of_education: '',
+ gender: '',
+ year_of_birth: '',
+ mailing_address: '',
+ goals: ''
+ },
+ ajaxType: '',
+ urlRoot: '',
- return Backbone.Model.extend({
- defaults: {
- email: '',
- name: '',
- username: '',
- password: '',
- level_of_education: '',
- gender: '',
- year_of_birth: '',
- mailing_address: '',
- goals: ''
- },
- ajaxType: '',
- urlRoot: '',
+ initialize: function(attributes, options) {
+ this.ajaxType = options.method;
+ this.urlRoot = options.url;
+ },
- initialize: function( attributes, options ) {
- this.ajaxType = options.method;
- this.urlRoot = options.url;
- },
-
- sync: function(method, model) {
- var headers = { 'X-CSRFToken': $.cookie('csrftoken') },
- data = {},
- courseId = $.url( '?course_id' );
+ sync: function(method, model) {
+ var headers = {'X-CSRFToken': $.cookie('csrftoken')},
+ data = {},
+ courseId = $.url('?course_id');
// If there is a course ID in the query string param,
// send that to the server as well so it can be included
// in analytics events.
- if ( courseId ) {
- data.course_id = decodeURIComponent(courseId);
- }
+ if (courseId) {
+ data.course_id = decodeURIComponent(courseId);
+ }
// Include all form fields and analytics info in the data sent to the server
- $.extend( data, model.attributes);
+ $.extend(data, model.attributes);
- $.ajax({
- url: model.urlRoot,
- type: model.ajaxType,
- data: data,
- headers: headers,
- success: function() {
- model.trigger('sync');
- },
- error: function( error ) {
- model.trigger('error', error);
- }
- });
- }
+ $.ajax({
+ url: model.urlRoot,
+ type: model.ajaxType,
+ data: data,
+ headers: headers,
+ success: function() {
+ model.trigger('sync');
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/models/user_account_model.js b/lms/static/js/student_account/models/user_account_model.js
index 1bc98aa01c..4f9293b92f 100644
--- a/lms/static/js/student_account/models/user_account_model.js
+++ b/lms/static/js/student_account/models/user_account_model.js
@@ -1,9 +1,8 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'underscore', 'backbone'
- ], function (gettext, _, Backbone) {
-
+ ], function(gettext, _, Backbone) {
var UserAccountModel = Backbone.Model.extend({
idAttribute: 'username',
defaults: {
@@ -13,11 +12,11 @@
password: '',
language: null,
country: null,
- date_joined: "",
+ date_joined: '',
gender: null,
- goals: "",
+ goals: '',
level_of_education: null,
- mailing_address: "",
+ mailing_address: '',
year_of_birth: null,
bio: null,
language_proficiencies: [],
@@ -27,7 +26,7 @@
default_public_account_fields: []
},
- parse : function(response) {
+ parse: function(response) {
if (_.isNull(response) || _.isUndefined(response)) {
return {};
}
@@ -35,28 +34,28 @@
// Currently when a non-staff user A access user B's profile, the only way to tell whether user B's
// profile is public is to check if the api has returned fields other than the default public fields
// specified in settings.ACCOUNT_VISIBILITY_CONFIGURATION.
- var responseKeys = _.filter(_.keys(response), function (key) {
- return key !== 'default_public_account_fields';
+ var responseKeys = _.filter(_.keys(response), function(key) {
+ return key !== 'default_public_account_fields';
});
-
+
var isPublic = _.size(_.difference(responseKeys, response.default_public_account_fields)) > 0;
response.profile_is_public = isPublic;
return response;
},
- hasProfileImage: function () {
+ hasProfileImage: function() {
var profile_image = this.get('profile_image');
return (_.isObject(profile_image) && profile_image.has_image === true);
},
- profileImageUrl: function () {
+ profileImageUrl: function() {
return this.get('profile_image').image_url_large;
},
isAboveMinimumAge: function() {
var yearOfBirth = this.get('year_of_birth');
var isBirthDefined = !(_.isUndefined(yearOfBirth) || _.isNull(yearOfBirth));
- return isBirthDefined && !(this.get("requires_parental_consent"));
+ return isBirthDefined && !(this.get('requires_parental_consent'));
}
});
return UserAccountModel;
diff --git a/lms/static/js/student_account/models/user_preferences_model.js b/lms/static/js/student_account/models/user_preferences_model.js
index af421013b3..212d05ca8e 100644
--- a/lms/static/js/student_account/models/user_preferences_model.js
+++ b/lms/static/js/student_account/models/user_preferences_model.js
@@ -1,9 +1,8 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'underscore', 'backbone'
- ], function (gettext, _, Backbone) {
-
+ ], function(gettext, _, Backbone) {
var UserPreferencesModel = Backbone.Model.extend({
idAttribute: 'account_privacy',
defaults: {
diff --git a/lms/static/js/student_account/password_reset.js b/lms/static/js/student_account/password_reset.js
index 9733909315..e26448b4ae 100644
--- a/lms/static/js/student_account/password_reset.js
+++ b/lms/static/js/student_account/password_reset.js
@@ -4,12 +4,12 @@
$(function() {
'use strict';
// adding js class for styling with accessibility in mind
- $("body").addClass("js");
+ $('body').addClass('js');
// form field label styling on focus
- $("form :input").focus(function() {
- $("label[for='" + this.id + "']").parent().addClass("is-focused");
+ $('form :input').focus(function() {
+ $("label[for='" + this.id + "']").parent().addClass('is-focused');
}).blur(function() {
- $("label").parent().removeClass("is-focused");
+ $('label').parent().removeClass('is-focused');
});
});
diff --git a/lms/static/js/student_account/shoppingcart.js b/lms/static/js/student_account/shoppingcart.js
index 36af44f3ee..8dd218ad66 100644
--- a/lms/static/js/student_account/shoppingcart.js
+++ b/lms/static/js/student_account/shoppingcart.js
@@ -1,14 +1,13 @@
/**
* Use the shopping cart to purchase courses.
*/
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var ShoppingCartInterface = {
urls: {
- viewCart: "/shoppingcart/",
- addCourse: "/shoppingcart/add/course/"
+ viewCart: '/shoppingcart/',
+ addCourse: '/shoppingcart/add/course/'
},
headers: {
@@ -19,15 +18,15 @@
* Add a course to a cart, then redirect to the view cart page.
* @param {string} courseId The slash-separated course ID to add to the cart.
*/
- addCourseToCart: function( courseId ) {
+ addCourseToCart: function(courseId) {
$.ajax({
- url: this.urls.addCourse + courseId + "/",
+ url: this.urls.addCourse + courseId + '/',
type: 'POST',
data: {},
headers: this.headers,
context: this
}).always(function() {
- this.redirect( this.urls.viewCart );
+ this.redirect(this.urls.viewCart);
});
},
@@ -35,7 +34,7 @@
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
+ redirect: function(url) {
window.location.href = url;
}
};
diff --git a/lms/static/js/student_account/views/AccessView.js b/lms/static/js/student_account/views/AccessView.js
index b18edaacc9..40ef26aaf7 100644
--- a/lms/static/js/student_account/views/AccessView.js
+++ b/lms/static/js/student_account/views/AccessView.js
@@ -1,242 +1,238 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'utility',
- 'underscore',
- 'underscore.string',
- 'backbone',
- 'js/student_account/models/LoginModel',
- 'js/student_account/models/PasswordResetModel',
- 'js/student_account/models/RegisterModel',
- 'js/student_account/views/LoginView',
- 'js/student_account/views/PasswordResetView',
- 'js/student_account/views/RegisterView',
- 'js/student_account/views/InstitutionLoginView',
- 'js/student_account/views/HintedLoginView',
- 'js/vendor/history'
- ],
+ 'jquery',
+ 'utility',
+ 'underscore',
+ 'underscore.string',
+ 'backbone',
+ 'js/student_account/models/LoginModel',
+ 'js/student_account/models/PasswordResetModel',
+ 'js/student_account/models/RegisterModel',
+ 'js/student_account/views/LoginView',
+ 'js/student_account/views/PasswordResetView',
+ 'js/student_account/views/RegisterView',
+ 'js/student_account/views/InstitutionLoginView',
+ 'js/student_account/views/HintedLoginView',
+ 'js/vendor/history'
+ ],
function($, utility, _, _s, Backbone, LoginModel, PasswordResetModel, RegisterModel, LoginView,
PasswordResetView, RegisterView, InstitutionLoginView, HintedLoginView) {
-
- return Backbone.View.extend({
- tpl: '#access-tpl',
- events: {
- 'click .form-toggle': 'toggleForm'
- },
- subview: {
- login: {},
- register: {},
- passwordHelp: {},
- institutionLogin: {},
- hintedLogin: {}
- },
- nextUrl: '/dashboard',
+ return Backbone.View.extend({
+ tpl: '#access-tpl',
+ events: {
+ 'click .form-toggle': 'toggleForm'
+ },
+ subview: {
+ login: {},
+ register: {},
+ passwordHelp: {},
+ institutionLogin: {},
+ hintedLogin: {}
+ },
+ nextUrl: '/dashboard',
// The form currently loaded
- activeForm: '',
-
- initialize: function( options ) {
+ activeForm: '',
+ initialize: function(options) {
/* Mix non-conflicting functions from underscore.string
* (all but include, contains, and reverse) into the
* Underscore namespace
*/
- _.mixin( _s.exports() );
+ _.mixin(_s.exports());
- this.tpl = $(this.tpl).html();
+ this.tpl = $(this.tpl).html();
- this.activeForm = options.initial_mode || 'login';
+ this.activeForm = options.initial_mode || 'login';
- this.thirdPartyAuth = options.third_party_auth || {
- currentProvider: null,
- providers: []
- };
+ this.thirdPartyAuth = options.third_party_auth || {
+ currentProvider: null,
+ providers: []
+ };
- this.thirdPartyAuthHint = options.third_party_auth_hint || null;
+ this.thirdPartyAuthHint = options.third_party_auth_hint || null;
- if (options.login_redirect_url) {
+ if (options.login_redirect_url) {
// Ensure that the next URL is internal for security reasons
- if ( ! window.isExternal( options.login_redirect_url ) ) {
- this.nextUrl = options.login_redirect_url;
+ if (! window.isExternal(options.login_redirect_url)) {
+ this.nextUrl = options.login_redirect_url;
+ }
}
- }
- this.formDescriptions = {
- login: options.login_form_desc,
- register: options.registration_form_desc,
- reset: options.password_reset_form_desc,
- institution_login: null,
- hinted_login: null
- };
+ this.formDescriptions = {
+ login: options.login_form_desc,
+ register: options.registration_form_desc,
+ reset: options.password_reset_form_desc,
+ institution_login: null,
+ hinted_login: null
+ };
- this.platformName = options.platform_name;
- this.supportURL = options.support_link;
+ this.platformName = options.platform_name;
+ this.supportURL = options.support_link;
// The login view listens for 'sync' events from the reset model
- this.resetModel = new PasswordResetModel({}, {
- method: 'GET',
- url: '#'
- });
+ this.resetModel = new PasswordResetModel({}, {
+ method: 'GET',
+ url: '#'
+ });
- this.render();
+ this.render();
// Once the third party error message has been shown once,
// there is no need to show it again, if the user changes mode:
- this.thirdPartyAuth.errorMessage = null;
- },
+ this.thirdPartyAuth.errorMessage = null;
+ },
- render: function() {
- $(this.el).html( _.template(this.tpl)({
- mode: this.activeForm
- }));
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
+ mode: this.activeForm
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- //get & check current url hash part & load form accordingly
- if (Backbone.history.getHash() === 'forgot-password-modal') {
- this.resetPassword();
- }
- this.loadForm(this.activeForm);
+ postRender: function() {
+ // get & check current url hash part & load form accordingly
+ if (Backbone.history.getHash() === 'forgot-password-modal') {
+ this.resetPassword();
+ }
+ this.loadForm(this.activeForm);
+ },
- },
+ loadForm: function(type) {
+ var loadFunc = _.bind(this.load[type], this);
+ loadFunc(this.formDescriptions[type]);
+ },
- loadForm: function( type ) {
- var loadFunc = _.bind( this.load[type], this );
- loadFunc( this.formDescriptions[type] );
- },
+ load: {
+ login: function(data) {
+ var model = new LoginModel({}, {
+ method: data.method,
+ url: data.submit_url
+ });
- load: {
- login: function( data ) {
- var model = new LoginModel({}, {
- method: data.method,
- url: data.submit_url
- });
-
- this.subview.login = new LoginView({
- fields: data.fields,
- model: model,
- resetModel: this.resetModel,
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName,
- supportURL: this.supportURL
- });
+ this.subview.login = new LoginView({
+ fields: data.fields,
+ model: model,
+ resetModel: this.resetModel,
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName,
+ supportURL: this.supportURL
+ });
// Listen for 'password-help' event to toggle sub-views
- this.listenTo( this.subview.login, 'password-help', this.resetPassword );
+ this.listenTo(this.subview.login, 'password-help', this.resetPassword);
// Listen for 'auth-complete' event so we can enroll/redirect the user appropriately.
- this.listenTo( this.subview.login, 'auth-complete', this.authComplete );
+ this.listenTo(this.subview.login, 'auth-complete', this.authComplete);
+ },
- },
+ reset: function(data) {
+ this.resetModel.ajaxType = data.method;
+ this.resetModel.urlRoot = data.submit_url;
- reset: function( data ) {
- this.resetModel.ajaxType = data.method;
- this.resetModel.urlRoot = data.submit_url;
-
- this.subview.passwordHelp = new PasswordResetView({
- fields: data.fields,
- model: this.resetModel
- });
+ this.subview.passwordHelp = new PasswordResetView({
+ fields: data.fields,
+ model: this.resetModel
+ });
// Listen for 'password-email-sent' event to toggle sub-views
- this.listenTo( this.subview.passwordHelp, 'password-email-sent', this.passwordEmailSent );
+ this.listenTo(this.subview.passwordHelp, 'password-email-sent', this.passwordEmailSent);
// Focus on the form
- $('.password-reset-form').focus();
- },
+ $('.password-reset-form').focus();
+ },
- register: function( data ) {
- var model = new RegisterModel({}, {
- method: data.method,
- url: data.submit_url
- });
+ register: function(data) {
+ var model = new RegisterModel({}, {
+ method: data.method,
+ url: data.submit_url
+ });
- this.subview.register = new RegisterView({
- fields: data.fields,
- model: model,
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName
- });
+ this.subview.register = new RegisterView({
+ fields: data.fields,
+ model: model,
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName
+ });
// Listen for 'auth-complete' event so we can enroll/redirect the user appropriately.
- this.listenTo( this.subview.register, 'auth-complete', this.authComplete );
+ this.listenTo(this.subview.register, 'auth-complete', this.authComplete);
+ },
+
+ institution_login: function(unused) {
+ this.subview.institutionLogin = new InstitutionLoginView({
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName,
+ mode: this.activeForm
+ });
+
+ this.subview.institutionLogin.render();
+ },
+
+ hinted_login: function(unused) {
+ this.subview.hintedLogin = new HintedLoginView({
+ thirdPartyAuth: this.thirdPartyAuth,
+ hintedProvider: this.thirdPartyAuthHint,
+ platformName: this.platformName
+ });
+
+ this.subview.hintedLogin.render();
+ }
},
- institution_login: function ( unused ) {
- this.subview.institutionLogin = new InstitutionLoginView({
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName,
- mode: this.activeForm
- });
-
- this.subview.institutionLogin.render();
+ passwordEmailSent: function() {
+ var $loginAnchorElement = $('#login-anchor');
+ this.element.hide($(this.el).find('#password-reset-anchor'));
+ this.element.show($loginAnchorElement);
+ this.element.scrollTop($loginAnchorElement);
},
- hinted_login: function ( unused ) {
- this.subview.hintedLogin = new HintedLoginView({
- thirdPartyAuth: this.thirdPartyAuth,
- hintedProvider: this.thirdPartyAuthHint,
- platformName: this.platformName
+ resetPassword: function() {
+ window.analytics.track('edx.bi.password_reset_form.viewed', {
+ category: 'user-engagement'
});
- this.subview.hintedLogin.render();
- }
- },
+ this.element.hide($(this.el).find('#login-anchor'));
+ this.loadForm('reset');
+ this.element.scrollTop($('#password-reset-anchor'));
+ },
- passwordEmailSent: function() {
- var $loginAnchorElement = $('#login-anchor');
- this.element.hide( $(this.el).find('#password-reset-anchor') );
- this.element.show( $loginAnchorElement );
- this.element.scrollTop( $loginAnchorElement );
- },
+ toggleForm: function(e) {
+ var type = $(e.currentTarget).data('type'),
+ $form = $('#' + type + '-form'),
+ $anchor = $('#' + type + '-anchor'),
+ queryParams = url('?'),
+ queryStr = queryParams.length > 0 ? '?' + queryParams : '';
- resetPassword: function() {
- window.analytics.track('edx.bi.password_reset_form.viewed', {
- category: 'user-engagement'
- });
+ e.preventDefault();
- this.element.hide( $(this.el).find('#login-anchor') );
- this.loadForm('reset');
- this.element.scrollTop( $('#password-reset-anchor') );
- },
-
- toggleForm: function( e ) {
- var type = $(e.currentTarget).data('type'),
- $form = $('#' + type + '-form'),
- $anchor = $('#' + type + '-anchor'),
- queryParams = url('?'),
- queryStr = queryParams.length > 0 ? '?' + queryParams : '';
-
- e.preventDefault();
-
- window.analytics.track('edx.bi.' + type + '_form.toggled', {
- category: 'user-engagement'
- });
+ window.analytics.track('edx.bi.' + type + '_form.toggled', {
+ category: 'user-engagement'
+ });
// Load the form. Institution login is always refreshed since it changes based on the previous form.
- if ( !this.form.isLoaded( $form ) || type == 'institution_login') {
- this.loadForm( type );
- }
- this.activeForm = type;
+ if (!this.form.isLoaded($form) || type == 'institution_login') {
+ this.loadForm(type);
+ }
+ this.activeForm = type;
- this.element.hide( $(this.el).find('.submission-success') );
- this.element.hide( $(this.el).find('.form-wrapper') );
- this.element.show( $form );
- this.element.scrollTop( $anchor );
+ this.element.hide($(this.el).find('.submission-success'));
+ this.element.hide($(this.el).find('.form-wrapper'));
+ this.element.show($form);
+ this.element.scrollTop($anchor);
// Update url without reloading page
- if (type != 'institution_login') {
- History.pushState( null, document.title, '/' + type + queryStr );
- }
- analytics.page( 'login_and_registration', type );
+ if (type != 'institution_login') {
+ History.pushState(null, document.title, '/' + type + queryStr);
+ }
+ analytics.page('login_and_registration', type);
// Focus on the form
- $('#' + type).focus();
- },
+ $('#' + type).focus();
+ },
/**
* Once authentication has completed successfully:
@@ -245,48 +241,48 @@
* Otherwise, redirect to the specified next step.
*
*/
- authComplete: function() {
- if (this.thirdPartyAuth && this.thirdPartyAuth.finishAuthUrl) {
- this.redirect(this.thirdPartyAuth.finishAuthUrl);
+ authComplete: function() {
+ if (this.thirdPartyAuth && this.thirdPartyAuth.finishAuthUrl) {
+ this.redirect(this.thirdPartyAuth.finishAuthUrl);
// Note: the third party auth URL likely contains another redirect URL embedded inside
- } else {
- this.redirect(this.nextUrl);
- }
- },
+ } else {
+ this.redirect(this.nextUrl);
+ }
+ },
/**
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- window.location.replace(url);
- },
+ redirect: function(url) {
+ window.location.replace(url);
+ },
- form: {
- isLoaded: function( $form ) {
- return $form.html().length > 0;
- }
- },
+ form: {
+ isLoaded: function($form) {
+ return $form.html().length > 0;
+ }
+ },
/* Helper method to toggle display
* including accessibility considerations
*/
- element: {
- hide: function( $el ) {
- $el.addClass('hidden');
- },
+ element: {
+ hide: function($el) {
+ $el.addClass('hidden');
+ },
- scrollTop: function( $el ) {
+ scrollTop: function($el) {
// Scroll to top of selected element
- $('html,body').animate({
- scrollTop: $el.offset().top
- },'slow');
- },
+ $('html,body').animate({
+ scrollTop: $el.offset().top
+ }, 'slow');
+ },
- show: function( $el ) {
- $el.removeClass('hidden');
+ show: function($el) {
+ $el.removeClass('hidden');
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/FinishAuthView.js b/lms/static/js/student_account/views/FinishAuthView.js
index bef5aa4f2b..870c56b615 100644
--- a/lms/static/js/student_account/views/FinishAuthView.js
+++ b/lms/static/js/student_account/views/FinishAuthView.js
@@ -23,7 +23,7 @@
* - The specified 'nextUrl' if safe, or
* - The dashboard
*/
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'jquery',
@@ -33,8 +33,7 @@
'js/student_account/emailoptin',
'js/student_account/enrollment',
'js/student_account/shoppingcart'
- ], function ($, _, Backbone, gettext, emailOptInInterface, enrollmentInterface, shoppingCartInterface) {
-
+ ], function($, _, Backbone, gettext, emailOptInInterface, enrollmentInterface, shoppingCartInterface) {
var FinishAuthView = Backbone.View.extend({
el: '#finish-auth-status',
@@ -45,14 +44,14 @@
trackSelection: '/course_modes/choose/'
},
- initialize: function( obj ) {
+ initialize: function(obj) {
var queryParams = {
- next: $.url( '?next' ),
- enrollmentAction: $.url( '?enrollment_action' ),
- courseId: $.url( '?course_id' ),
- courseMode: $.url( '?course_mode' ),
- emailOptIn: $.url( '?email_opt_in' ),
- purchaseWorkflow: $.url( '?purchase_workflow' )
+ next: $.url('?next'),
+ enrollmentAction: $.url('?enrollment_action'),
+ courseId: $.url('?course_id'),
+ courseMode: $.url('?course_mode'),
+ emailOptIn: $.url('?email_opt_in'),
+ purchaseWorkflow: $.url('?purchase_workflow')
};
for (var key in queryParams) {
if (queryParams[key]) {
@@ -67,7 +66,7 @@
this.purchaseWorkflow = queryParams.purchaseWorkflow;
if (queryParams.next) {
// Ensure that the next URL is internal for security reasons
- if ( ! window.isExternal( queryParams.next ) ) {
+ if (! window.isExternal(queryParams.next)) {
this.nextUrl = queryParams.next;
}
}
@@ -77,8 +76,8 @@
try {
var next = _.bind(this.enrollment, this);
this.checkEmailOptIn(next);
- } catch(err) {
- this.updateTaskDescription(gettext("Error") + ": " + err.message);
+ } catch (err) {
+ this.updateTaskDescription(gettext('Error') + ': ' + err.message);
this.redirect(this.nextUrl);
}
},
@@ -104,8 +103,8 @@
*/
checkEmailOptIn: function(next) {
// Set the email opt in preference. this.emailOptIn is null or "true" or "false"
- if ((this.emailOptIn === "true" || this.emailOptIn === "false") && this.enrollmentAction) {
- this.updateTaskDescription(gettext("Saving your email preference"));
+ if ((this.emailOptIn === 'true' || this.emailOptIn === 'false') && this.enrollmentAction) {
+ this.updateTaskDescription(gettext('Saving your email preference'));
emailOptInInterface
.setPreference(this.courseId, this.emailOptIn)
.always(next);
@@ -122,12 +121,12 @@
enrollment: function() {
var redirectUrl = this.nextUrl;
- if ( this.enrollmentAction === 'enroll' && this.courseId ) {
- this.updateTaskDescription(gettext("Enrolling you in the selected course"));
- var courseId = decodeURIComponent( this.courseId );
+ if (this.enrollmentAction === 'enroll' && this.courseId) {
+ this.updateTaskDescription(gettext('Enrolling you in the selected course'));
+ var courseId = decodeURIComponent(this.courseId);
// Determine where to redirect the user after auto-enrollment.
- if ( !this.courseMode ) {
+ if (!this.courseMode) {
/* Backwards compatibility with the original course details page.
The old implementation did not specify the course mode for enrollment,
so we'd always send the user to the "track selection" page.
@@ -135,7 +134,7 @@
("verified", "honor", etc.) -- or, if the only course mode was "honor",
it would redirect the user to the dashboard. */
redirectUrl = this.appendPurchaseWorkflow(this.urls.trackSelection + courseId + '/');
- } else if ( this.courseMode === 'honor' || this.courseMode === 'audit' ) {
+ } else if (this.courseMode === 'honor' || this.courseMode === 'audit') {
/* The newer version of the course details page allows the user
to specify which course mode to enroll as. If the student has
chosen "honor", we send them immediately to the next URL
@@ -149,17 +148,17 @@
/* Attempt to auto-enroll the user in a free mode of the course,
then redirect to the next location. */
- enrollmentInterface.enroll( courseId, redirectUrl );
- } else if ( this.enrollmentAction === 'add_to_cart' && this.courseId) {
+ enrollmentInterface.enroll(courseId, redirectUrl);
+ } else if (this.enrollmentAction === 'add_to_cart' && this.courseId) {
/*
If this is a paid course, add it to the shopping cart and redirect
the user to the "view cart" page.
*/
- this.updateTaskDescription(gettext("Adding the selected course to your cart"));
- shoppingCartInterface.addCourseToCart( this.courseId );
+ this.updateTaskDescription(gettext('Adding the selected course to your cart'));
+ shoppingCartInterface.addCourseToCart(this.courseId);
} else {
// Otherwise, redirect the user to the next page.
- this.redirect( redirectUrl );
+ this.redirect(redirectUrl);
}
},
@@ -167,8 +166,8 @@
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- this.updateTaskDescription(gettext("Loading your courses"));
+ redirect: function(url) {
+ this.updateTaskDescription(gettext('Loading your courses'));
window.location.replace(url);
}
});
diff --git a/lms/static/js/student_account/views/FormView.js b/lms/static/js/student_account/views/FormView.js
index 5e98e2bb4b..92dbd73b2c 100644
--- a/lms/static/js/student_account/views/FormView.js
+++ b/lms/static/js/student_account/views/FormView.js
@@ -1,261 +1,259 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/utils/edx.utils.validate'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/utils/edx.utils.validate'
+ ],
function($, _, Backbone, EdxUtilsValidate) {
+ return Backbone.View.extend({
+ tagName: 'form',
- return Backbone.View.extend({
- tagName: 'form',
+ el: '',
- el: '',
+ tpl: '',
- tpl: '',
+ fieldTpl: '#form_field-tpl',
- fieldTpl: '#form_field-tpl',
+ events: {},
- events: {},
+ errors: [],
- errors: [],
+ formType: '',
- formType: '',
+ $form: {},
- $form: {},
-
- fields: [],
+ fields: [],
// String to append to required label fields
- requiredStr: '*',
+ requiredStr: '*',
- submitButton: '',
+ submitButton: '',
- initialize: function( data ) {
- this.model = data.model;
- this.preRender( data );
+ initialize: function(data) {
+ this.model = data.model;
+ this.preRender(data);
- this.tpl = $(this.tpl).html();
- this.fieldTpl = $(this.fieldTpl).html();
- this.buildForm( data.fields );
+ this.tpl = $(this.tpl).html();
+ this.fieldTpl = $(this.fieldTpl).html();
+ this.buildForm(data.fields);
- this.listenTo( this.model, 'error', this.saveError );
- },
+ this.listenTo(this.model, 'error', this.saveError);
+ },
/* Allows extended views to add custom
* init steps without needing to repeat
* default init steps
*/
- preRender: function( data ) {
+ preRender: function(data) {
/* Custom code goes here */
- return data;
- },
+ return data;
+ },
- render: function( html ) {
- var fields = html || '';
+ render: function(html) {
+ var fields = html || '';
- $(this.el).html( _.template(this.tpl)({
- fields: fields
- }));
+ $(this.el).html(_.template(this.tpl)({
+ fields: fields
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- var $container = $(this.el);
- this.$form = $container.find('form');
- this.$errors = $container.find('.submission-error');
- this.$submitButton = $container.find(this.submitButton);
- },
+ postRender: function() {
+ var $container = $(this.el);
+ this.$form = $container.find('form');
+ this.$errors = $container.find('.submission-error');
+ this.$submitButton = $container.find(this.submitButton);
+ },
- buildForm: function( data ) {
- var html = [],
- i,
- len = data.length,
- fieldTpl = this.fieldTpl;
+ buildForm: function(data) {
+ var html = [],
+ i,
+ len = data.length,
+ fieldTpl = this.fieldTpl;
- this.fields = data;
+ this.fields = data;
- for ( i=0; i
' + error.responseText + ''];
- this.setErrors();
- this.toggleDisableButton(false);
- },
+ focusFirstError: function() {
+ var $error = this.$form.find('.error').first(),
+ $field = {},
+ $parent = {};
- setErrors: function() {
- var $msg = this.$errors.find('.message-copy'),
- html = [],
- errors = this.errors,
- i,
- len = errors.length;
+ if ($error.is('label')) {
+ $parent = $error.parent('.form-field');
+ $error = $parent.find('input') || $parent.find('select');
+ } else {
+ $field = $error;
+ }
- for ( i=0; i' + error.responseText + ''];
+ this.setErrors();
+ this.toggleDisableButton(false);
+ },
+
+ setErrors: function() {
+ var $msg = this.$errors.find('.message-copy'),
+ html = [],
+ errors = this.errors,
+ i,
+ len = errors.length;
+
+ for (i = 0; i < len; i++) {
+ html.push(errors[i]);
+ }
+
+ $msg.html(html.join(''));
+
+ this.element.show(this.$errors);
// Scroll to error messages
- $('html,body').animate({
- scrollTop: this.$errors.offset().top
- },'slow');
+ $('html,body').animate({
+ scrollTop: this.$errors.offset().top
+ }, 'slow');
// Focus on first error field
- this.focusFirstError();
- },
+ this.focusFirstError();
+ },
/* Allows extended views to add non-form attributes
- * to the data before saving it to model
+ * to the data before saving it to model
*/
- setExtraData: function( data ) {
- return data;
- },
+ setExtraData: function(data) {
+ return data;
+ },
- submitForm: function( event ) {
- var data = this.getFormData();
+ submitForm: function(event) {
+ var data = this.getFormData();
- if (!_.isUndefined(event)) {
- event.preventDefault();
- }
+ if (!_.isUndefined(event)) {
+ event.preventDefault();
+ }
- this.toggleDisableButton(true);
+ this.toggleDisableButton(true);
- if ( !_.compact(this.errors).length ) {
- data = this.setExtraData( data );
- this.model.set( data );
- this.model.save();
- this.toggleErrorMsg( false );
- } else {
- this.toggleErrorMsg( true );
- }
+ if (!_.compact(this.errors).length) {
+ data = this.setExtraData(data);
+ this.model.set(data);
+ this.model.save();
+ this.toggleErrorMsg(false);
+ } else {
+ this.toggleErrorMsg(true);
+ }
- this.postFormSubmission();
- },
+ this.postFormSubmission();
+ },
/* Allows extended views to add custom
* code after form submission
*/
- postFormSubmission: function() {
- return true;
- },
+ postFormSubmission: function() {
+ return true;
+ },
- toggleErrorMsg: function( show ) {
- if ( show ) {
- this.setErrors();
- this.toggleDisableButton(false);
- } else {
- this.element.hide( this.$errors );
- }
- },
+ toggleErrorMsg: function(show) {
+ if (show) {
+ this.setErrors();
+ this.toggleDisableButton(false);
+ } else {
+ this.element.hide(this.$errors);
+ }
+ },
/**
* If a form button is defined for this form, this will disable the button on
@@ -265,15 +263,15 @@
* disabled (boolean): If set to TRUE, disable the button.
*
*/
- toggleDisableButton: function ( disabled ) {
- if (this.$submitButton) {
- this.$submitButton.attr('disabled', disabled);
- }
- },
+ toggleDisableButton: function(disabled) {
+ if (this.$submitButton) {
+ this.$submitButton.attr('disabled', disabled);
+ }
+ },
- validate: function( $el ) {
- return EdxUtilsValidate.validate( $el );
- }
+ validate: function($el) {
+ return EdxUtilsValidate.validate($el);
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/HintedLoginView.js b/lms/static/js/student_account/views/HintedLoginView.js
index bd35ddbad9..74793304e9 100644
--- a/lms/static/js/student_account/views/HintedLoginView.js
+++ b/lms/static/js/student_account/views/HintedLoginView.js
@@ -1,46 +1,45 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone'],
function($, _, Backbone) {
+ return Backbone.View.extend({
+ el: '#hinted-login-form',
- return Backbone.View.extend({
- el: '#hinted-login-form',
+ tpl: '#hinted_login-tpl',
- tpl: '#hinted_login-tpl',
+ events: {
+ 'click .proceed-button': 'proceedWithHintedAuth'
+ },
- events: {
- 'click .proceed-button': 'proceedWithHintedAuth'
- },
+ formType: 'hinted-login',
- formType: 'hinted-login',
-
- initialize: function( data ) {
- this.tpl = $(this.tpl).html();
- this.hintedProvider = (
+ initialize: function(data) {
+ this.tpl = $(this.tpl).html();
+ this.hintedProvider = (
_.findWhere(data.thirdPartyAuth.providers, {id: data.hintedProvider}) ||
_.findWhere(data.thirdPartyAuth.secondaryProviders, {id: data.hintedProvider})
);
- },
+ },
- render: function() {
- $(this.el).html(_.template(this.tpl)({
- hintedProvider: this.hintedProvider
- }));
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
+ hintedProvider: this.hintedProvider
+ }));
- return this;
- },
+ return this;
+ },
- proceedWithHintedAuth: function( event ) {
- this.redirect(this.hintedProvider.loginUrl);
- },
+ proceedWithHintedAuth: function(event) {
+ this.redirect(this.hintedProvider.loginUrl);
+ },
/**
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- window.location.href = url;
- }
+ redirect: function(url) {
+ window.location.href = url;
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/InstitutionLoginView.js b/lms/static/js/student_account/views/InstitutionLoginView.js
index 8f191d5d3c..d466d15c19 100644
--- a/lms/static/js/student_account/views/InstitutionLoginView.js
+++ b/lms/static/js/student_account/views/InstitutionLoginView.js
@@ -1,28 +1,27 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone'],
function($, _, Backbone) {
+ return Backbone.View.extend({
+ el: '#institution_login-form',
- return Backbone.View.extend({
- el: '#institution_login-form',
+ initialize: function(data) {
+ var tpl = data.mode == 'register' ? '#institution_register-tpl' : '#institution_login-tpl';
+ this.tpl = $(tpl).html();
+ this.providers = data.thirdPartyAuth.secondaryProviders || [];
+ this.platformName = data.platformName;
+ },
- initialize: function( data ) {
- var tpl = data.mode == "register" ? '#institution_register-tpl' : '#institution_login-tpl';
- this.tpl = $(tpl).html();
- this.providers = data.thirdPartyAuth.secondaryProviders || [];
- this.platformName = data.platformName;
- },
-
- render: function() {
- $(this.el).html(_.template(this.tpl)({
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
// We pass the context object to the template so that
// we can perform variable interpolation using sprintf
- providers: this.providers,
- platformName: this.platformName
- }));
+ providers: this.providers,
+ platformName: this.platformName
+ }));
- return this;
- }
+ return this;
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/LoginView.js b/lms/static/js/student_account/views/LoginView.js
index c62edc6787..05bbc2eca1 100644
--- a/lms/static/js/student_account/views/LoginView.js
+++ b/lms/static/js/student_account/views/LoginView.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'jquery',
@@ -6,38 +6,38 @@
'gettext',
'edx-ui-toolkit/js/utils/html-utils',
'js/student_account/views/FormView'
- ],
+ ],
function($, _, gettext, HtmlUtils, FormView) {
- return FormView.extend({
- el: '#login-form',
- tpl: '#login-tpl',
- events: {
- 'click .js-login': 'submitForm',
- 'click .forgot-password': 'forgotPassword',
- 'click .login-provider': 'thirdPartyAuth'
- },
- formType: 'login',
- requiredStr: '',
- submitButton: '.js-login',
+ return FormView.extend({
+ el: '#login-form',
+ tpl: '#login-tpl',
+ events: {
+ 'click .js-login': 'submitForm',
+ 'click .forgot-password': 'forgotPassword',
+ 'click .login-provider': 'thirdPartyAuth'
+ },
+ formType: 'login',
+ requiredStr: '',
+ submitButton: '.js-login',
- preRender: function( data ) {
- this.providers = data.thirdPartyAuth.providers || [];
- this.hasSecondaryProviders = (
+ preRender: function(data) {
+ this.providers = data.thirdPartyAuth.providers || [];
+ this.hasSecondaryProviders = (
data.thirdPartyAuth.secondaryProviders && data.thirdPartyAuth.secondaryProviders.length
);
- this.currentProvider = data.thirdPartyAuth.currentProvider || '';
- this.errorMessage = data.thirdPartyAuth.errorMessage || '';
- this.platformName = data.platformName;
- this.resetModel = data.resetModel;
- this.supportURL = data.supportURL;
+ this.currentProvider = data.thirdPartyAuth.currentProvider || '';
+ this.errorMessage = data.thirdPartyAuth.errorMessage || '';
+ this.platformName = data.platformName;
+ this.resetModel = data.resetModel;
+ this.supportURL = data.supportURL;
- this.listenTo( this.model, 'sync', this.saveSuccess );
- this.listenTo( this.resetModel, 'sync', this.resetEmail );
- },
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ this.listenTo(this.resetModel, 'sync', this.resetEmail);
+ },
- render: function( html ) {
- var fields = html || '';
- this.successMessage = HtmlUtils.interpolateHtml(
+ render: function(html) {
+ var fields = html || '';
+ this.successMessage = HtmlUtils.interpolateHtml(
// eslint-disable-next-line
gettext('We have sent an email message with password reset instructions to the email address you provided. If you do not receive this message, {anchorStart}contact technical support{anchorEnd}.'), { // eslint-disable-line max-len
anchorStart: HtmlUtils.HTML(''),
@@ -45,91 +45,91 @@
}
);
- $(this.el).html(_.template(this.tpl)({
+ $(this.el).html(_.template(this.tpl)({
// We pass the context object to the template so that
// we can perform variable interpolation using sprintf
- context: {
- fields: fields,
- currentProvider: this.currentProvider,
- errorMessage: this.errorMessage,
- providers: this.providers,
- hasSecondaryProviders: this.hasSecondaryProviders,
- platformName: this.platformName
- }
- }));
+ context: {
+ fields: fields,
+ currentProvider: this.currentProvider,
+ errorMessage: this.errorMessage,
+ providers: this.providers,
+ hasSecondaryProviders: this.hasSecondaryProviders,
+ platformName: this.platformName
+ }
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- this.$container = $(this.el);
+ postRender: function() {
+ this.$container = $(this.el);
- this.$form = this.$container.find('form');
- this.$errors = this.$container.find('.submission-error');
- this.$resetSuccess = this.$container.find('.js-reset-success');
- this.$authError = this.$container.find('.already-authenticated-msg');
- this.$submitButton = this.$container.find(this.submitButton);
+ this.$form = this.$container.find('form');
+ this.$errors = this.$container.find('.submission-error');
+ this.$resetSuccess = this.$container.find('.js-reset-success');
+ this.$authError = this.$container.find('.already-authenticated-msg');
+ this.$submitButton = this.$container.find(this.submitButton);
/* If we're already authenticated with a third-party
* provider, try logging in. The easiest way to do this
* is to simply submit the form.
*/
- if (this.currentProvider) {
- this.model.save();
- }
- },
+ if (this.currentProvider) {
+ this.model.save();
+ }
+ },
- forgotPassword: function( event ) {
- event.preventDefault();
+ forgotPassword: function(event) {
+ event.preventDefault();
- this.trigger('password-help');
- this.element.hide( this.$resetSuccess );
- },
+ this.trigger('password-help');
+ this.element.hide(this.$resetSuccess);
+ },
- postFormSubmission: function() {
- this.element.hide( this.$resetSuccess );
- },
+ postFormSubmission: function() {
+ this.element.hide(this.$resetSuccess);
+ },
- resetEmail: function() {
- this.element.hide( this.$errors );
- this.resetMessage = this.$resetSuccess.find('.message-copy');
- if (this.resetMessage.find('p').length === 0) {
- this.resetMessage.append(
+ resetEmail: function() {
+ this.element.hide(this.$errors);
+ this.resetMessage = this.$resetSuccess.find('.message-copy');
+ if (this.resetMessage.find('p').length === 0) {
+ this.resetMessage.append(
HtmlUtils.joinHtml(
HtmlUtils.HTML(''),
this.successMessage,
HtmlUtils.HTML('
')
).toString()
);
- }
- this.element.show( this.$resetSuccess );
- },
+ }
+ this.element.show(this.$resetSuccess);
+ },
- thirdPartyAuth: function( event ) {
- var providerUrl = $(event.currentTarget).data('provider-url') || '';
+ thirdPartyAuth: function(event) {
+ var providerUrl = $(event.currentTarget).data('provider-url') || '';
- if (providerUrl) {
- window.location.href = providerUrl;
- }
- },
+ if (providerUrl) {
+ window.location.href = providerUrl;
+ }
+ },
- saveSuccess: function() {
- this.trigger('auth-complete');
- this.element.hide( this.$resetSuccess );
- },
+ saveSuccess: function() {
+ this.trigger('auth-complete');
+ this.element.hide(this.$resetSuccess);
+ },
- saveError: function( error ) {
- var msg = error.responseText;
- if (error.status === 0) {
- msg = gettext('An error has occurred. Check your Internet connection and try again.');
- } else if(error.status === 500){
- msg = gettext('An error has occurred. Try refreshing the page, or check your Internet connection.');
- }
- this.errors = ['' + msg + ' '];
- this.setErrors();
- this.element.hide( this.$resetSuccess );
+ saveError: function(error) {
+ var msg = error.responseText;
+ if (error.status === 0) {
+ msg = gettext('An error has occurred. Check your Internet connection and try again.');
+ } else if (error.status === 500) {
+ msg = gettext('An error has occurred. Try refreshing the page, or check your Internet connection.');
+ }
+ this.errors = ['' + msg + ' '];
+ this.setErrors();
+ this.element.hide(this.$resetSuccess);
/* If we've gotten a 403 error, it means that we've successfully
* authenticated with a third-party provider, but we haven't
@@ -137,17 +137,17 @@
* we need to prompt the user to enter a little more information
* to complete the registration process.
*/
- if ( error.status === 403 &&
+ if (error.status === 403 &&
error.responseText === 'third-party-auth' &&
- this.currentProvider ) {
- this.element.show( this.$authError );
- this.element.hide( this.$errors );
- } else {
- this.element.hide( this.$authError );
- this.element.show( this.$errors );
+ this.currentProvider) {
+ this.element.show(this.$authError);
+ this.element.hide(this.$errors);
+ } else {
+ this.element.hide(this.$authError);
+ this.element.show(this.$errors);
+ }
+ this.toggleDisableButton(false);
}
- this.toggleDisableButton(false);
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/PasswordResetView.js b/lms/static/js/student_account/views/PasswordResetView.js
index c7b11b2298..32a0ee9956 100644
--- a/lms/static/js/student_account/views/PasswordResetView.js
+++ b/lms/static/js/student_account/views/PasswordResetView.js
@@ -1,48 +1,47 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'js/student_account/views/FormView'
- ],
+ 'jquery',
+ 'js/student_account/views/FormView'
+ ],
function($, FormView) {
+ return FormView.extend({
+ el: '#password-reset-form',
- return FormView.extend({
- el: '#password-reset-form',
+ tpl: '#password_reset-tpl',
- tpl: '#password_reset-tpl',
+ events: {
+ 'click .js-reset': 'submitForm'
+ },
- events: {
- 'click .js-reset': 'submitForm'
- },
+ formType: 'password-reset',
- formType: 'password-reset',
+ requiredStr: '',
- requiredStr: '',
+ submitButton: '.js-reset',
- submitButton: '.js-reset',
+ preRender: function() {
+ this.element.show($(this.el));
+ this.element.show($(this.el).parent());
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ },
- preRender: function() {
- this.element.show( $( this.el ) );
- this.element.show( $( this.el ).parent() );
- this.listenTo( this.model, 'sync', this.saveSuccess );
- },
+ toggleErrorMsg: function(show) {
+ if (show) {
+ this.setErrors();
+ this.toggleDisableButton(false);
+ } else {
+ this.element.hide(this.$errors);
+ }
+ },
- toggleErrorMsg: function( show ) {
- if ( show ) {
- this.setErrors();
- this.toggleDisableButton(false);
- } else {
- this.element.hide( this.$errors );
- }
- },
-
- saveSuccess: function() {
- this.trigger('password-email-sent');
+ saveSuccess: function() {
+ this.trigger('password-email-sent');
// Destroy the view (but not el) and unbind events
- this.$el.empty().off();
- this.stopListening();
- }
+ this.$el.empty().off();
+ this.stopListening();
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/RegisterView.js b/lms/static/js/student_account/views/RegisterView.js
index 96d43a78f3..8b03015732 100644
--- a/lms/static/js/student_account/views/RegisterView.js
+++ b/lms/static/js/student_account/views/RegisterView.js
@@ -1,85 +1,84 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'js/student_account/views/FormView'
- ],
+ 'jquery',
+ 'underscore',
+ 'js/student_account/views/FormView'
+ ],
function($, _, FormView) {
+ return FormView.extend({
+ el: '#register-form',
- return FormView.extend({
- el: '#register-form',
+ tpl: '#register-tpl',
- tpl: '#register-tpl',
+ events: {
+ 'click .js-register': 'submitForm',
+ 'click .login-provider': 'thirdPartyAuth'
+ },
- events: {
- 'click .js-register': 'submitForm',
- 'click .login-provider': 'thirdPartyAuth'
- },
+ formType: 'register',
- formType: 'register',
+ submitButton: '.js-register',
- submitButton: '.js-register',
-
- preRender: function( data ) {
- this.providers = data.thirdPartyAuth.providers || [];
- this.hasSecondaryProviders = (
+ preRender: function(data) {
+ this.providers = data.thirdPartyAuth.providers || [];
+ this.hasSecondaryProviders = (
data.thirdPartyAuth.secondaryProviders && data.thirdPartyAuth.secondaryProviders.length
);
- this.currentProvider = data.thirdPartyAuth.currentProvider || '';
- this.errorMessage = data.thirdPartyAuth.errorMessage || '';
- this.platformName = data.platformName;
- this.autoSubmit = data.thirdPartyAuth.autoSubmitRegForm;
+ this.currentProvider = data.thirdPartyAuth.currentProvider || '';
+ this.errorMessage = data.thirdPartyAuth.errorMessage || '';
+ this.platformName = data.platformName;
+ this.autoSubmit = data.thirdPartyAuth.autoSubmitRegForm;
- this.listenTo( this.model, 'sync', this.saveSuccess );
- },
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ },
- render: function( html ) {
- var fields = html || '';
+ render: function(html) {
+ var fields = html || '';
- $(this.el).html(_.template(this.tpl)({
+ $(this.el).html(_.template(this.tpl)({
/* We pass the context object to the template so that
* we can perform variable interpolation using sprintf
*/
- context: {
- fields: fields,
- currentProvider: this.currentProvider,
- errorMessage: this.errorMessage,
- providers: this.providers,
- hasSecondaryProviders: this.hasSecondaryProviders,
- platformName: this.platformName
+ context: {
+ fields: fields,
+ currentProvider: this.currentProvider,
+ errorMessage: this.errorMessage,
+ providers: this.providers,
+ hasSecondaryProviders: this.hasSecondaryProviders,
+ platformName: this.platformName
+ }
+ }));
+
+ this.postRender();
+
+ if (this.autoSubmit) {
+ $(this.el).hide();
+ $('#register-honor_code').prop('checked', true);
+ this.submitForm();
}
- }));
- this.postRender();
+ return this;
+ },
- if (this.autoSubmit) {
- $(this.el).hide();
- $('#register-honor_code').prop('checked', true);
- this.submitForm();
- }
+ thirdPartyAuth: function(event) {
+ var providerUrl = $(event.currentTarget).data('provider-url') || '';
- return this;
- },
+ if (providerUrl) {
+ window.location.href = providerUrl;
+ }
+ },
- thirdPartyAuth: function( event ) {
- var providerUrl = $(event.currentTarget).data('provider-url') || '';
+ saveSuccess: function() {
+ this.trigger('auth-complete');
+ },
- if ( providerUrl ) {
- window.location.href = providerUrl;
- }
- },
-
- saveSuccess: function() {
- this.trigger('auth-complete');
- },
-
- saveError: function( error ) {
- $(this.el).show(); // Show in case the form was hidden for auto-submission
- this.errors = _.flatten(
+ saveError: function(error) {
+ $(this.el).show(); // Show in case the form was hidden for auto-submission
+ this.errors = _.flatten(
_.map(
// Something is passing this 'undefined'. Protect against this.
- JSON.parse(error.responseText || "[]"),
+ JSON.parse(error.responseText || '[]'),
function(error_list) {
return _.map(
error_list,
@@ -88,16 +87,16 @@
}
)
);
- this.setErrors();
- this.toggleDisableButton(false);
- },
+ this.setErrors();
+ this.toggleDisableButton(false);
+ },
- postFormSubmission: function() {
- if (_.compact(this.errors).length) {
+ postFormSubmission: function() {
+ if (_.compact(this.errors).length) {
// The form did not get submitted due to validation errors.
- $(this.el).show(); // Show in case the form was hidden for auto-submission
+ $(this.el).show(); // Show in case the form was hidden for auto-submission
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/account_section_view.js b/lms/static/js/student_account/views/account_section_view.js
index 4164c81c77..cd022eee9d 100644
--- a/lms/static/js/student_account/views/account_section_view.js
+++ b/lms/static/js/student_account/views/account_section_view.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -6,15 +6,14 @@
'underscore',
'backbone',
'text!templates/student_account/account_settings_section.underscore'
- ], function (gettext, $, _, Backbone, sectionTemplate) {
-
+ ], function(gettext, $, _, Backbone, sectionTemplate) {
var AccountSectionView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
},
- render: function () {
+ render: function() {
this.$el.html(_.template(sectionTemplate)({
sections: this.options.sections,
activeTabName: this.options.activeTabName
diff --git a/lms/static/js/student_account/views/account_settings_factory.js b/lms/static/js/student_account/views/account_settings_factory.js
index 1f93bf0541..fc92c267da 100644
--- a/lms/static/js/student_account/views/account_settings_factory.js
+++ b/lms/static/js/student_account/views/account_settings_factory.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'logger',
@@ -7,10 +7,9 @@
'js/student_account/views/account_settings_fields',
'js/student_account/views/account_settings_view',
'edx-ui-toolkit/js/utils/string-utils'
- ], function (gettext, $, _, Backbone, Logger, UserAccountModel, UserPreferencesModel,
+ ], function(gettext, $, _, Backbone, Logger, UserAccountModel, UserPreferencesModel,
AccountSettingsFieldViews, AccountSettingsView, StringUtils) {
-
- return function (
+ return function(
fieldsData,
ordersHistoryData,
authData,
@@ -21,7 +20,7 @@
) {
var accountSettingsElement, userAccountModel, userPreferencesModel, aboutSectionsData,
accountsSectionData, ordersSectionData, accountSettingsView, showAccountSettingsPage,
- showLoadingError, orderNumber;
+ showLoadingError, orderNumber, getUserField, userFields, timeZoneDropdownField, countryDropdownField;
accountSettingsElement = $('.wrapper-account-settings');
@@ -32,7 +31,7 @@
userPreferencesModel.url = userPreferencesApiUrl;
aboutSectionsData = [
- {
+ {
title: gettext('Basic Account Information'),
subtitle: gettext('These settings include basic information about your account. You can also specify additional information and see your linked social accounts on this page.'), // eslint-disable-line max-len
fields: [
@@ -111,7 +110,7 @@
})
},
{
- view: new AccountSettingsFieldViews.DropdownFieldView({
+ view: new AccountSettingsFieldViews.TimeZoneFieldView({
model: userPreferencesModel,
required: true,
title: gettext('Time Zone'),
@@ -121,7 +120,10 @@
'time zone here, course dates, including assignment deadlines, are displayed in ' +
'Coordinated Universal Time (UTC).'
),
- options: fieldsData.time_zone.options,
+ groupOptions: [{
+ groupTitle: gettext('All Time Zones'),
+ selectOptions: fieldsData.time_zone.options
+ }],
persistChanges: true
})
}
@@ -170,6 +172,19 @@
}
];
+ // set TimeZoneField to listen to CountryField
+ getUserField = function(list, search) {
+ return _.find(list, function(field) {
+ return field.view.options.valueAttribute === search;
+ }).view;
+ };
+ userFields = _.find(aboutSectionsData, function(section) {
+ return section.title === gettext('Basic Account Information');
+ }).fields;
+ timeZoneDropdownField = getUserField(userFields, 'time_zone');
+ countryDropdownField = getUserField(userFields, 'country');
+ timeZoneDropdownField.listenToCountryView(countryDropdownField);
+
accountsSectionData = [
{
title: gettext('Linked Accounts'),
@@ -243,10 +258,10 @@
accountSettingsView.render();
- showAccountSettingsPage = function () {
+ showAccountSettingsPage = function() {
// Record that the account settings page was viewed.
Logger.log('edx.user.settings.viewed', {
- page: "account",
+ page: 'account',
visibility: null,
user_id: accountUserId
});
@@ -255,12 +270,12 @@
accountSettingsView.renderFields();
};
- showLoadingError = function () {
+ showLoadingError = function() {
accountSettingsView.showLoadingError();
};
userAccountModel.fetch({
- success: function () {
+ success: function() {
// Fetch the user preferences model
userPreferencesModel.fetch({
success: showAccountSettingsPage,
diff --git a/lms/static/js/student_account/views/account_settings_fields.js b/lms/static/js/student_account/views/account_settings_fields.js
index dbfff2172f..1e350b22cc 100644
--- a/lms/static/js/student_account/views/account_settings_fields.js
+++ b/lms/static/js/student_account/views/account_settings_fields.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -14,7 +14,7 @@
'text!templates/fields/field_order_history.underscore',
'edx-ui-toolkit/js/utils/string-utils',
'edx-ui-toolkit/js/utils/html-utils'
- ], function (
+ ], function(
gettext, $, _, Backbone,
FieldViews,
field_text_account_template,
@@ -27,7 +27,6 @@
HtmlUtils
)
{
-
var AccountSettingsFieldViews = {
ReadonlyFieldView: FieldViews.ReadonlyFieldView.extend({
fieldTemplate: field_readonly_account_template
@@ -40,7 +39,7 @@
}),
EmailFieldView: FieldViews.TextFieldView.extend({
fieldTemplate: field_text_account_template,
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(
this.indicators.success,
StringUtils.interpolate(
@@ -52,7 +51,7 @@
}),
LanguagePreferenceFieldView: FieldViews.DropdownFieldView.extend({
fieldTemplate: field_dropdown_account_template,
- saveSucceeded: function () {
+ saveSucceeded: function() {
var data = {
'language': this.modelValue()
};
@@ -63,10 +62,10 @@
url: '/i18n/setlang/',
data: data,
dataType: 'html',
- success: function () {
+ success: function() {
view.showSuccessMessage();
},
- error: function () {
+ error: function() {
view.showNotificationMessage(
HtmlUtils.joinHtml(
view.indicators.error,
@@ -77,6 +76,67 @@
});
}
+ }),
+ TimeZoneFieldView: FieldViews.DropdownFieldView.extend({
+ fieldTemplate: field_dropdown_account_template,
+
+ initialize: function(options) {
+ this.options = _.extend({}, options);
+ _.bindAll(this, 'listenToCountryView', 'updateCountrySubheader', 'replaceOrAddGroupOption');
+ this._super(options); // eslint-disable-line no-underscore-dangle
+ },
+
+ listenToCountryView: function(view) {
+ this.listenTo(view.model, 'change:country', this.updateCountrySubheader);
+ },
+
+ updateCountrySubheader: function(user) {
+ var view = this;
+ $.ajax({
+ type: 'GET',
+ url: '/user_api/v1/preferences/time_zones/',
+ data: {country_code: user.attributes.country},
+ success: function(data) {
+ var countryTimeZones = $.map(data, function(timeZoneInfo) {
+ return [[timeZoneInfo.time_zone, timeZoneInfo.description]];
+ });
+ view.replaceOrAddGroupOption(
+ 'Country Time Zones',
+ countryTimeZones
+ );
+ view.render();
+ }
+ });
+ },
+
+ updateValueInField: function() {
+ var options;
+ if (this.modelValue()) {
+ options = [[this.modelValue(), this.displayValue(this.modelValue())]];
+ this.replaceOrAddGroupOption(
+ 'Currently Selected Time Zone',
+ options
+ );
+ }
+ this._super(); // eslint-disable-line no-underscore-dangle
+ },
+
+ replaceOrAddGroupOption: function(title, options) {
+ var groupOption = {
+ groupTitle: gettext(title),
+ selectOptions: options
+ };
+
+ var index = _.findIndex(this.options.groupOptions, function(group) {
+ return group.groupTitle === gettext(title);
+ });
+ if (index >= 0) {
+ this.options.groupOptions[index] = groupOption;
+ } else {
+ this.options.groupOptions.unshift(groupOption);
+ }
+ }
+
}),
PasswordFieldView: FieldViews.LinkFieldView.extend({
fieldType: 'button',
@@ -84,16 +144,16 @@
events: {
'click button': 'linkClicked'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'resetPassword');
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
this.resetPassword(event);
},
- resetPassword: function () {
+ resetPassword: function() {
var data = {};
data[this.options.emailAttribute] = this.model.get(this.options.emailAttribute);
@@ -102,15 +162,15 @@
type: 'POST',
url: view.options.linkHref,
data: data,
- success: function () {
+ success: function() {
view.showSuccessMessage();
},
- error: function (xhr) {
+ error: function(xhr) {
view.showErrorMessage(xhr);
}
});
},
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(
this.indicators.success,
StringUtils.interpolate(
@@ -122,7 +182,7 @@
}),
LanguageProficienciesFieldView: FieldViews.DropdownFieldView.extend({
fieldTemplate: field_dropdown_account_template,
- modelValue: function () {
+ modelValue: function() {
var modelValue = this.model.get(this.options.valueAttribute);
if (_.isArray(modelValue) && modelValue.length > 0) {
return modelValue[0].code;
@@ -130,7 +190,7 @@
return null;
}
},
- saveValue: function () {
+ saveValue: function() {
if (this.persistChanges === true) {
var attributes = {},
value = this.fieldValue() ? [{'code': this.fieldValue()}] : [];
@@ -141,20 +201,20 @@
}),
AuthFieldView: FieldViews.LinkFieldView.extend({
fieldTemplate: field_social_link_template,
- className: function () {
+ className: function() {
return 'u-field u-field-social u-field-' + this.options.valueAttribute;
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'redirect_to', 'disconnect', 'successMessage', 'inProgressMessage');
},
- render: function () {
+ render: function() {
var linkTitle = '',
linkClass = '',
subTitle = '',
screenReaderTitle = StringUtils.interpolate(
- gettext("Link your {accountName} account"),
+ gettext('Link your {accountName} account'),
{accountName: this.options.title}
);
if (this.options.connected) {
@@ -165,7 +225,7 @@
{accountName: this.options.title, platformName: this.options.platformName}
);
screenReaderTitle = StringUtils.interpolate(
- gettext("Unlink your {accountName} account"),
+ gettext('Unlink your {accountName} account'),
{accountName: this.options.title}
);
} else if (this.options.acceptsLogins) {
@@ -190,7 +250,7 @@
this.delegateEvents();
return this;
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
this.showInProgressMessage();
@@ -203,10 +263,10 @@
this.redirect_to(this.options.connectUrl);
}
},
- redirect_to: function (url) {
+ redirect_to: function(url) {
window.location.href = url;
},
- disconnect: function () {
+ disconnect: function() {
var data = {};
// Disconnects the provider from the user's edX account.
@@ -217,22 +277,22 @@
url: this.options.disconnectUrl,
data: data,
dataType: 'html',
- success: function () {
+ success: function() {
view.options.connected = false;
view.render();
view.showSuccessMessage();
},
- error: function (xhr) {
+ error: function(xhr) {
view.showErrorMessage(xhr);
}
});
},
- inProgressMessage: function () {
+ inProgressMessage: function() {
return HtmlUtils.joinHtml(this.indicators.inProgress, (
this.options.connected ? gettext('Unlinking') : gettext('Linking')
));
},
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(this.indicators.success, gettext('Successfully unlinked.'));
}
}),
@@ -241,13 +301,13 @@
fieldType: 'orderHistory',
fieldTemplate: field_order_history_template,
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
this._super(options);
this.template = HtmlUtils.template(this.fieldTemplate);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, this.template({
title: this.options.title,
totalPrice: this.options.totalPrice,
diff --git a/lms/static/js/student_account/views/account_settings_view.js b/lms/static/js/student_account/views/account_settings_view.js
index 8b9f387e7f..3271154c67 100644
--- a/lms/static/js/student_account/views/account_settings_view.js
+++ b/lms/static/js/student_account/views/account_settings_view.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -8,8 +8,7 @@
'edx-ui-toolkit/js/utils/html-utils',
'js/student_account/views/account_section_view',
'text!templates/student_account/account_settings.underscore'
- ], function (gettext, $, _, Backbone, HtmlUtils, AccountSectionView, accountSettingsTemplate) {
-
+ ], function(gettext, $, _, Backbone, HtmlUtils, AccountSectionView, accountSettingsTemplate) {
var AccountSettingsView = Backbone.View.extend({
navLink: '.account-nav-link',
@@ -23,12 +22,12 @@
'click .account-nav-link': 'changeTab'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
_.bindAll(this, 'render', 'changeTab', 'renderFields', 'showLoadingError');
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(accountSettingsTemplate)({
accountSettingsTabs: this.accountSettingsTabs
}));
@@ -49,10 +48,10 @@
$currentTab.addClass('active');
$(this.navLink).removeAttr('aria-describedby');
- $currentTab.attr('aria-describedby', 'header-subtitle-'+this.activeTab);
+ $currentTab.attr('aria-describedby', 'header-subtitle-' + this.activeTab);
},
- renderSection: function (tabSections) {
+ renderSection: function(tabSections) {
var accountSectionView = new AccountSectionView({
activeTabName: this.activeTab,
sections: tabSections,
@@ -62,19 +61,19 @@
accountSectionView.render();
},
- renderFields: function () {
+ renderFields: function() {
var view = this;
view.$('.ui-loading-indicator').addClass('is-hidden');
- _.each(view.$('.account-settings-section-body'), function (sectionEl, index) {
- _.each(view.options.tabSections[view.activeTab][index].fields, function (field) {
+ _.each(view.$('.account-settings-section-body'), function(sectionEl, index) {
+ _.each(view.options.tabSections[view.activeTab][index].fields, function(field) {
$(sectionEl).append(field.view.render().el);
});
});
return this;
},
- showLoadingError: function () {
+ showLoadingError: function() {
this.$('.ui-loading-indicator').addClass('is-hidden');
this.$('.ui-loading-error').removeClass('is-hidden');
}
diff --git a/lms/static/js/student_account/views/finish_auth_factory.js b/lms/static/js/student_account/views/finish_auth_factory.js
index aa4ffbff9a..a6e62a098b 100644
--- a/lms/static/js/student_account/views/finish_auth_factory.js
+++ b/lms/static/js/student_account/views/finish_auth_factory.js
@@ -1,8 +1,8 @@
-(function (define) {
+(function(define) {
'use strict';
- define("js/student_account/views/finish_auth_factory",
+ define('js/student_account/views/finish_auth_factory',
['jquery', 'underscore', 'backbone', 'js/student_account/views/FinishAuthView', 'utility'],
- function ($, _, Backbone, FinishAuthView) {
+ function($, _, Backbone, FinishAuthView) {
return function() {
var view = new FinishAuthView({});
view.render();
diff --git a/lms/static/js/student_profile/models/badges_model.js b/lms/static/js/student_profile/models/badges_model.js
index 8b127824d4..efb44d0c35 100644
--- a/lms/static/js/student_profile/models/badges_model.js
+++ b/lms/static/js/student_profile/models/badges_model.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
-
var BadgesModel = Backbone.Model.extend({});
return BadgesModel;
});
diff --git a/lms/static/js/student_profile/views/badge_list_container.js b/lms/static/js/student_profile/views/badge_list_container.js
index 528f03c548..b7607e7d59 100644
--- a/lms/static/js/student_profile/views/badge_list_container.js
+++ b/lms/static/js/student_profile/views/badge_list_container.js
@@ -1,10 +1,10 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'common/js/components/views/paginated_view',
'js/student_profile/views/badge_view', 'js/student_profile/views/badge_list_view',
'text!templates/student_profile/badge_list.underscore'],
- function (gettext, $, _, PaginatedView, BadgeView, BadgeListView, BadgeListTemplate) {
+ function(gettext, $, _, PaginatedView, BadgeView, BadgeListView, BadgeListTemplate) {
var BadgeListContainer = PaginatedView.extend({
type: 'badge',
@@ -18,7 +18,7 @@
paginationLabel: gettext('Accomplishments Pagination'),
- initialize: function (options) {
+ initialize: function(options) {
BadgeListContainer.__super__.initialize.call(this, options);
this.listView.find_courses_url = options.find_courses_url;
this.listView.badgeMeta = options.badgeMeta;
diff --git a/lms/static/js/student_profile/views/badge_list_view.js b/lms/static/js/student_profile/views/badge_list_view.js
index 603b04cd42..40aa50d5b2 100644
--- a/lms/static/js/student_profile/views/badge_list_view.js
+++ b/lms/static/js/student_profile/views/badge_list_view.js
@@ -1,28 +1,28 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
- 'gettext',
- 'jquery',
- 'underscore',
- 'edx-ui-toolkit/js/utils/html-utils',
- 'common/js/components/views/list',
- 'js/student_profile/views/badge_view',
- 'text!templates/student_profile/badge_placeholder.underscore'
- ],
- function (gettext, $, _, HtmlUtils, ListView, BadgeView, badgePlaceholder) {
+ 'gettext',
+ 'jquery',
+ 'underscore',
+ 'edx-ui-toolkit/js/utils/html-utils',
+ 'common/js/components/views/list',
+ 'js/student_profile/views/badge_view',
+ 'text!templates/student_profile/badge_placeholder.underscore'
+ ],
+ function(gettext, $, _, HtmlUtils, ListView, BadgeView, badgePlaceholder) {
var BadgeListView = ListView.extend({
tagName: 'div',
-
+
template: HtmlUtils.template(badgePlaceholder),
-
- renderCollection: function () {
+
+ renderCollection: function() {
var self = this,
$row;
this.$el.empty();
// Split into two columns.
- this.collection.each(function (badge, index) {
+ this.collection.each(function(badge, index) {
if (index % 2 === 0) {
$row = $('');
this.$el.append($row);
diff --git a/lms/static/js/student_profile/views/badge_view.js b/lms/static/js/student_profile/views/badge_view.js
index 5e3d4d0313..6c456c1a84 100644
--- a/lms/static/js/student_profile/views/badge_view.js
+++ b/lms/static/js/student_profile/views/badge_view.js
@@ -1,10 +1,9 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'moment',
'text!templates/student_profile/badge.underscore',
'js/student_profile/views/share_modal_view'],
- function (gettext, $, _, Backbone, Moment, badgeTemplate, ShareModalView) {
-
+ function(gettext, $, _, Backbone, Moment, badgeTemplate, ShareModalView) {
var BadgeView = Backbone.View.extend({
initialize: function(options) {
this.options = _.extend({}, options);
@@ -31,7 +30,7 @@
$('body').append(modal.$el);
modal.$el.fadeIn('short', 'swing', _.bind(modal.ready, modal));
},
- render: function () {
+ render: function() {
this.$el.html(this.template(this.context));
this.shareButton = this.$el.find('.share-button');
return this;
diff --git a/lms/static/js/student_profile/views/learner_profile_factory.js b/lms/static/js/student_profile/views/learner_profile_factory.js
index 9ebcbee153..a83e594e6d 100644
--- a/lms/static/js/student_profile/views/learner_profile_factory.js
+++ b/lms/static/js/student_profile/views/learner_profile_factory.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -17,12 +17,10 @@
'js/student_account/views/account_settings_fields',
'js/views/message_banner',
'string_utils'
- ], function (gettext, $, _, Backbone, Logger, PagingCollection, AccountSettingsModel, AccountPreferencesModel,
+ ], function(gettext, $, _, Backbone, Logger, PagingCollection, AccountSettingsModel, AccountPreferencesModel,
FieldsView, LearnerProfileFieldsView, LearnerProfileView, BadgeModel, BadgeListContainer,
AccountSettingsFieldViews, MessageBannerView) {
-
- return function (options) {
-
+ return function(options) {
var learnerProfileElement = $('.wrapper-profile');
var accountSettingsModel = new AccountSettingsModel(
@@ -56,7 +54,7 @@
title: interpolate_text(
gettext('{platform_name} learners can see my:'), {platform_name: options.platform_name}
),
- valueAttribute: "account_privacy",
+ valueAttribute: 'account_privacy',
options: [
['private', gettext('Limited Profile')],
['all_users', gettext('Full Profile')]
@@ -78,10 +76,10 @@
});
var usernameFieldView = new FieldsView.ReadonlyFieldView({
- model: accountSettingsModel,
- screenReaderTitle: gettext('Username'),
- valueAttribute: "username",
- helpMessage: ""
+ model: accountSettingsModel,
+ screenReaderTitle: gettext('Username'),
+ valueAttribute: 'username',
+ helpMessage: ''
});
var sectionOneFieldViews = [
@@ -94,7 +92,7 @@
showMessages: false,
iconName: 'fa-map-marker',
placeholderValue: gettext('Add Country'),
- valueAttribute: "country",
+ valueAttribute: 'country',
options: options.country_options,
helpMessage: '',
persistChanges: true
@@ -108,7 +106,7 @@
showMessages: false,
iconName: 'fa-comment',
placeholderValue: gettext('Add language'),
- valueAttribute: "language_proficiencies",
+ valueAttribute: 'language_proficiencies',
options: options.language_options,
helpMessage: '',
persistChanges: true
@@ -122,7 +120,7 @@
showMessages: false,
title: gettext('About me'),
placeholderValue: gettext("Tell other learners a little about yourself: where you live, what your interests are, why you're taking courses, or what you hope to learn."),
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
persistChanges: true,
messagePosition: 'header'
@@ -174,7 +172,7 @@
var showLearnerProfileView = function() {
// Record that the profile page was viewed
Logger.log('edx.user.settings.viewed', {
- page: "profile",
+ page: 'profile',
visibility: getProfileVisibility(),
user_id: options.profile_user_id
});
diff --git a/lms/static/js/student_profile/views/learner_profile_fields.js b/lms/static/js/student_profile/views/learner_profile_fields.js
index c57d62e1e0..da18d97d7f 100644
--- a/lms/static/js/student_profile/views/learner_profile_fields.js
+++ b/lms/static/js/student_profile/views/learner_profile_fields.js
@@ -1,22 +1,21 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'edx-ui-toolkit/js/utils/string-utils',
'edx-ui-toolkit/js/utils/html-utils', 'js/views/fields', 'js/views/image_field', 'backbone-super'
- ], function (gettext, $, _, Backbone, StringUtils, HtmlUtils, FieldViews, ImageFieldView) {
-
+ ], function(gettext, $, _, Backbone, StringUtils, HtmlUtils, FieldViews, ImageFieldView) {
var LearnerProfileFieldViews = {};
LearnerProfileFieldViews.AccountPrivacyFieldView = FieldViews.DropdownFieldView.extend({
- render: function () {
+ render: function() {
this._super();
this.showNotificationMessage();
this.updateFieldValue();
return this;
},
- showNotificationMessage: function () {
+ showNotificationMessage: function() {
var accountSettingsLink = HtmlUtils.joinHtml(
HtmlUtils.interpolateHtml(
HtmlUtils.HTML('
'), {settings_url: this.options.accountSettingsPageUrl}
@@ -28,7 +27,7 @@
this._super(
HtmlUtils.interpolateHtml(
gettext('You must specify your birth year before you can share your full profile. To specify your birth year, go to the {account_settings_page_link}'), // eslint-disable-line max-len
- {'account_settings_page_link':accountSettingsLink}
+ {'account_settings_page_link': accountSettingsLink}
)
);
} else if (this.requiresParentalConsent) {
@@ -56,35 +55,35 @@
screenReaderTitle: gettext('Profile Image'),
- imageUrl: function () {
+ imageUrl: function() {
return this.model.profileImageUrl();
},
- imageAltText: function () {
+ imageAltText: function() {
return interpolate_text(
- gettext("Profile image for {username}"), {username: this.model.get('username')}
+ gettext('Profile image for {username}'), {username: this.model.get('username')}
);
},
- imageChangeSucceeded: function (e, data) {
+ imageChangeSucceeded: function(e, data) {
var view = this;
// Update model to get the latest urls of profile image.
- this.model.fetch().done(function () {
+ this.model.fetch().done(function() {
view.setCurrentStatus('');
view.render();
view.$('.u-field-upload-button').focus();
- }).fail(function () {
+ }).fail(function() {
view.setCurrentStatus('');
view.showErrorMessage(view.errorMessage);
});
},
- imageChangeFailed: function (e, data) {
+ imageChangeFailed: function(e, data) {
this.setCurrentStatus('');
this.showImageChangeFailedMessage(data.jqXHR.status, data.jqXHR.responseText);
},
- showImageChangeFailedMessage: function (status, responseText) {
+ showImageChangeFailedMessage: function(status, responseText) {
if (_.contains([400, 404], status)) {
try {
var errors = JSON.parse(responseText);
@@ -97,24 +96,24 @@
}
},
- showErrorMessage: function (message) {
+ showErrorMessage: function(message) {
this.options.messageView.showMessage(message);
},
- isEditingAllowed: function () {
+ isEditingAllowed: function() {
return this.model.isAboveMinimumAge();
},
- isShowingPlaceholder: function () {
+ isShowingPlaceholder: function() {
return !this.model.hasProfileImage();
},
- clickedRemoveButton: function (e, data) {
+ clickedRemoveButton: function(e, data) {
this.options.messageView.hideMessage();
this._super(e, data);
},
- fileSelected: function (e, data) {
+ fileSelected: function(e, data) {
this.options.messageView.hideMessage();
this._super(e, data);
}
diff --git a/lms/static/js/student_profile/views/learner_profile_view.js b/lms/static/js/student_profile/views/learner_profile_view.js
index 05d015621a..d840b6865e 100644
--- a/lms/static/js/student_profile/views/learner_profile_view.js
+++ b/lms/static/js/student_profile/views/learner_profile_view.js
@@ -1,140 +1,138 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'edx-ui-toolkit/js/utils/html-utils',
'common/js/components/views/tabbed_view',
'js/student_profile/views/section_two_tab',
'text!templates/student_profile/learner_profile.underscore'],
- function (gettext, $, _, Backbone, HtmlUtils, TabbedView, SectionTwoTab, learnerProfileTemplate) {
+ function(gettext, $, _, Backbone, HtmlUtils, TabbedView, SectionTwoTab, learnerProfileTemplate) {
+ var LearnerProfileView = Backbone.View.extend({
- var LearnerProfileView = Backbone.View.extend({
+ initialize: function(options) {
+ this.options = _.extend({}, options);
+ _.bindAll(this, 'showFullProfile', 'render', 'renderFields', 'showLoadingError');
+ this.listenTo(this.options.preferencesModel, 'change:' + 'account_privacy', this.render);
+ var Router = Backbone.Router.extend({
+ routes: {':about_me': 'loadTab', ':accomplishments': 'loadTab'}
+ });
- initialize: function (options) {
- this.options = _.extend({}, options);
- _.bindAll(this, 'showFullProfile', 'render', 'renderFields', 'showLoadingError');
- this.listenTo(this.options.preferencesModel, "change:" + 'account_privacy', this.render);
- var Router = Backbone.Router.extend({
- routes: {":about_me": "loadTab", ":accomplishments": "loadTab"}
- });
+ this.router = new Router();
+ this.firstRender = true;
+ },
- this.router = new Router();
- this.firstRender = true;
- },
-
- template: _.template(learnerProfileTemplate),
+ template: _.template(learnerProfileTemplate),
- showFullProfile: function () {
- var isAboveMinimumAge = this.options.accountSettingsModel.isAboveMinimumAge();
- if (this.options.ownProfile) {
- return isAboveMinimumAge && this.options.preferencesModel.get('account_privacy') === 'all_users';
- } else {
- return this.options.accountSettingsModel.get('profile_is_public');
- }
- },
+ showFullProfile: function() {
+ var isAboveMinimumAge = this.options.accountSettingsModel.isAboveMinimumAge();
+ if (this.options.ownProfile) {
+ return isAboveMinimumAge && this.options.preferencesModel.get('account_privacy') === 'all_users';
+ } else {
+ return this.options.accountSettingsModel.get('profile_is_public');
+ }
+ },
- setActiveTab: function(tab) {
+ setActiveTab: function(tab) {
// This tab may not actually exist.
- if (this.tabbedView.getTabMeta(tab).tab) {
- this.tabbedView.setActiveTab(tab);
- }
- },
+ if (this.tabbedView.getTabMeta(tab).tab) {
+ this.tabbedView.setActiveTab(tab);
+ }
+ },
- render: function () {
- var self = this;
+ render: function() {
+ var self = this;
- this.sectionTwoView = new SectionTwoTab({
- viewList: this.options.sectionTwoFieldViews,
- showFullProfile: this.showFullProfile,
- ownProfile: this.options.ownProfile
- });
-
- var tabs = [
- {view: this.sectionTwoView, title: gettext("About Me"), url: "about_me"}
- ];
-
- HtmlUtils.setHtml(this.$el, HtmlUtils.template(learnerProfileTemplate)({
- username: self.options.accountSettingsModel.get('username'),
- ownProfile: self.options.ownProfile,
- showFullProfile: self.showFullProfile()
- }));
- this.renderFields();
-
- if (this.showFullProfile() && (this.options.accountSettingsModel.get('accomplishments_shared'))) {
- tabs.push({
- view: this.options.badgeListContainer,
- title: gettext("Accomplishments"),
- url: "accomplishments"
+ this.sectionTwoView = new SectionTwoTab({
+ viewList: this.options.sectionTwoFieldViews,
+ showFullProfile: this.showFullProfile,
+ ownProfile: this.options.ownProfile
});
- this.options.badgeListContainer.collection.fetch().done(function () {
- self.options.badgeListContainer.render();
- }).error(function () {
- self.options.badgeListContainer.renderError();
+
+ var tabs = [
+ {view: this.sectionTwoView, title: gettext('About Me'), url: 'about_me'}
+ ];
+
+ HtmlUtils.setHtml(this.$el, HtmlUtils.template(learnerProfileTemplate)({
+ username: self.options.accountSettingsModel.get('username'),
+ ownProfile: self.options.ownProfile,
+ showFullProfile: self.showFullProfile()
+ }));
+ this.renderFields();
+
+ if (this.showFullProfile() && (this.options.accountSettingsModel.get('accomplishments_shared'))) {
+ tabs.push({
+ view: this.options.badgeListContainer,
+ title: gettext('Accomplishments'),
+ url: 'accomplishments'
+ });
+ this.options.badgeListContainer.collection.fetch().done(function() {
+ self.options.badgeListContainer.render();
+ }).error(function() {
+ self.options.badgeListContainer.renderError();
+ });
+ }
+ this.tabbedView = new TabbedView({
+ tabs: tabs,
+ router: this.router,
+ viewLabel: gettext('Profile')
});
- }
- this.tabbedView = new TabbedView({
- tabs: tabs,
- router: this.router,
- viewLabel: gettext("Profile")
- });
- this.tabbedView.render();
+ this.tabbedView.render();
- if (tabs.length === 1) {
+ if (tabs.length === 1) {
// If the tab is unambiguous, don't display the tab interface.
- this.tabbedView.$el.find('.page-content-nav').hide();
- }
+ this.tabbedView.$el.find('.page-content-nav').hide();
+ }
- this.$el.find('.account-settings-container').append(this.tabbedView.el);
+ this.$el.find('.account-settings-container').append(this.tabbedView.el);
- if (this.firstRender) {
- this.router.on("route:loadTab", _.bind(this.setActiveTab, this));
- Backbone.history.start();
- this.firstRender = false;
+ if (this.firstRender) {
+ this.router.on('route:loadTab', _.bind(this.setActiveTab, this));
+ Backbone.history.start();
+ this.firstRender = false;
// Load from history.
- this.router.navigate((Backbone.history.getFragment() || 'about_me'), {trigger: true});
- } else {
+ this.router.navigate((Backbone.history.getFragment() || 'about_me'), {trigger: true});
+ } else {
// Restart the router so the tab will be brought up anew.
- Backbone.history.stop();
- Backbone.history.start();
+ Backbone.history.stop();
+ Backbone.history.start();
+ }
+
+
+ return this;
+ },
+
+ renderFields: function() {
+ var view = this;
+
+ if (this.options.ownProfile) {
+ var fieldView = this.options.accountPrivacyFieldView,
+ settings = this.options.accountSettingsModel;
+ fieldView.profileIsPrivate = !settings.get('year_of_birth');
+ fieldView.requiresParentalConsent = settings.get('requires_parental_consent');
+ fieldView.isAboveMinimumAge = settings.isAboveMinimumAge();
+ fieldView.undelegateEvents();
+ this.$('.wrapper-profile-field-account-privacy').append(fieldView.render().el);
+ fieldView.delegateEvents();
+ }
+
+ this.$('.profile-section-one-fields').append(this.options.usernameFieldView.render().el);
+
+ var imageView = this.options.profileImageFieldView;
+ this.$('.profile-image-field').append(imageView.render().el);
+
+ if (this.showFullProfile()) {
+ _.each(this.options.sectionOneFieldViews, function(fieldView) {
+ view.$('.profile-section-one-fields').append(fieldView.render().el);
+ });
+ }
+ },
+
+ showLoadingError: function() {
+ this.$('.ui-loading-indicator').addClass('is-hidden');
+ this.$('.ui-loading-error').removeClass('is-hidden');
}
+ });
-
- return this;
- },
-
- renderFields: function() {
- var view = this;
-
- if (this.options.ownProfile) {
- var fieldView = this.options.accountPrivacyFieldView,
- settings = this.options.accountSettingsModel;
- fieldView.profileIsPrivate = !settings.get('year_of_birth');
- fieldView.requiresParentalConsent = settings.get('requires_parental_consent');
- fieldView.isAboveMinimumAge = settings.isAboveMinimumAge();
- fieldView.undelegateEvents();
- this.$('.wrapper-profile-field-account-privacy').append(fieldView.render().el);
- fieldView.delegateEvents();
- }
-
- this.$('.profile-section-one-fields').append(this.options.usernameFieldView.render().el);
-
- var imageView = this.options.profileImageFieldView;
- this.$('.profile-image-field').append(imageView.render().el);
-
- if (this.showFullProfile()) {
- _.each(this.options.sectionOneFieldViews, function (fieldView) {
- view.$('.profile-section-one-fields').append(fieldView.render().el);
- });
-
- }
- },
-
- showLoadingError: function () {
- this.$('.ui-loading-indicator').addClass('is-hidden');
- this.$('.ui-loading-error').removeClass('is-hidden');
- }
+ return LearnerProfileView;
});
-
- return LearnerProfileView;
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_profile/views/section_two_tab.js b/lms/static/js/student_profile/views/section_two_tab.js
index 46c832e068..69d3117320 100644
--- a/lms/static/js/student_profile/views/section_two_tab.js
+++ b/lms/static/js/student_profile/views/section_two_tab.js
@@ -1,18 +1,17 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
- 'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/student_profile/section_two.underscore'],
- function (gettext, $, _, Backbone, sectionTwoTemplate) {
-
+ 'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/student_profile/section_two.underscore'],
+ function(gettext, $, _, Backbone, sectionTwoTemplate) {
var SectionTwoTab = Backbone.View.extend({
attributes: {
'class': 'wrapper-profile-section-two'
},
template: _.template(sectionTwoTemplate),
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
},
- render: function () {
+ render: function() {
var self = this;
var showFullProfile = this.options.showFullProfile();
this.$el.html(this.template({
@@ -20,7 +19,7 @@
showFullProfile: showFullProfile
}));
if (showFullProfile) {
- _.each(this.options.viewList, function (fieldView) {
+ _.each(this.options.viewList, function(fieldView) {
self.$el.find('.field-container').append(fieldView.render().el);
});
}
diff --git a/lms/static/js/student_profile/views/share_modal_view.js b/lms/static/js/student_profile/views/share_modal_view.js
index 00d7235b05..1d77997c60 100644
--- a/lms/static/js/student_profile/views/share_modal_view.js
+++ b/lms/static/js/student_profile/views/share_modal_view.js
@@ -1,37 +1,36 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'moment',
'text!templates/student_profile/share_modal.underscore'],
- function (gettext, $, _, Backbone, Moment, badgeModalTemplate) {
-
+ function(gettext, $, _, Backbone, Moment, badgeModalTemplate) {
var ShareModalView = Backbone.View.extend({
attributes: {
'class': 'badges-overlay'
},
template: _.template(badgeModalTemplate),
events: {
- 'click .badges-modal': function (event) {event.stopPropagation();},
+ 'click .badges-modal': function(event) { event.stopPropagation(); },
'click .badges-modal .close': 'close',
'click .badges-overlay': 'close',
'keydown': 'keyAction',
'focus .focusguard-start': 'focusGuardStart',
'focus .focusguard-end': 'focusGuardEnd'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
},
- focusGuardStart: function () {
+ focusGuardStart: function() {
// Should only be selected directly if shift-tabbing from the start, so grab last item.
- this.$el.find("a").last().focus();
+ this.$el.find('a').last().focus();
},
focusGuardEnd: function() {
- this.$el.find(".badges-modal").focus();
+ this.$el.find('.badges-modal').focus();
},
- close: function () {
+ close: function() {
this.$el.fadeOut('short', 'swing', _.bind(this.remove, this));
this.options.shareButton.focus();
},
- keyAction: function (event) {
+ keyAction: function(event) {
if (event.keyCode === $.ui.keyCode.ESCAPE) {
this.close();
}
@@ -41,7 +40,7 @@
// to its positioning.
this.$el.find('.badges-modal').focus();
},
- render: function () {
+ render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
diff --git a/lms/static/js/toggle_login_modal.js b/lms/static/js/toggle_login_modal.js
index e8310716e3..9485801a7c 100644
--- a/lms/static/js/toggle_login_modal.js
+++ b/lms/static/js/toggle_login_modal.js
@@ -1,5 +1,5 @@
-(function($){
- $.fn.extend({
+(function($) {
+ $.fn.extend({
/*
* leanModal prepares an element to be a modal dialog. Call it once on the
* element that launches the dialog, when the page is ready. This function
@@ -10,117 +10,116 @@
* - have an href= attribute identifying the id of the dialog element,
* - have rel='leanModal'.
*/
- leanModal: function(options) {
- var defaults = {
- top: 100,
- overlay: 0.5,
- closeButton: null,
- position: 'fixed'
- }
+ leanModal: function(options) {
+ var defaults = {
+ top: 100,
+ overlay: 0.5,
+ closeButton: null,
+ position: 'fixed'
+ };
- if ($("#lean_overlay").length == 0) {
- var overlay = $("
");
- $("body").append(overlay);
- }
+ if ($('#lean_overlay').length == 0) {
+ var overlay = $("
");
+ $('body').append(overlay);
+ }
- options = $.extend(defaults, options);
+ options = $.extend(defaults, options);
- return this.each(function() {
- var o = options;
+ return this.each(function() {
+ var o = options;
- $(this).click(function(e) {
+ $(this).click(function(e) {
+ $('.modal').hide();
- $(".modal").hide();
+ var modal_id = $(this).attr('href');
- var modal_id = $(this).attr("href");
+ if ($(modal_id).hasClass('video-modal')) {
+ // Video modals need to be cloned before being presented as a modal
+ // This is because actions on the video get recorded in the history.
+ // Deleting the video (clone) prevents the odd back button behavior.
+ var modal_clone = $(modal_id).clone(true, true);
+ modal_clone.attr('id', 'modal_clone');
+ $(modal_id).after(modal_clone);
+ modal_id = '#modal_clone';
+ }
- if ($(modal_id).hasClass("video-modal")) {
- //Video modals need to be cloned before being presented as a modal
- //This is because actions on the video get recorded in the history.
- //Deleting the video (clone) prevents the odd back button behavior.
- var modal_clone = $(modal_id).clone(true, true);
- modal_clone.attr('id', 'modal_clone');
- $(modal_id).after(modal_clone);
- modal_id = '#modal_clone';
- }
+ $('#lean_overlay').click(function(e) {
+ close_modal(modal_id, e);
+ });
- $("#lean_overlay").click(function(e) {
- close_modal(modal_id, e);
- });
-
- $(o.closeButton).click(function(e) {
- close_modal(modal_id, e);
- });
+ $(o.closeButton).click(function(e) {
+ close_modal(modal_id, e);
+ });
// To enable closing of email modal when copy button hit
- $(o.copyEmailButton).click(function(e) {
- close_modal(modal_id, e);
- });
+ $(o.copyEmailButton).click(function(e) {
+ close_modal(modal_id, e);
+ });
- var modal_height = $(modal_id).outerHeight();
- var modal_width = $(modal_id).outerWidth();
+ var modal_height = $(modal_id).outerHeight();
+ var modal_width = $(modal_id).outerWidth();
- $('#lean_overlay').css({ 'display' : 'block', opacity : 0 });
- $('#lean_overlay').fadeTo(200,o.overlay);
+ $('#lean_overlay').css({'display': 'block', opacity: 0});
+ $('#lean_overlay').fadeTo(200, o.overlay);
- $('iframe', modal_id).attr('src', $('iframe', modal_id).data('src'));
- if ($(modal_id).hasClass("email-modal")){
- $(modal_id).css({
- 'width' : 80 + '%',
- 'height' : 80 + '%',
- 'position' : o.position,
- 'opacity' : 0,
- 'z-index' : 11000,
- 'left' : 10 + '%',
- 'top' : 10 + '%'
- })
- } else {
- $(modal_id).css({
- 'position' : o.position,
- 'opacity' : 0,
- 'z-index': 11000,
- 'left' : 50 + '%',
- 'margin-left' : -(modal_width/2) + "px",
- 'top' : o.top + "px"
- })
- }
+ $('iframe', modal_id).attr('src', $('iframe', modal_id).data('src'));
+ if ($(modal_id).hasClass('email-modal')) {
+ $(modal_id).css({
+ 'width': 80 + '%',
+ 'height': 80 + '%',
+ 'position': o.position,
+ 'opacity': 0,
+ 'z-index': 11000,
+ 'left': 10 + '%',
+ 'top': 10 + '%'
+ });
+ } else {
+ $(modal_id).css({
+ 'position': o.position,
+ 'opacity': 0,
+ 'z-index': 11000,
+ 'left': 50 + '%',
+ 'margin-left': -(modal_width / 2) + 'px',
+ 'top': o.top + 'px'
+ });
+ }
- $(modal_id).show().fadeTo(200,1);
- $(modal_id).find(".notice").hide().html("");
- var notice = $(this).data('notice')
- if(notice !== undefined) {
- $notice = $(modal_id).find(".notice");
- $notice.show().html(notice);
+ $(modal_id).show().fadeTo(200, 1);
+ $(modal_id).find('.notice').hide().html('');
+ var notice = $(this).data('notice');
+ if (notice !== undefined) {
+ $notice = $(modal_id).find('.notice');
+ $notice.show().html(notice);
// This is for activating leanModal links that were in the notice. We should have a cleaner way of
// allowing all dynamically added leanmodal links to work.
- $notice.find("a[rel*=leanModal]").leanModal({ top : 120, overlay: 1, closeButton: ".close-modal", position: 'absolute' });
- }
- window.scrollTo(0, 0);
- e.preventDefault();
- });
- });
+ $notice.find('a[rel*=leanModal]').leanModal({top: 120, overlay: 1, closeButton: '.close-modal', position: 'absolute'});
+ }
+ window.scrollTo(0, 0);
+ e.preventDefault();
+ });
+ });
- function close_modal(modal_id, e) {
- $("#lean_overlay").fadeOut(200);
- $('iframe', modal_id).attr('src', '');
- $(modal_id).css({ 'display' : 'none' });
- if (modal_id == '#modal_clone') {
- $(modal_id).remove();
+ function close_modal(modal_id, e) {
+ $('#lean_overlay').fadeOut(200);
+ $('iframe', modal_id).attr('src', '');
+ $(modal_id).css({'display': 'none'});
+ if (modal_id == '#modal_clone') {
+ $(modal_id).remove();
+ }
+ e.preventDefault();
+ }
}
- e.preventDefault();
- }
- }
- });
-
- $(document).ready(function ($) {
- $("a[rel*=leanModal]").each(function () {
- $(this).leanModal({ top : 120, overlay: 1, closeButton: ".close-modal", position: 'absolute' });
- embed = $($(this).attr('href')).find('iframe')
- if (embed.length > 0 && embed.attr('src')) {
- var sep = (embed.attr('src').indexOf("?") > 0) ? '&' : '?';
- embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0');
- embed.attr('src', '');
- }
});
- });
+
+ $(document).ready(function($) {
+ $('a[rel*=leanModal]').each(function() {
+ $(this).leanModal({top: 120, overlay: 1, closeButton: '.close-modal', position: 'absolute'});
+ embed = $($(this).attr('href')).find('iframe');
+ if (embed.length > 0 && embed.attr('src')) {
+ var sep = (embed.attr('src').indexOf('?') > 0) ? '&' : '?';
+ embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0');
+ embed.attr('src', '');
+ }
+ });
+ });
})(jQuery);
diff --git a/lms/static/js/utils/facebook.js b/lms/static/js/utils/facebook.js
index 74b1c2a2d1..d5b8695be0 100644
--- a/lms/static/js/utils/facebook.js
+++ b/lms/static/js/utils/facebook.js
@@ -2,24 +2,24 @@ var FaceBook = (function() {
var _args = {};
return {
- init : function (Args) {
+ init: function(Args) {
_args = Args;
window.fbAsyncInit = function() {
FB.init({
- appId : _args.facebook_app_id,
- xfbml : true,
- version : 'v2.3'
+ appId: _args.facebook_app_id,
+ xfbml: true,
+ version: 'v2.3'
});
};
- (function(d, s, id){
+ (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
- if (d.getElementById(id)) {return;}
+ if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
- js.src = "//connect.facebook.net/en_US/sdk.js";
+ js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
},
- share: function (feed_data) {
+ share: function(feed_data) {
FB.ui({
method: 'feed',
name: feed_data['share_text'],
diff --git a/lms/static/js/utils/navigation.js b/lms/static/js/utils/navigation.js
index 9f46907d0a..fe6d2ba03b 100644
--- a/lms/static/js/utils/navigation.js
+++ b/lms/static/js/utils/navigation.js
@@ -1,7 +1,6 @@
var edx = edx || {},
Navigation = (function() {
-
var navigation = {
init: function() {
@@ -122,9 +121,8 @@ var edx = edx || {},
return {
init: navigation.init
};
-
})();
- edx.util = edx.util || {};
- edx.util.navigation = Navigation;
- edx.util.navigation.init();
+edx.util = edx.util || {};
+edx.util.navigation = Navigation;
+edx.util.navigation.init();
diff --git a/lms/static/js/verify_student/incourse_reverify.js b/lms/static/js/verify_student/incourse_reverify.js
index cad681e848..311c8208e3 100644
--- a/lms/static/js/verify_student/incourse_reverify.js
+++ b/lms/static/js/verify_student/incourse_reverify.js
@@ -7,22 +7,21 @@
*/
var edx = edx || {};
- (function( $, _ ) {
- 'use strict';
- var errorView,
- el = $('#incourse-reverify-container');
+ (function($, _) {
+ 'use strict';
+ var errorView,
+ el = $('#incourse-reverify-container');
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- errorView = new edx.verify_student.ErrorView({
- el: $('#error-container')
- });
+ errorView = new edx.verify_student.ErrorView({
+ el: $('#error-container')
+ });
- return new edx.verify_student.InCourseReverifyView({
- courseKey: el.data('course-key'),
- platformName: el.data('platform-name'),
- usageId: el.data('usage-id'),
- errorModel: errorView.model
- }).render();
-
- })( jQuery, _ );
+ return new edx.verify_student.InCourseReverifyView({
+ courseKey: el.data('course-key'),
+ platformName: el.data('platform-name'),
+ usageId: el.data('usage-id'),
+ errorModel: errorView.model
+ }).render();
+ })(jQuery, _);
diff --git a/lms/static/js/verify_student/models/verification_model.js b/lms/static/js/verify_student/models/verification_model.js
index afe9763564..f5fe173aba 100644
--- a/lms/static/js/verify_student/models/verification_model.js
+++ b/lms/static/js/verify_student/models/verification_model.js
@@ -8,78 +8,77 @@
*/
var edx = edx || {};
- (function( $, Backbone ) {
- 'use strict';
+ (function($, Backbone) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.VerificationModel = Backbone.Model.extend({
+ edx.verify_student.VerificationModel = Backbone.Model.extend({
- defaults: {
+ defaults: {
// If provided, change the user's full name when submitting photos.
- fullName: null,
+ fullName: null,
// Image data for the user's face photo.
- faceImage: "",
+ faceImage: '',
// Image data for the user's ID photo.
// In the case of an in-course reverification, we won't
// need to send this because we'll send the ID photo that
// the user submitted with the initial verification attempt.
- identificationImage: null,
+ identificationImage: null,
// If the verification attempt is associated with a checkpoint
// in a course, we send the the course and checkpoint location.
- courseKey: null,
- checkpoint: null,
- },
+ courseKey: null,
+ checkpoint: null
+ },
- sync: function( method, model ) {
- var headers = { 'X-CSRFToken': $.cookie( 'csrftoken' ) },
- data = {};
+ sync: function(method, model) {
+ var headers = {'X-CSRFToken': $.cookie('csrftoken')},
+ data = {};
- data.face_image = model.get("faceImage");
+ data.face_image = model.get('faceImage');
// The ID photo is optional, since in-course reverification
// re-uses the image from the initial verification attempt.
- if (model.has("identificationImage")) {
- data.photo_id_image = model.get("identificationImage");
- }
+ if (model.has('identificationImage')) {
+ data.photo_id_image = model.get('identificationImage');
+ }
// Full name is an optional parameter; if not provided,
// it won't be changed.
- if (model.has("fullName")) {
- data.full_name = model.get("fullName");
+ if (model.has('fullName')) {
+ data.full_name = model.get('fullName');
// Track the user's decision to change the name on their account
- window.analytics.track( 'edx.bi.user.full_name.changed', {
- category: 'verification'
- });
- }
+ window.analytics.track('edx.bi.user.full_name.changed', {
+ category: 'verification'
+ });
+ }
// If the user entered the verification flow from a checkpoint
// in a course, we need to send the course and checkpoint
// location to associate the attempt with the checkpoint.
- if (model.has("courseKey") && model.has("checkpoint")) {
- data.course_key = model.get("courseKey");
- data.checkpoint = model.get("checkpoint");
- }
+ if (model.has('courseKey') && model.has('checkpoint')) {
+ data.course_key = model.get('courseKey');
+ data.checkpoint = model.get('checkpoint');
+ }
// Submit the request to the server,
// triggering events on success and error.
- $.ajax({
- url: '/verify_student/submit-photos/',
- type: 'POST',
- data: data,
- headers: headers,
- success: function( response ) {
- model.trigger( 'sync', response.url );
- },
- error: function( error ) {
- model.trigger( 'error', error );
- }
- });
- }
- });
-
- })( jQuery, Backbone );
+ $.ajax({
+ url: '/verify_student/submit-photos/',
+ type: 'POST',
+ data: data,
+ headers: headers,
+ success: function(response) {
+ model.trigger('sync', response.url);
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
+ })(jQuery, Backbone);
diff --git a/lms/static/js/verify_student/pay_and_verify.js b/lms/static/js/verify_student/pay_and_verify.js
index 440337c4af..19b97b23de 100644
--- a/lms/static/js/verify_student/pay_and_verify.js
+++ b/lms/static/js/verify_student/pay_and_verify.js
@@ -10,7 +10,7 @@
*/
var edx = edx || {};
-(function( $, _ ) {
+(function($, _) {
'use strict';
var errorView,
el = $('#pay-and-verify-container');
@@ -52,15 +52,15 @@ var edx = edx || {};
userEmail: el.data('user-email'),
hasVisibleReqs: _.some(
el.data('requirements'),
- function( isVisible ) { return isVisible; }
+ function(isVisible) { return isVisible; }
),
upgrade: el.data('msg-key') === 'upgrade',
minPrice: el.data('course-mode-min-price'),
sku: el.data('course-mode-sku'),
contributionAmount: el.data('contribution-amount'),
suggestedPrices: _.filter(
- (el.data('course-mode-suggested-prices').toString()).split(","),
- function( price ) { return Boolean( price ); }
+ (el.data('course-mode-suggested-prices').toString()).split(','),
+ function(price) { return Boolean(price); }
),
currency: el.data('course-mode-currency'),
processors: el.data('processors'),
@@ -68,7 +68,7 @@ var edx = edx || {};
courseModeSlug: el.data('course-mode-slug'),
alreadyVerified: el.data('already-verified'),
verificationGoodUntil: el.data('verification-good-until'),
- isABTesting: el.data('is-ab-testing')
+ isABTesting: el.data('is-ab-testing')
},
'payment-confirmation-step': {
courseKey: el.data('course-key'),
@@ -98,4 +98,4 @@ var edx = edx || {};
}
}
}).render();
-})( jQuery, _ );
+})(jQuery, _);
diff --git a/lms/static/js/verify_student/reverify.js b/lms/static/js/verify_student/reverify.js
index 42d732ae2b..12eb641c4c 100644
--- a/lms/static/js/verify_student/reverify.js
+++ b/lms/static/js/verify_student/reverify.js
@@ -7,38 +7,38 @@
*/
var edx = edx || {};
- (function( $, _ ) {
- 'use strict';
- var errorView,
- el = $('#reverify-container');
+ (function($, _) {
+ 'use strict';
+ var errorView,
+ el = $('#reverify-container');
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
// Initialize an error view for displaying top-level error messages.
- errorView = new edx.verify_student.ErrorView({
- el: $('#error-container')
- });
+ errorView = new edx.verify_student.ErrorView({
+ el: $('#error-container')
+ });
// Initialize the base view, passing in information
// from the data attributes on the parent div.
- return new edx.verify_student.ReverifyView({
- errorModel: errorView.model,
- stepInfo: {
- 'face-photo-step': {
- platformName: el.data('platform-name'),
- captureSoundPath: el.data('capture-sound')
- },
- 'id-photo-step': {
- platformName: el.data('platform-name'),
- captureSoundPath: el.data('capture-sound')
- },
- 'review-photos-step': {
- fullName: el.data('full-name'),
- platformName: el.data('platform-name')
- },
- 'reverify-success-step': {
- platformName: el.data('platform-name')
- }
- }
- }).render();
-})( jQuery, _ );
+ return new edx.verify_student.ReverifyView({
+ errorModel: errorView.model,
+ stepInfo: {
+ 'face-photo-step': {
+ platformName: el.data('platform-name'),
+ captureSoundPath: el.data('capture-sound')
+ },
+ 'id-photo-step': {
+ platformName: el.data('platform-name'),
+ captureSoundPath: el.data('capture-sound')
+ },
+ 'review-photos-step': {
+ fullName: el.data('full-name'),
+ platformName: el.data('platform-name')
+ },
+ 'reverify-success-step': {
+ platformName: el.data('platform-name')
+ }
+ }
+ }).render();
+ })(jQuery, _);
diff --git a/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js b/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
index f9402f56f2..e71976b765 100644
--- a/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
+++ b/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
@@ -17,7 +17,7 @@ var edx = edx || {};
postRender: function() {
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
},
defaultContext: function() {
@@ -29,5 +29,4 @@ var edx = edx || {};
};
}
});
-
})();
diff --git a/lms/static/js/verify_student/views/error_view.js b/lms/static/js/verify_student/views/error_view.js
index 67f385a14f..703655260d 100644
--- a/lms/static/js/verify_student/views/error_view.js
+++ b/lms/static/js/verify_student/views/error_view.js
@@ -3,41 +3,40 @@
*/
var edx = edx || {};
-(function ( $, _, Backbone ) {
- 'use strict';
+ (function($, _, Backbone) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ErrorView = Backbone.View.extend({
+ edx.verify_student.ErrorView = Backbone.View.extend({
- initialize: function( obj ) {
- var ErrorModel = Backbone.Model.extend({});
- this.model = obj.model || new ErrorModel({
- errorTitle: "",
- errorMsg: "",
- shown: false
- });
- this.listenTo( this.model, 'change', this.render );
- },
+ initialize: function(obj) {
+ var ErrorModel = Backbone.Model.extend({});
+ this.model = obj.model || new ErrorModel({
+ errorTitle: '',
+ errorMsg: '',
+ shown: false
+ });
+ this.listenTo(this.model, 'change', this.render);
+ },
- render: function() {
- var renderedHtml = _.template($( '#error-tpl' ).html())(
- {
- errorTitle: this.model.get( 'errorTitle' ),
- errorMsg: this.model.get( 'errorMsg' )
- }
+ render: function() {
+ var renderedHtml = _.template($('#error-tpl').html())(
+ {
+ errorTitle: this.model.get('errorTitle'),
+ errorMsg: this.model.get('errorMsg')
+ }
);
- $( this.el ).html( renderedHtml );
+ $(this.el).html(renderedHtml);
- if ( this.model.get( 'shown' ) ) {
- $( this.el ).show();
- $( "html, body" ).animate({ scrollTop: 0 });
- }
- else {
- $( this.el ).hide();
- }
- }
- });
-
-})( $, _, Backbone );
+ if (this.model.get('shown')) {
+ $(this.el).show();
+ $('html, body').animate({scrollTop: 0});
+ }
+ else {
+ $(this.el).hide();
+ }
+ }
+ });
+ })($, _, Backbone);
diff --git a/lms/static/js/verify_student/views/face_photo_step_view.js b/lms/static/js/verify_student/views/face_photo_step_view.js
index b2654271b2..f9afacb5e5 100644
--- a/lms/static/js/verify_student/views/face_photo_step_view.js
+++ b/lms/static/js/verify_student/views/face_photo_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.FacePhotoStepView = edx.verify_student.StepView.extend({
- templateName: "face_photo_step",
+ templateName: 'face_photo_step',
defaultContext: function() {
return {
@@ -20,7 +20,7 @@ var edx = edx || {};
postRender: function() {
var webcam = edx.verify_student.getSupportedWebcamView({
- el: $( '#facecam' ),
+ el: $('#facecam'),
model: this.model,
modelAttribute: 'faceImage',
submitButton: '#next_step_button',
@@ -29,17 +29,16 @@ var edx = edx || {};
}).render();
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
- this.listenTo( webcam, 'imageCaptured', function() {
+ this.listenTo(webcam, 'imageCaptured', function() {
// Track the user's successful image capture
- window.analytics.track( 'edx.bi.user.face_image.captured', {
+ window.analytics.track('edx.bi.user.face_image.captured', {
category: 'verification'
});
});
- $( '#next_step_button' ).on( 'click', _.bind( this.nextStep, this ) );
- },
+ $('#next_step_button').on('click', _.bind(this.nextStep, this));
+ }
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/id_photo_step_view.js b/lms/static/js/verify_student/views/id_photo_step_view.js
index f89bd3e7ca..aa8ae4a94b 100644
--- a/lms/static/js/verify_student/views/id_photo_step_view.js
+++ b/lms/static/js/verify_student/views/id_photo_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.IDPhotoStepView = edx.verify_student.StepView.extend({
- templateName: "id_photo_step",
+ templateName: 'id_photo_step',
defaultContext: function() {
return {
@@ -20,7 +20,7 @@ var edx = edx || {};
postRender: function() {
var webcam = edx.verify_student.getSupportedWebcamView({
- el: $( '#idcam' ),
+ el: $('#idcam'),
model: this.model,
modelAttribute: 'identificationImage',
submitButton: '#next_step_button',
@@ -29,17 +29,16 @@ var edx = edx || {};
}).render();
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
- this.listenTo( webcam, 'imageCaptured', function() {
+ this.listenTo(webcam, 'imageCaptured', function() {
// Track the user's successful image capture
- window.analytics.track( 'edx.bi.user.identification_image.captured', {
+ window.analytics.track('edx.bi.user.identification_image.captured', {
category: 'verification'
});
});
- $( '#next_step_button' ).on( 'click', _.bind( this.nextStep, this ) );
+ $('#next_step_button').on('click', _.bind(this.nextStep, this));
}
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/image_input_view.js b/lms/static/js/verify_student/views/image_input_view.js
index 3b0ef721b2..80b679d143 100644
--- a/lms/static/js/verify_student/views/image_input_view.js
+++ b/lms/static/js/verify_student/views/image_input_view.js
@@ -8,105 +8,104 @@
var edx = edx || {};
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ImageInputView = Backbone.View.extend({
+ edx.verify_student.ImageInputView = Backbone.View.extend({
- template: '#image_input-tpl',
+ template: '#image_input-tpl',
- initialize: function( obj ) {
- this.$submitButton = obj.submitButton ? $( obj.submitButton ) : '';
- this.modelAttribute = obj.modelAttribute || '';
- this.errorModel = obj.errorModel || null;
- },
+ initialize: function(obj) {
+ this.$submitButton = obj.submitButton ? $(obj.submitButton) : '';
+ this.modelAttribute = obj.modelAttribute || '';
+ this.errorModel = obj.errorModel || null;
+ },
- render: function() {
- var renderedHtml = _.template( $( this.template ).html())({});
- $( this.el ).html( renderedHtml );
+ render: function() {
+ var renderedHtml = _.template($(this.template).html())({});
+ $(this.el).html(renderedHtml);
// Set the submit button to disabled by default
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
- this.$input = $( 'input.image-upload' );
- this.$preview = $( 'img.preview' );
- this.$input.on('change', _.bind( this.handleInputChange, this ) );
+ this.$input = $('input.image-upload');
+ this.$preview = $('img.preview');
+ this.$input.on('change', _.bind(this.handleInputChange, this));
// Initially hide the preview
- this.displayImage( false );
+ this.displayImage(false);
- return this;
- },
+ return this;
+ },
- handleInputChange: function( event ) {
- var files = event.target.files,
- reader = new FileReader();
- if ( files[0] && files[0].type.match( 'image.[png|jpg|jpeg]' ) ) {
- reader.onload = _.bind( this.handleImageUpload, this );
- reader.onerror = _.bind( this.handleUploadError, this );
- reader.readAsDataURL( files[0] );
- } else if ( files.length === 0 ) {
- this.handleUploadError( false );
- } else {
- this.handleUploadError( true );
- }
- },
+ handleInputChange: function(event) {
+ var files = event.target.files,
+ reader = new FileReader();
+ if (files[0] && files[0].type.match('image.[png|jpg|jpeg]')) {
+ reader.onload = _.bind(this.handleImageUpload, this);
+ reader.onerror = _.bind(this.handleUploadError, this);
+ reader.readAsDataURL(files[0]);
+ } else if (files.length === 0) {
+ this.handleUploadError(false);
+ } else {
+ this.handleUploadError(true);
+ }
+ },
- handleImageUpload: function( event ) {
- var imageData = event.target.result;
- this.model.set( this.modelAttribute, imageData );
- this.displayImage( imageData );
- this.setSubmitButtonEnabled( true );
+ handleImageUpload: function(event) {
+ var imageData = event.target.result;
+ this.model.set(this.modelAttribute, imageData);
+ this.displayImage(imageData);
+ this.setSubmitButtonEnabled(true);
// Hide any errors we may have displayed previously
- if ( this.errorModel ) {
- this.errorModel.set({ shown: false });
- }
+ if (this.errorModel) {
+ this.errorModel.set({shown: false});
+ }
- this.trigger( 'imageCaptured' );
- },
+ this.trigger('imageCaptured');
+ },
- displayImage: function( imageData ) {
- if ( imageData ) {
- this.$preview
- .attr( 'src', imageData )
+ displayImage: function(imageData) {
+ if (imageData) {
+ this.$preview
+ .attr('src', imageData)
.removeClass('is-hidden')
.attr('aria-hidden', 'false');
- } else {
- this.$preview
- .attr( 'src', '' )
+ } else {
+ this.$preview
+ .attr('src', '')
.addClass('is-hidden')
.attr('aria-hidden', 'true');
- }
- },
+ }
+ },
- handleUploadError: function( displayError ) {
- this.displayImage( null );
- this.setSubmitButtonEnabled( false );
- if ( this.errorModel ) {
- if ( displayError ) {
- this.errorModel.set({
- errorTitle: gettext( 'Image Upload Error' ),
- errorMsg: gettext( 'Please verify that you have uploaded a valid image (PNG and JPEG).' ),
- shown: true
- });
- } else {
- this.errorModel.set({
- shown: false
- });
- }
- }
- this.trigger( 'error' );
- },
+ handleUploadError: function(displayError) {
+ this.displayImage(null);
+ this.setSubmitButtonEnabled(false);
+ if (this.errorModel) {
+ if (displayError) {
+ this.errorModel.set({
+ errorTitle: gettext('Image Upload Error'),
+ errorMsg: gettext('Please verify that you have uploaded a valid image (PNG and JPEG).'),
+ shown: true
+ });
+ } else {
+ this.errorModel.set({
+ shown: false
+ });
+ }
+ }
+ this.trigger('error');
+ },
- setSubmitButtonEnabled: function( isEnabled ) {
- this.$submitButton
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ this.$submitButton
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- }
- });
-
- })( jQuery, _, Backbone, gettext );
+ }
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/incourse_reverify_view.js b/lms/static/js/verify_student/views/incourse_reverify_view.js
index 1587f44aef..bbcaec2b19 100644
--- a/lms/static/js/verify_student/views/incourse_reverify_view.js
+++ b/lms/static/js/verify_student/views/incourse_reverify_view.js
@@ -6,43 +6,43 @@
*/
var edx = edx || {};
- (function( $, _, _s, Backbone, gettext, HtmlUtils ) {
- 'use strict';
+ (function($, _, _s, Backbone, gettext, HtmlUtils) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.InCourseReverifyView = Backbone.View.extend({
+ edx.verify_student.InCourseReverifyView = Backbone.View.extend({
- el: '#incourse-reverify-container',
- templateId: '#incourse_reverify-tpl',
- submitButtonId: '#submit',
+ el: '#incourse-reverify-container',
+ templateId: '#incourse_reverify-tpl',
+ submitButtonId: '#submit',
- events: {
- 'click #submit': 'submitPhoto'
- },
+ events: {
+ 'click #submit': 'submitPhoto'
+ },
- initialize: function( obj ) {
- _.mixin( _s.exports() );
+ initialize: function(obj) {
+ _.mixin(_s.exports());
- this.errorModel = obj.errorModel || null;
- this.courseKey = obj.courseKey || null;
- this.platformName = obj.platformName || null;
- this.usageId = obj.usageId || null;
+ this.errorModel = obj.errorModel || null;
+ this.courseKey = obj.courseKey || null;
+ this.platformName = obj.platformName || null;
+ this.usageId = obj.usageId || null;
- this.model = new edx.verify_student.VerificationModel({
- courseKey: this.courseKey,
- checkpoint: this.usageId
- });
+ this.model = new edx.verify_student.VerificationModel({
+ courseKey: this.courseKey,
+ checkpoint: this.usageId
+ });
- this.listenTo( this.model, 'sync', _.bind( this.handleSubmitPhotoSuccess, this ));
- this.listenTo( this.model, 'error', _.bind( this.handleSubmissionError, this ));
- },
+ this.listenTo(this.model, 'sync', _.bind(this.handleSubmitPhotoSuccess, this));
+ this.listenTo(this.model, 'error', _.bind(this.handleSubmissionError, this));
+ },
- render: function() {
- HtmlUtils.setHtml(
+ render: function() {
+ HtmlUtils.setHtml(
this.el,
- HtmlUtils.template($( this.templateId ).html())(
+ HtmlUtils.template($(this.templateId).html())(
{
courseKey: this.courseKey,
platformName: this.platformName
@@ -53,53 +53,53 @@
// Render the webcam view *after* the parent view
// so that the container div for the webcam
// exists in the DOM.
- this.renderWebcam();
+ this.renderWebcam();
- return this;
- },
+ return this;
+ },
- renderWebcam: function() {
- edx.verify_student.getSupportedWebcamView({
- el: $( '#webcam' ),
- model: this.model,
- modelAttribute: 'faceImage',
- submitButton: this.submitButtonId,
- errorModel: this.errorModel
- }).render();
- },
+ renderWebcam: function() {
+ edx.verify_student.getSupportedWebcamView({
+ el: $('#webcam'),
+ model: this.model,
+ modelAttribute: 'faceImage',
+ submitButton: this.submitButtonId,
+ errorModel: this.errorModel
+ }).render();
+ },
- submitPhoto: function() {
+ submitPhoto: function() {
// disable the submit button to prevent multiple submissions.
- this.setSubmitButtonEnabled(false);
- this.model.save();
- },
+ this.setSubmitButtonEnabled(false);
+ this.model.save();
+ },
- handleSubmitPhotoSuccess: function(redirect_url) {
+ handleSubmitPhotoSuccess: function(redirect_url) {
// Redirect back to the courseware at the checkpoint location
- window.location.href = redirect_url;
- },
+ window.location.href = redirect_url;
+ },
- handleSubmissionError: function(xhr) {
- var errorMsg = gettext( 'An error has occurred. Please try again later.' );
+ handleSubmissionError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again later.');
// Re-enable the submit button to allow the user to retry
- this.setSubmitButtonEnabled( true );
+ this.setSubmitButtonEnabled(true);
- if ( xhr.status === 400 ) {
- errorMsg = xhr.responseText;
- }
+ if (xhr.status === 400) {
+ errorMsg = xhr.responseText;
+ }
- this.errorModel.set({
- errorTitle: gettext( 'Could not submit photos' ),
- errorMsg: errorMsg,
- shown: true
- });
- },
- setSubmitButtonEnabled: function( isEnabled ) {
- $(this.submitButtonId)
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ this.errorModel.set({
+ errorTitle: gettext('Could not submit photos'),
+ errorMsg: errorMsg,
+ shown: true
+ });
+ },
+ setSubmitButtonEnabled: function(isEnabled) {
+ $(this.submitButtonId)
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- }
- });
-})(jQuery, _, _.str, Backbone, gettext, edx.HtmlUtils);
+ }
+ });
+ })(jQuery, _, _.str, Backbone, gettext, edx.HtmlUtils);
diff --git a/lms/static/js/verify_student/views/intro_step_view.js b/lms/static/js/verify_student/views/intro_step_view.js
index dd0e75cbc6..5fb9d0bc3d 100644
--- a/lms/static/js/verify_student/views/intro_step_view.js
+++ b/lms/static/js/verify_student/views/intro_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.IntroStepView = edx.verify_student.StepView.extend({
- templateName: "intro_step",
+ templateName: 'intro_step',
defaultContext: function() {
return {
@@ -31,9 +31,8 @@ var edx = edx || {};
// second step.
postRender: function() {
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
}
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/make_payment_step_view.js b/lms/static/js/verify_student/views/make_payment_step_view.js
index 65019c7adb..3e9eb7e532 100644
--- a/lms/static/js/verify_student/views/make_payment_step_view.js
+++ b/lms/static/js/verify_student/views/make_payment_step_view.js
@@ -3,22 +3,22 @@
*/
var edx = edx || {};
-(function( $, _, gettext, interpolate_text ) {
+(function($, _, gettext, interpolate_text) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.MakePaymentStepView = edx.verify_student.StepView.extend({
- templateName: "make_payment_step",
+ templateName: 'make_payment_step',
btnClass: 'action-primary',
- initialize: function( obj ) {
- _.extend( this, obj );
- if (this.templateContext().isABTesting) {
- this.templateName = 'make_payment_step_ab_testing';
- this.btnClass = 'action-primary-blue';
- }
+ initialize: function(obj) {
+ _.extend(this, obj);
+ if (this.templateContext().isABTesting) {
+ this.templateName = 'make_payment_step_ab_testing';
+ this.btnClass = 'action-primary-blue';
+ }
},
defaultContext: function() {
@@ -42,25 +42,25 @@ var edx = edx || {};
};
},
- _getProductText: function( modeSlug, isUpgrade ) {
- switch ( modeSlug ) {
- case "professional":
- return gettext( "Professional Education Verified Certificate" );
- case "no-id-professional":
- return gettext( "Professional Education" );
- default:
- if ( isUpgrade ) {
- return gettext( "Verified Certificate upgrade" );
- } else {
- return gettext( "Verified Certificate" );
- }
+ _getProductText: function(modeSlug, isUpgrade) {
+ switch (modeSlug) {
+ case 'professional':
+ return gettext('Professional Education Verified Certificate');
+ case 'no-id-professional':
+ return gettext('Professional Education');
+ default:
+ if (isUpgrade) {
+ return gettext('Verified Certificate upgrade');
+ } else {
+ return gettext('Verified Certificate');
+ }
}
},
_getPaymentButtonText: function(processorName) {
- if (processorName.toLowerCase().substr(0, 11)=='cybersource') {
+ if (processorName.toLowerCase().substr(0, 11) == 'cybersource') {
return gettext('Checkout');
- } else if (processorName.toLowerCase()=='paypal') {
+ } else if (processorName.toLowerCase() == 'paypal') {
return gettext('Checkout with PayPal');
} else {
// This is mainly for testing as no other processors are supported right now.
@@ -80,7 +80,7 @@ var edx = edx || {};
var templateContext = this.templateContext(),
hasVisibleReqs = _.some(
templateContext.requirements,
- function( isVisible ) { return isVisible; }
+ function(isVisible) { return isVisible; }
),
// This a hack to appease /lms/static/js/spec/verify_student/pay_and_verify_view_spec.js,
// which does not load an actual template context.
@@ -88,7 +88,7 @@ var edx = edx || {};
self = this;
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'payment', this.templateName );
+ window.analytics.page('payment', this.templateName);
// The contribution section is hidden by default
// Display it if the user hasn't already selected an amount
@@ -98,22 +98,22 @@ var edx = edx || {};
// Otherwise, there's absolutely nothing to do on this page.
// In the future, we'll likely skip directly to payment
// from the track selection page if this happens.
- if ( templateContext.upgrade || !templateContext.contributionAmount || !hasVisibleReqs ) {
- $( '.wrapper-task' ).removeClass( 'hidden' ).removeAttr( 'aria-hidden' );
+ if (templateContext.upgrade || !templateContext.contributionAmount || !hasVisibleReqs) {
+ $('.wrapper-task').removeClass('hidden').removeAttr('aria-hidden');
}
- if ( templateContext.suggestedPrices.length > 0 ) {
+ if (templateContext.suggestedPrices.length > 0) {
// Enable the payment button once an amount is chosen
- $( 'input[name="contribution"]' ).on( 'click', _.bind( this.setPaymentEnabled, this ) );
+ $('input[name="contribution"]').on('click', _.bind(this.setPaymentEnabled, this));
} else {
// If there is only one payment option, then the user isn't shown
// radio buttons, so we need to enable the radio button.
- this.setPaymentEnabled( true );
+ this.setPaymentEnabled(true);
}
// render the name of the product being paid for
- $( 'div.payment-buttons span.product-name').append(
- self._getProductText( templateContext.courseModeSlug, templateContext.upgrade )
+ $('div.payment-buttons span.product-name').append(
+ self._getProductText(templateContext.courseModeSlug, templateContext.upgrade)
);
if (processors.length === 0) {
@@ -122,26 +122,26 @@ var edx = edx || {};
errorTitle: gettext('All payment options are currently unavailable.'),
errorMsg: gettext('Try the transaction again in a few minutes.'),
shown: true
- })
+ });
}
else {
// create a button for each payment processor
_.each(processors.reverse(), function(processorName) {
- $( 'div.payment-buttons' ).append( self._getPaymentButtonHtml(processorName) );
+ $('div.payment-buttons').append(self._getPaymentButtonHtml(processorName));
});
}
// Handle payment submission
- $( '.payment-button' ).on( 'click', _.bind( this.createOrder, this ) );
+ $('.payment-button').on('click', _.bind(this.createOrder, this));
},
- setPaymentEnabled: function( isEnabled ) {
- if ( _.isUndefined( isEnabled ) ) {
+ setPaymentEnabled: function(isEnabled) {
+ if (_.isUndefined(isEnabled)) {
isEnabled = true;
}
- $( '.payment-button' )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ $('.payment-button')
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
},
@@ -160,9 +160,9 @@ var edx = edx || {};
};
// Disable the payment button to prevent multiple submissions
- this.setPaymentEnabled( false );
+ this.setPaymentEnabled(false);
- $( event.target ).toggleClass( 'is-selected' );
+ $(event.target).toggleClass('is-selected');
// Create the order for the amount
$.ajax({
@@ -176,24 +176,23 @@ var edx = edx || {};
success: this.handleCreateOrderResponse,
error: this.handleCreateOrderError
});
-
},
- handleCreateOrderResponse: function( paymentData ) {
+ handleCreateOrderResponse: function(paymentData) {
// At this point, the basket has been created on the server,
// and we've received signed payment parameters.
// We need to dynamically construct a form using
// these parameters, then submit it to the payment processor.
// This will send the user to an externally-hosted page
// where she can proceed with payment.
- var form = $( '#payment-processor-form' );
+ var form = $('#payment-processor-form');
- $( 'input', form ).remove();
+ $('input', form).remove();
- form.attr( 'action', paymentData.payment_page_url );
- form.attr( 'method', 'POST' );
+ form.attr('action', paymentData.payment_page_url);
+ form.attr('method', 'POST');
- _.each( paymentData.payment_form_data, function( value, key ) {
+ _.each(paymentData.payment_form_data, function(value, key) {
$(' ').attr({
type: 'hidden',
name: key,
@@ -204,70 +203,70 @@ var edx = edx || {};
// Marketing needs a way to tell the difference between users
// leaving for the payment processor and users dropping off on
// this page. A virtual pageview can be used to do this.
- window.analytics.page( 'payment', 'payment_processor_step' );
+ window.analytics.page('payment', 'payment_processor_step');
- this.submitForm( form );
+ this.submitForm(form);
},
- handleCreateOrderError: function( xhr ) {
- var errorMsg = gettext( 'An error has occurred. Please try again.' );
+ handleCreateOrderError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again.');
- if ( xhr.status === 400 ) {
+ if (xhr.status === 400) {
errorMsg = xhr.responseText;
}
this.errorModel.set({
- errorTitle: gettext( 'Could not submit order' ),
+ errorTitle: gettext('Could not submit order'),
errorMsg: errorMsg,
shown: true
});
// Re-enable the button so the user can re-try
- this.setPaymentEnabled( true );
+ this.setPaymentEnabled(true);
- $( '.payment-button' ).toggleClass( 'is-selected', false );
+ $('.payment-button').toggleClass('is-selected', false);
},
getPaymentAmount: function() {
- var contributionInput = $( 'input[name="contribution"]:checked' , this.el),
+ var contributionInput = $('input[name="contribution"]:checked', this.el),
amount = null;
- if ( contributionInput.attr('id') === 'contribution-other' ) {
- amount = $( 'input[name="contribution-other-amt"]' , this.el ).val();
+ if (contributionInput.attr('id') === 'contribution-other') {
+ amount = $('input[name="contribution-other-amt"]', this.el).val();
} else {
amount = contributionInput.val();
}
// If no suggested prices are available, then the user does not
// get the option to select a price. Default to the minimum.
- if ( !amount ) {
+ if (!amount) {
amount = this.templateContext().minPrice;
}
return amount;
},
- selectPaymentAmount: function( amount ) {
- var amountFloat = parseFloat( amount ),
+ selectPaymentAmount: function(amount) {
+ var amountFloat = parseFloat(amount),
foundPrice,
sel;
// Check if we have a suggested price that matches the amount
foundPrice = _.find(
this.stepData.suggestedPrices,
- function( price ) {
- return parseFloat( price ) === amountFloat;
+ function(price) {
+ return parseFloat(price) === amountFloat;
}
);
// If we've found an option for the price, select it.
- if ( foundPrice ) {
- sel = _.sprintf( 'input[name="contribution"][value="%s"]', foundPrice );
- $( sel ).prop( 'checked', true );
+ if (foundPrice) {
+ sel = _.sprintf('input[name="contribution"][value="%s"]', foundPrice);
+ $(sel).prop('checked', true);
} else {
// Otherwise, enter the value into the text box
- $( '#contribution-other-amt', this.el ).val( amount );
- $( '#contribution-other', this.el ).prop( 'checked', true );
+ $('#contribution-other-amt', this.el).val(amount);
+ $('#contribution-other', this.el).prop('checked', true);
}
// In either case, enable the payment button
@@ -277,10 +276,9 @@ var edx = edx || {};
},
// Stubbed out in tests
- submitForm: function( form ) {
+ submitForm: function(form) {
form.submit();
}
});
-
-})( jQuery, _, gettext, interpolate_text );
+})(jQuery, _, gettext, interpolate_text);
diff --git a/lms/static/js/verify_student/views/pay_and_verify_view.js b/lms/static/js/verify_student/views/pay_and_verify_view.js
index 5c6239479d..386030598b 100644
--- a/lms/static/js/verify_student/views/pay_and_verify_view.js
+++ b/lms/static/js/verify_student/views/pay_and_verify_view.js
@@ -24,20 +24,20 @@ var edx = edx || {};
'review-photos-step'
],
- initialize: function( obj ) {
+ initialize: function(obj) {
this.errorModel = obj.errorModel || null;
this.displaySteps = obj.displaySteps || [];
this.courseKey = obj.courseKey || null;
this.checkpointLocation = obj.checkpointLocation || null;
- this.initializeStepViews( obj.stepInfo || {} );
+ this.initializeStepViews(obj.stepInfo || {});
this.currentStepIndex = _.indexOf(
- _.pluck( this.displaySteps, 'name' ),
+ _.pluck(this.displaySteps, 'name'),
obj.currentStep
);
},
- initializeStepViews: function( stepInfo ) {
+ initializeStepViews: function(stepInfo) {
var i,
stepName,
stepData,
@@ -73,22 +73,22 @@ var edx = edx || {};
checkpoint: this.checkpointLocation
});
- for ( i = 0; i < this.displaySteps.length; i++ ) {
+ for (i = 0; i < this.displaySteps.length; i++) {
stepName = this.displaySteps[i].name;
subview = null;
- if ( i < this.displaySteps.length - 1) {
+ if (i < this.displaySteps.length - 1) {
nextStepTitle = this.displaySteps[i + 1].title;
} else {
- nextStepTitle = "";
+ nextStepTitle = '';
}
- if ( subviewConstructors.hasOwnProperty( stepName ) ) {
+ if (subviewConstructors.hasOwnProperty(stepName)) {
stepData = {};
// Add any info specific to this step
- if ( stepInfo.hasOwnProperty( stepName ) ) {
- _.extend( stepData, stepInfo[ stepName ] );
+ if (stepInfo.hasOwnProperty(stepName)) {
+ _.extend(stepData, stepInfo[stepName]);
}
subviewConfig = {
@@ -98,19 +98,19 @@ var edx = edx || {};
};
// For photo verification steps, set the shared photo model
- if ( this.VERIFICATION_VIEW_NAMES.indexOf(stepName) >= 0 ) {
- _.extend( subviewConfig, { model: verificationModel } );
+ if (this.VERIFICATION_VIEW_NAMES.indexOf(stepName) >= 0) {
+ _.extend(subviewConfig, {model: verificationModel});
}
// Create the subview instance
// Note that we are NOT yet rendering the view,
// so this doesn't trigger GET requests or modify
// the DOM.
- this.subviews[stepName] = new subviewConstructors[stepName]( subviewConfig );
+ this.subviews[stepName] = new subviewConstructors[stepName](subviewConfig);
// Listen for events to change the current step
- this.listenTo( this.subviews[stepName], 'next-step', this.nextStep );
- this.listenTo( this.subviews[stepName], 'go-to-step', this.goToStep );
+ this.listenTo(this.subviews[stepName], 'next-step', this.nextStep);
+ this.listenTo(this.subviews[stepName], 'go-to-step', this.goToStep);
}
}
},
@@ -124,7 +124,7 @@ var edx = edx || {};
var stepName, stepView, stepEl;
// Get or create the step container
- stepEl = $("#current-step-container");
+ stepEl = $('#current-step-container');
if (!stepEl.length) {
stepEl = $('
').appendTo(this.el);
}
@@ -132,8 +132,8 @@ var edx = edx || {};
// Render the subview
// When the view is rendered, it will overwrite the existing
// step in the DOM.
- stepName = this.displaySteps[ this.currentStepIndex ].name;
- stepView = this.subviews[ stepName ];
+ stepName = this.displaySteps[this.currentStepIndex].name;
+ stepView = this.subviews[stepName];
stepView.el = stepEl;
stepView.render();
},
@@ -146,18 +146,17 @@ var edx = edx || {};
this.render();
},
- goToStep: function( stepName ) {
+ goToStep: function(stepName) {
var stepIndex = _.indexOf(
- _.pluck( this.displaySteps, 'name' ),
+ _.pluck(this.displaySteps, 'name'),
stepName
);
- if ( stepIndex >= 0 ) {
+ if (stepIndex >= 0) {
this.currentStepIndex = stepIndex;
}
this.render();
}
});
-
})(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/payment_confirmation_step_view.js b/lms/static/js/verify_student/views/payment_confirmation_step_view.js
index 5e581dc7d7..cba61eebc6 100644
--- a/lms/static/js/verify_student/views/payment_confirmation_step_view.js
+++ b/lms/static/js/verify_student/views/payment_confirmation_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $, _, gettext ) {
+(function($, _, gettext) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.PaymentConfirmationStepView = edx.verify_student.StepView.extend({
- templateName: "payment_confirmation_step",
+ templateName: 'payment_confirmation_step',
defaultContext: function() {
return {
@@ -40,19 +40,19 @@ var edx = edx || {};
* @return {object} A JQuery promise that resolves with the modified
* template context.
*/
- updateContext: function( templateContext ) {
+ updateContext: function(templateContext) {
var view = this;
return $.Deferred(
- function( defer ) {
- var paymentOrderNum = $.url( '?payment-order-num' );
- if ( paymentOrderNum ) {
+ function(defer) {
+ var paymentOrderNum = $.url('?payment-order-num');
+ if (paymentOrderNum) {
// If there is a payment order number, try to retrieve
// the receipt information from the shopping cart.
- view.getReceiptData( paymentOrderNum ).done(
- function( data ) {
+ view.getReceiptData(paymentOrderNum).done(
+ function(data) {
// Add the receipt info to the template context
- _.extend( templateContext, { receipt: this.receiptContext( data ) } );
- defer.resolveWith( view, [ templateContext ]);
+ _.extend(templateContext, {receipt: this.receiptContext(data)});
+ defer.resolveWith(view, [templateContext]);
}
).fail(function() {
// Display an error
@@ -61,16 +61,16 @@ var edx = edx || {};
defer.rejectWith(
this,
[
- gettext( "Error" ),
- gettext( "Could not retrieve payment information" )
+ gettext('Error'),
+ gettext('Could not retrieve payment information')
]
);
});
} else {
// If no payment order is provided, return the original context
// The template is responsible for displaying a default state.
- _.extend( templateContext, { receipt: null } );
- defer.resolveWith( view, [ templateContext ]);
+ _.extend(templateContext, {receipt: null});
+ defer.resolveWith(view, [templateContext]);
}
}
).promise();
@@ -87,15 +87,15 @@ var edx = edx || {};
$verifyLaterButton = $('#verify_later_button');
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'payment', this.templateName );
+ window.analytics.page('payment', this.templateName);
// Track the user's decision to verify immediately
- window.analytics.trackLink( $verifyNowButton, 'edx.bi.user.verification.immediate', {
+ window.analytics.trackLink($verifyNowButton, 'edx.bi.user.verification.immediate', {
category: 'verification'
});
// Track the user's decision to defer their verification
- window.analytics.trackLink( $verifyLaterButton, 'edx.bi.user.verification.deferred', {
+ window.analytics.trackLink($verifyLaterButton, 'edx.bi.user.verification.deferred', {
category: 'verification'
});
},
@@ -105,9 +105,9 @@ var edx = edx || {};
* @param {int} paymentOrderNum The order number of the payment.
* @return {object} JQuery Promise.
*/
- getReceiptData: function( paymentOrderNum ) {
+ getReceiptData: function(paymentOrderNum) {
return $.ajax({
- url: _.sprintf( '/shoppingcart/receipt/%s/', paymentOrderNum ),
+ url: _.sprintf('/shoppingcart/receipt/%s/', paymentOrderNum),
type: 'GET',
dataType: 'json',
context: this
@@ -121,7 +121,7 @@ var edx = edx || {};
* @param {object} data Receipt data received from the server
* @return {object} Receipt template context.
*/
- receiptContext: function( data ) {
+ receiptContext: function(data) {
var view = this,
receiptContext;
@@ -129,8 +129,8 @@ var edx = edx || {};
orderNum: data.orderNum,
currency: data.currency,
purchasedDatetime: data.purchase_datetime,
- totalCost: view.formatMoney( data.total_cost ),
- isRefunded: data.status === "refunded",
+ totalCost: view.formatMoney(data.total_cost),
+ isRefunded: data.status === 'refunded',
billedTo: {
firstName: data.billed_to.first_name,
lastName: data.billed_to.last_name,
@@ -144,10 +144,10 @@ var edx = edx || {};
receiptContext.items = _.map(
data.items,
- function( item ) {
+ function(item) {
return {
lineDescription: item.line_desc,
- cost: view.formatMoney( item.line_cost )
+ cost: view.formatMoney(item.line_cost)
};
}
);
@@ -155,9 +155,8 @@ var edx = edx || {};
return receiptContext;
},
- formatMoney: function( moneyStr ) {
- return Number( moneyStr ).toFixed(2);
+ formatMoney: function(moneyStr) {
+ return Number(moneyStr).toFixed(2);
}
});
-
-})( jQuery, _, gettext );
+})(jQuery, _, gettext);
diff --git a/lms/static/js/verify_student/views/reverify_success_step_view.js b/lms/static/js/verify_student/views/reverify_success_step_view.js
index 6d87d12eec..939f3abfac 100644
--- a/lms/static/js/verify_student/views/reverify_success_step_view.js
+++ b/lms/static/js/verify_student/views/reverify_success_step_view.js
@@ -6,12 +6,11 @@
var edx = edx || {};
(function() {
- 'use strict';
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
-
- edx.verify_student.ReverifySuccessStepView = edx.verify_student.StepView.extend({
- templateName: 'reverify_success_step'
- });
+ edx.verify_student = edx.verify_student || {};
+ edx.verify_student.ReverifySuccessStepView = edx.verify_student.StepView.extend({
+ templateName: 'reverify_success_step'
+ });
})();
diff --git a/lms/static/js/verify_student/views/reverify_view.js b/lms/static/js/verify_student/views/reverify_view.js
index 10547cddd9..55d5aabc60 100644
--- a/lms/static/js/verify_student/views/reverify_view.js
+++ b/lms/static/js/verify_student/views/reverify_view.js
@@ -9,107 +9,106 @@
var edx = edx || {};
-(function($, _, Backbone, gettext) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ReverifyView = Backbone.View.extend({
- el: '#reverify-container',
+ edx.verify_student.ReverifyView = Backbone.View.extend({
+ el: '#reverify-container',
- stepOrder: [
- "face-photo-step",
- "id-photo-step",
- "review-photos-step",
- "reverify-success-step"
- ],
- stepViews: {},
+ stepOrder: [
+ 'face-photo-step',
+ 'id-photo-step',
+ 'review-photos-step',
+ 'reverify-success-step'
+ ],
+ stepViews: {},
- initialize: function( obj ) {
- this.errorModel = obj.errorModel || null;
- this.initializeStepViews( obj.stepInfo || {} );
- this.currentStepIndex = 0;
- },
+ initialize: function(obj) {
+ this.errorModel = obj.errorModel || null;
+ this.initializeStepViews(obj.stepInfo || {});
+ this.currentStepIndex = 0;
+ },
- initializeStepViews: function( stepInfo ) {
- var verificationModel, stepViewConstructors, nextStepTitles;
+ initializeStepViews: function(stepInfo) {
+ var verificationModel, stepViewConstructors, nextStepTitles;
// We need to initialize this here, because
// outside of this method the subview classes
// might not yet have been loaded.
- stepViewConstructors = {
- 'face-photo-step': edx.verify_student.FacePhotoStepView,
- 'id-photo-step': edx.verify_student.IDPhotoStepView,
- 'review-photos-step': edx.verify_student.ReviewPhotosStepView,
- 'reverify-success-step': edx.verify_student.ReverifySuccessStepView
- };
+ stepViewConstructors = {
+ 'face-photo-step': edx.verify_student.FacePhotoStepView,
+ 'id-photo-step': edx.verify_student.IDPhotoStepView,
+ 'review-photos-step': edx.verify_student.ReviewPhotosStepView,
+ 'reverify-success-step': edx.verify_student.ReverifySuccessStepView
+ };
- nextStepTitles = [
- gettext( "Take a photo of your ID" ),
- gettext( "Review your info" ),
- gettext( "Confirm" ),
- ""
- ];
+ nextStepTitles = [
+ gettext('Take a photo of your ID'),
+ gettext('Review your info'),
+ gettext('Confirm'),
+ ''
+ ];
// Create the verification model, which is shared
// among the different steps. This allows
// one step to save photos and another step
// to submit them.
- verificationModel = new edx.verify_student.VerificationModel();
+ verificationModel = new edx.verify_student.VerificationModel();
- _.each(this.stepOrder, function(name, index) {
- var stepView = new stepViewConstructors[name]({
- errorModel: this.errorModel,
- nextStepTitle: nextStepTitles[index],
- stepData: stepInfo[name],
- model: verificationModel
- });
+ _.each(this.stepOrder, function(name, index) {
+ var stepView = new stepViewConstructors[name]({
+ errorModel: this.errorModel,
+ nextStepTitle: nextStepTitles[index],
+ stepData: stepInfo[name],
+ model: verificationModel
+ });
- this.listenTo(stepView, 'next-step', this.nextStep);
- this.listenTo(stepView, 'go-to-step', this.goToStep);
+ this.listenTo(stepView, 'next-step', this.nextStep);
+ this.listenTo(stepView, 'go-to-step', this.goToStep);
- this.stepViews[name] = stepView;
- }, this);
- },
+ this.stepViews[name] = stepView;
+ }, this);
+ },
- render: function() {
- this.renderCurrentStep();
- return this;
- },
+ render: function() {
+ this.renderCurrentStep();
+ return this;
+ },
- renderCurrentStep: function() {
- var stepView, stepEl;
+ renderCurrentStep: function() {
+ var stepView, stepEl;
// Get or create the step container
- stepEl = $("#current-step-container");
- if (!stepEl.length) {
- stepEl = $('
').appendTo(this.el);
- }
+ stepEl = $('#current-step-container');
+ if (!stepEl.length) {
+ stepEl = $('
').appendTo(this.el);
+ }
// Render the step subview
// When the view is rendered, it will overwrite the existing step in the DOM.
- stepView = this.stepViews[ this.stepOrder[ this.currentStepIndex ] ];
- stepView.el = stepEl;
- stepView.render();
- },
+ stepView = this.stepViews[this.stepOrder[this.currentStepIndex]];
+ stepView.el = stepEl;
+ stepView.render();
+ },
- nextStep: function() {
- this.currentStepIndex = Math.min(
+ nextStep: function() {
+ this.currentStepIndex = Math.min(
this.currentStepIndex + 1,
this.stepOrder.length - 1
);
- this.render();
- },
+ this.render();
+ },
- goToStep: function( stepName ) {
- var stepIndex = _.indexOf(this.stepOrder, stepName);
+ goToStep: function(stepName) {
+ var stepIndex = _.indexOf(this.stepOrder, stepName);
- if ( stepIndex >= 0 ) {
- this.currentStepIndex = stepIndex;
- }
+ if (stepIndex >= 0) {
+ this.currentStepIndex = stepIndex;
+ }
- this.render();
- }
- });
-
-})(jQuery, _, Backbone, gettext);
+ this.render();
+ }
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/review_photos_step_view.js b/lms/static/js/verify_student/views/review_photos_step_view.js
index a83ed906ee..61cb014a74 100644
--- a/lms/static/js/verify_student/views/review_photos_step_view.js
+++ b/lms/static/js/verify_student/views/review_photos_step_view.js
@@ -3,105 +3,104 @@
*/
var edx = edx || {};
-(function( $, gettext ) {
+(function($, gettext) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.ReviewPhotosStepView = edx.verify_student.StepView.extend({
- templateName: "review_photos_step",
+ templateName: 'review_photos_step',
defaultContext: function() {
return {
platformName: '',
- fullName: '',
+ fullName: ''
};
},
postRender: function() {
// Load the photos from the previous steps
- $( '#face_image' )[0].src = this.model.get('faceImage');
- $( '#photo_id_image' )[0].src = this.model.get('identificationImage');
+ $('#face_image')[0].src = this.model.get('faceImage');
+ $('#photo_id_image')[0].src = this.model.get('identificationImage');
// Prep the name change dropdown
- $( '.expandable-area' ).slideUp();
- $( '.is-expandable' ).addClass('is-ready');
- $( '.is-expandable .title-expand' ).on( 'click', this.expandCallback );
+ $('.expandable-area').slideUp();
+ $('.is-expandable').addClass('is-ready');
+ $('.is-expandable .title-expand').on('click', this.expandCallback);
// Go back to the first photo step if we need to retake photos
- $( '#retake_photos_button' ).on( 'click', _.bind( this.retakePhotos, this ) );
+ $('#retake_photos_button').on('click', _.bind(this.retakePhotos, this));
// When moving to the next step, submit photos for verification
- $( '#next_step_button' ).on( 'click', _.bind( this.submitPhotos, this ) );
+ $('#next_step_button').on('click', _.bind(this.submitPhotos, this));
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
},
retakePhotos: function() {
// Track the user's intent to retake their photos
- window.analytics.track( 'edx.bi.user.images.retaken', {
+ window.analytics.track('edx.bi.user.images.retaken', {
category: 'verification'
});
- this.goToStep( 'face-photo-step' );
+ this.goToStep('face-photo-step');
},
submitPhotos: function() {
- var fullName = $( '#new-name' ).val();
+ var fullName = $('#new-name').val();
// Disable the submit button to prevent duplicate submissions
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// On success, move on to the next step
- this.listenToOnce( this.model, 'sync', _.bind( this.nextStep, this ) );
+ this.listenToOnce(this.model, 'sync', _.bind(this.nextStep, this));
// On failure, re-enable the submit button and display the error
- this.listenToOnce( this.model, 'error', _.bind( this.handleSubmissionError, this ) );
+ this.listenToOnce(this.model, 'error', _.bind(this.handleSubmissionError, this));
// Submit
- if ( fullName ) {
- this.model.set( 'fullName', fullName );
+ if (fullName) {
+ this.model.set('fullName', fullName);
}
this.model.save();
},
- handleSubmissionError: function( xhr ) {
- var errorMsg = gettext( 'An error has occurred. Please try again later.' );
+ handleSubmissionError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again later.');
// Re-enable the submit button to allow the user to retry
- this.setSubmitButtonEnabled( true );
+ this.setSubmitButtonEnabled(true);
- if ( xhr.status === 400 ) {
+ if (xhr.status === 400) {
errorMsg = xhr.responseText;
}
this.errorModel.set({
- errorTitle: gettext( 'Could not submit photos' ),
+ errorTitle: gettext('Could not submit photos'),
errorMsg: errorMsg,
shown: true
});
},
- expandCallback: function( event ) {
+ expandCallback: function(event) {
var $link = $(this),
$title = $link.closest('.help-tip'),
expanded = $title.hasClass('is-expanded');
event.preventDefault();
- $link.attr( 'aria-expanded', !expanded );
+ $link.attr('aria-expanded', !expanded);
$title.toggleClass('is-expanded')
.find('.expandable-area').slideToggle();
},
- setSubmitButtonEnabled: function( isEnabled ) {
- $( '#next_step_button' )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ $('#next_step_button')
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
}
});
-
-})( jQuery, gettext );
+})(jQuery, gettext);
diff --git a/lms/static/js/verify_student/views/step_view.js b/lms/static/js/verify_student/views/step_view.js
index fd5e941cb5..42ede52631 100644
--- a/lms/static/js/verify_student/views/step_view.js
+++ b/lms/static/js/verify_student/views/step_view.js
@@ -1,4 +1,4 @@
-/*global jQuery, _, Backbone, gettext */
+/* global jQuery, _, Backbone, gettext */
/**
* Base view for defining steps in the payment/verification flow.
@@ -10,55 +10,55 @@
*/
var edx = edx || {};
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.StepView = Backbone.View.extend({
+ edx.verify_student.StepView = Backbone.View.extend({
- initialize: function( obj ) {
- _.extend( this, obj );
+ initialize: function(obj) {
+ _.extend(this, obj);
/* Mix non-conflicting functions from underscore.string
* (all but include, contains, and reverse) into the
* Underscore namespace.
*/
- _.mixin(_.str.exports());
- },
+ _.mixin(_.str.exports());
+ },
- render: function() {
- var templateHtml = $( "#" + this.templateName + "-tpl" ).html();
+ render: function() {
+ var templateHtml = $('#' + this.templateName + '-tpl').html();
// Allow subclasses to add additional information
// to the template context, perhaps asynchronously.
- this.updateContext( this.templateContext() ).done(
- function( templateContext ) {
+ this.updateContext(this.templateContext()).done(
+ function(templateContext) {
// Render the template into the DOM
- edx.HtmlUtils.setHtml( $(this.el), edx.HtmlUtils.template(templateHtml)( templateContext ) );
+ edx.HtmlUtils.setHtml($(this.el), edx.HtmlUtils.template(templateHtml)(templateContext));
// Allow subclasses to install custom event handlers
this.postRender();
}
- ).fail( _.bind( this.handleError, this ) );
+ ).fail(_.bind(this.handleError, this));
- return this;
- },
+ return this;
+ },
- handleError: function( errorTitle, errorMsg ) {
- this.errorModel.set({
- errorTitle: errorTitle || gettext( "Error" ),
- errorMsg: errorMsg || gettext( "An error has occurred. Please try reloading the page." ),
- shown: true
- });
- },
+ handleError: function(errorTitle, errorMsg) {
+ this.errorModel.set({
+ errorTitle: errorTitle || gettext('Error'),
+ errorMsg: errorMsg || gettext('An error has occurred. Please try reloading the page.'),
+ shown: true
+ });
+ },
- templateContext: function() {
- var context = {
- nextStepTitle: this.nextStepTitle
- };
- return _.extend( context, this.defaultContext(), this.stepData );
- },
+ templateContext: function() {
+ var context = {
+ nextStepTitle: this.nextStepTitle
+ };
+ return _.extend(context, this.defaultContext(), this.stepData);
+ },
/**
* Provide default values for the template context.
@@ -68,9 +68,9 @@
* tests can pass in only the values relevant
* to the test.
*/
- defaultContext: function() {
- return {};
- },
+ defaultContext: function() {
+ return {};
+ },
/**
* Subclasses can override this to add information to
@@ -79,28 +79,27 @@
* after completing an AJAX request.
* The default implementation is a no-op.
*/
- updateContext: function( templateContext ) {
- var view = this;
- return $.Deferred(
- function( defer ) {
- defer.resolveWith( view, [ templateContext ]);
+ updateContext: function(templateContext) {
+ var view = this;
+ return $.Deferred(
+ function(defer) {
+ defer.resolveWith(view, [templateContext]);
}
).promise();
- },
+ },
- postRender: function() {
+ postRender: function() {
// Sub-classes can override this method
// to install custom event handlers.
- },
+ },
- nextStep: function() {
- this.trigger('next-step');
- },
+ nextStep: function() {
+ this.trigger('next-step');
+ },
- goToStep: function( stepName ) {
- this.trigger( 'go-to-step', stepName );
- }
+ goToStep: function(stepName) {
+ this.trigger('go-to-step', stepName);
+ }
- });
-
- })( jQuery, _, Backbone, gettext );
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/webcam_photo_view.js b/lms/static/js/verify_student/views/webcam_photo_view.js
index 707bc0f797..b132f1b255 100644
--- a/lms/static/js/verify_student/views/webcam_photo_view.js
+++ b/lms/static/js/verify_student/views/webcam_photo_view.js
@@ -3,156 +3,156 @@
* Supports HTML5 and Flash.
*/
var edx = edx || {},
- key = {
- enter: 13
- };
+ key = {
+ enter: 13
+ };
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.WebcamPhotoView = Backbone.View.extend({
+ edx.verify_student.WebcamPhotoView = Backbone.View.extend({
- template: "#webcam_photo-tpl",
- el: "#webcam",
+ template: '#webcam_photo-tpl',
+ el: '#webcam',
- backends: {
- "html5": {
- name: "html5",
+ backends: {
+ 'html5': {
+ name: 'html5',
- initialize: function( obj ) {
- this.URL = (window.URL || window.webkitURL);
- this.video = obj.video || "";
- this.canvas = obj.canvas || "";
- this.stream = null;
+ initialize: function(obj) {
+ this.URL = (window.URL || window.webkitURL);
+ this.video = obj.video || '';
+ this.canvas = obj.canvas || '';
+ this.stream = null;
// Start the capture
- var getUserMedia = this.getUserMediaFunc();
- if ( getUserMedia ) {
- getUserMedia(
- {
- video: true,
+ var getUserMedia = this.getUserMediaFunc();
+ if (getUserMedia) {
+ getUserMedia(
+ {
+ video: true,
// Specify the `fake` constraint if we detect we are running in a test
// environment. In Chrome, this will do nothing, but in Firefox, it will
// instruct the browser to use a fake video device.
- fake: window.location.hostname === 'localhost'
- },
- _.bind( this.getUserMediaCallback, this ),
- _.bind( this.handleVideoFailure, this )
+ fake: window.location.hostname === 'localhost'
+ },
+ _.bind(this.getUserMediaCallback, this),
+ _.bind(this.handleVideoFailure, this)
);
- }
- },
+ }
+ },
- isSupported: function() {
- return this.getUserMediaFunc() !== undefined;
- },
+ isSupported: function() {
+ return this.getUserMediaFunc() !== undefined;
+ },
- snapshot: function() {
- var video;
+ snapshot: function() {
+ var video;
- if ( this.stream ) {
- video = this.getVideo();
- this.getCanvas().getContext('2d').drawImage( video, 0, 0 );
- video.pause();
- return true;
- }
+ if (this.stream) {
+ video = this.getVideo();
+ this.getCanvas().getContext('2d').drawImage(video, 0, 0);
+ video.pause();
+ return true;
+ }
- return false;
- },
+ return false;
+ },
- getImageData: function() {
- return this.getCanvas().toDataURL( 'image/png' );
- },
+ getImageData: function() {
+ return this.getCanvas().toDataURL('image/png');
+ },
- reset: function() {
- this.getVideo().play();
- },
+ reset: function() {
+ this.getVideo().play();
+ },
- getUserMediaFunc: function() {
- var userMedia = (
+ getUserMediaFunc: function() {
+ var userMedia = (
navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia
);
- if ( userMedia ) {
- return _.bind( userMedia, navigator );
- }
- },
+ if (userMedia) {
+ return _.bind(userMedia, navigator);
+ }
+ },
- getUserMediaCallback: function( stream ) {
- var video = this.getVideo();
- this.stream = stream;
- video.src = this.URL.createObjectURL( stream );
- video.play();
- this.trigger('webcam-loaded');
- },
+ getUserMediaCallback: function(stream) {
+ var video = this.getVideo();
+ this.stream = stream;
+ video.src = this.URL.createObjectURL(stream);
+ video.play();
+ this.trigger('webcam-loaded');
+ },
- getVideo: function() {
- return $( this.video ).first()[0];
- },
+ getVideo: function() {
+ return $(this.video).first()[0];
+ },
- getCanvas: function() {
- return $( this.canvas ).first()[0];
- },
+ getCanvas: function() {
+ return $(this.canvas).first()[0];
+ },
- handleVideoFailure: function() {
- this.trigger(
+ handleVideoFailure: function() {
+ this.trigger(
'error',
- gettext( 'Video Capture Error' ),
- gettext( 'Please verify that your webcam is connected and that you have allowed your browser to access it.' )
+ gettext('Video Capture Error'),
+ gettext('Please verify that your webcam is connected and that you have allowed your browser to access it.')
);
- }
- },
+ }
+ },
- "flash": {
+ 'flash': {
- name: "flash",
+ name: 'flash',
- initialize: function( obj ) {
- this.wrapper = obj.wrapper || "";
- this.imageData = "";
+ initialize: function(obj) {
+ this.wrapper = obj.wrapper || '';
+ this.imageData = '';
// Wait for the player to load, then verify camera support
// Trigger an error if no camera is available.
- this.checkCameraSupported();
- },
+ this.checkCameraSupported();
+ },
- isSupported: function() {
- try {
- var flashObj = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
- if ( flashObj ) {
- return true;
- }
- } catch(ex) {
- if ( navigator.mimeTypes["application/x-shockwave-flash"] !== undefined ) {
- return true;
- }
- }
+ isSupported: function() {
+ try {
+ var flashObj = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
+ if (flashObj) {
+ return true;
+ }
+ } catch (ex) {
+ if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) {
+ return true;
+ }
+ }
- return false;
- },
+ return false;
+ },
- snapshot: function() {
- var flashObj = this.getFlashObject();
- if ( flashObj.cameraAuthorized() ) {
- this.imageData = flashObj.snap();
- return true;
- }
- return false;
- },
+ snapshot: function() {
+ var flashObj = this.getFlashObject();
+ if (flashObj.cameraAuthorized()) {
+ this.imageData = flashObj.snap();
+ return true;
+ }
+ return false;
+ },
- reset: function() {
- this.getFlashObject().reset();
- },
+ reset: function() {
+ this.getFlashObject().reset();
+ },
- getImageData: function() {
- return this.imageData;
- },
+ getImageData: function() {
+ return this.imageData;
+ },
- flashObjectTag: function() {
- return (
+ flashObjectTag: function() {
+ return (
'' +
' '
);
- },
+ },
- getFlashObject: function() {
- return $( "#flash_video" )[0];
- },
+ getFlashObject: function() {
+ return $('#flash_video')[0];
+ },
- checkCameraSupported: function() {
- var flashObj = this.getFlashObject(),
- isLoaded = false,
- hasCamera = false;
+ checkCameraSupported: function() {
+ var flashObj = this.getFlashObject(),
+ isLoaded = false,
+ hasCamera = false;
- isLoaded = (
+ isLoaded = (
flashObj &&
- flashObj.hasOwnProperty( 'percentLoaded' ) &&
+ flashObj.hasOwnProperty('percentLoaded') &&
flashObj.percentLoaded() === 100
);
// On some browsers, the flash object will say it has a camera
// even "percentLoaded" isn't defined.
- hasCamera = (
+ hasCamera = (
flashObj &&
- flashObj.hasOwnProperty( 'hasCamera' ) &&
+ flashObj.hasOwnProperty('hasCamera') &&
flashObj.hasCamera()
);
// If we've fully loaded, and no camera is available,
// then show an error.
- if ( isLoaded && !hasCamera ) {
- this.trigger(
+ if (isLoaded && !hasCamera) {
+ this.trigger(
'error',
- gettext( "No Webcam Detected" ),
- gettext( "You don't seem to have a webcam connected." ) + " " +
- gettext( "Double-check that your webcam is connected and working to continue.")
+ gettext('No Webcam Detected'),
+ gettext("You don't seem to have a webcam connected.") + ' ' +
+ gettext('Double-check that your webcam is connected and working to continue.')
);
- }
+ }
// If we're still waiting for the player to load, check
// back later.
- else if ( !isLoaded && !hasCamera ) {
- setTimeout( _.bind( this.checkCameraSupported, this ), 50 );
- }
+ else if (!isLoaded && !hasCamera) {
+ setTimeout(_.bind(this.checkCameraSupported, this), 50);
+ }
// Otherwise, the flash player says it has a camera,
// so we don't need to keep checking.
- }
- }
- },
+ }
+ }
+ },
- initialize: function( obj ) {
- this.submitButton = obj.submitButton || "";
- this.modelAttribute = obj.modelAttribute || "";
- this.errorModel = obj.errorModel || null;
- this.backend = this.backends[obj.backendName] || obj.backend;
- this.captureSoundPath = obj.captureSoundPath || "";
+ initialize: function(obj) {
+ this.submitButton = obj.submitButton || '';
+ this.modelAttribute = obj.modelAttribute || '';
+ this.errorModel = obj.errorModel || null;
+ this.backend = this.backends[obj.backendName] || obj.backend;
+ this.captureSoundPath = obj.captureSoundPath || '';
- _.extend( this.backend, Backbone.Events );
- this.backend.initialize({
- wrapper: "#camera",
- video: '#photo_id_video',
- canvas: '#photo_id_canvas'
- });
+ _.extend(this.backend, Backbone.Events);
+ this.backend.initialize({
+ wrapper: '#camera',
+ video: '#photo_id_video',
+ canvas: '#photo_id_canvas'
+ });
- this.listenTo( this.backend, 'error', this.handleError );
- this.listenTo( this.backend, 'webcam-loaded', this.handleWebcamLoaded );
- },
+ this.listenTo(this.backend, 'error', this.handleError);
+ this.listenTo(this.backend, 'webcam-loaded', this.handleWebcamLoaded);
+ },
- isSupported: function() {
- return this.backend.isSupported();
- },
+ isSupported: function() {
+ return this.backend.isSupported();
+ },
- render: function() {
- var renderedHtml,
- $resetBtn,
- $captureBtn;
+ render: function() {
+ var renderedHtml,
+ $resetBtn,
+ $captureBtn;
// Set the submit button to disabled by default
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// Load the template for the webcam into the DOM
- renderedHtml = _.template($( this.template ).html())(
- { backendName: this.backend.name }
+ renderedHtml = _.template($(this.template).html())(
+ {backendName: this.backend.name}
);
- $( this.el ).html( renderedHtml );
+ $(this.el).html(renderedHtml);
- $resetBtn = this.$el.find('#webcam_reset_button');
- $captureBtn = this.$el.find('#webcam_capture_button');
+ $resetBtn = this.$el.find('#webcam_reset_button');
+ $captureBtn = this.$el.find('#webcam_capture_button');
// Install event handlers
- $resetBtn.on( 'click', _.bind( this.reset, this ) );
- $captureBtn.on( 'click', _.bind( this.capture, this ) );
+ $resetBtn.on('click', _.bind(this.reset, this));
+ $captureBtn.on('click', _.bind(this.capture, this));
- $resetBtn.on( 'keyup', _.bind( this.resetByEnter, this ) );
+ $resetBtn.on('keyup', _.bind(this.resetByEnter, this));
// Show the capture button
- $captureBtn.removeClass('is-hidden');
- $( "#webcam_capture_button", this.el ).removeClass('is-hidden');
- $( "#webcam_capture_sound", this.el ).attr('src', this.captureSoundPath);
+ $captureBtn.removeClass('is-hidden');
+ $('#webcam_capture_button', this.el).removeClass('is-hidden');
+ $('#webcam_capture_sound', this.el).attr('src', this.captureSoundPath);
- return this;
- },
+ return this;
+ },
- reset: function() {
+ reset: function() {
// Disable the submit button
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// Reset the video capture
- this.backend.reset();
+ this.backend.reset();
// Reset data on the model
- this.model.set( this.modelAttribute, "" );
+ this.model.set(this.modelAttribute, '');
// Go back to the initial button state
- $( "#webcam_reset_button", this.el ).addClass('is-hidden');
- $( "#webcam_capture_button", this.el ).removeClass('is-hidden');
- $( this.submitButton ).attr('title', '');
- },
+ $('#webcam_reset_button', this.el).addClass('is-hidden');
+ $('#webcam_capture_button', this.el).removeClass('is-hidden');
+ $(this.submitButton).attr('title', '');
+ },
- resetByEnter: function(event){
- if(event.keyCode == key.enter){
- this.reset();
- }
- },
- capture: function() {
+ resetByEnter: function(event) {
+ if (event.keyCode == key.enter) {
+ this.reset();
+ }
+ },
+ capture: function() {
// Take a snapshot of the video
- var success = this.backend.snapshot();
+ var success = this.backend.snapshot();
- if ( success ) {
+ if (success) {
// Trigger an event which parent views can use to fire a
// business intelligence event
- this.trigger( 'imageCaptured' );
+ this.trigger('imageCaptured');
// Hide the capture button, and show the reset button
- $( "#webcam_capture_button", this.el ).addClass('is-hidden');
- $( "#webcam_reset_button", this.el ).removeClass('is-hidden');
+ $('#webcam_capture_button', this.el).addClass('is-hidden');
+ $('#webcam_reset_button', this.el).removeClass('is-hidden');
// Save the data to the model
- this.model.set( this.modelAttribute, this.backend.getImageData() );
+ this.model.set(this.modelAttribute, this.backend.getImageData());
// Enable the submit button
- this.setSubmitButtonEnabled( true );
- this.setSubmitButtonFocused();
- this.captureSound();
- }
- },
+ this.setSubmitButtonEnabled(true);
+ this.setSubmitButtonFocused();
+ this.captureSound();
+ }
+ },
- handleWebcamLoaded: function( errorTitle, errorMsg ) {
+ handleWebcamLoaded: function(errorTitle, errorMsg) {
// Hide the text behind camera
- $( "#camera .placeholder-art", this.el ).hide();
- },
+ $('#camera .placeholder-art', this.el).hide();
+ },
- handleError: function( errorTitle, errorMsg ) {
+ handleError: function(errorTitle, errorMsg) {
// Hide the buttons
- $( "#webcam_capture_button", this.el ).addClass('is-hidden');
- $( "#webcam_reset_button", this.el ).addClass('is-hidden');
+ $('#webcam_capture_button', this.el).addClass('is-hidden');
+ $('#webcam_reset_button', this.el).addClass('is-hidden');
// Show the error message
- if ( this.errorModel ) {
- this.errorModel.set({
- errorTitle: errorTitle,
- errorMsg: errorMsg,
- shown: true
- });
- }
- },
+ if (this.errorModel) {
+ this.errorModel.set({
+ errorTitle: errorTitle,
+ errorMsg: errorMsg,
+ shown: true
+ });
+ }
+ },
- setSubmitButtonEnabled: function( isEnabled ) {
- $( this.submitButton )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ $(this.submitButton)
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- },
+ },
- captureSound: function(){
- $( '#webcam_capture_sound' )[0].play();
- },
+ captureSound: function() {
+ $('#webcam_capture_sound')[0].play();
+ },
- setSubmitButtonFocused: function(){
- $( this.submitButton )
+ setSubmitButtonFocused: function() {
+ $(this.submitButton)
.trigger('focus')
- .attr('title', gettext( 'Photo Captured successfully.'));
- },
+ .attr('title', gettext('Photo Captured successfully.'));
+ },
- isMobileDevice: function() {
+ isMobileDevice: function() {
// Check whether user is using mobile device or not
- return ( navigator.userAgent.match(/(Android|iPad|iPhone|iPod)/g) ? true : false );
- }
- });
+ return (navigator.userAgent.match(/(Android|iPad|iPhone|iPod)/g) ? true : false);
+ }
+ });
/**
* Retrieve a supported webcam view implementation.
@@ -363,37 +363,36 @@
* @param {Object} obj Parameters to the webcam view.
* @return {Object} A Backbone view.
*/
- edx.verify_student.getSupportedWebcamView = function( obj ) {
- var view = null;
+ edx.verify_student.getSupportedWebcamView = function(obj) {
+ var view = null;
// First choice is HTML5, supported by most web browsers
- obj.backendName = "html5";
- view = new edx.verify_student.WebcamPhotoView( obj );
- if ( view.isSupported() ) {
- return view;
- }
+ obj.backendName = 'html5';
+ view = new edx.verify_student.WebcamPhotoView(obj);
+ if (view.isSupported()) {
+ return view;
+ }
// Second choice is Flash, required for older versions of IE
- obj.backendName = "flash";
- view = new edx.verify_student.WebcamPhotoView( obj );
- if ( view.isSupported() ) {
- return view;
- }
+ obj.backendName = 'flash';
+ view = new edx.verify_student.WebcamPhotoView(obj);
+ if (view.isSupported()) {
+ return view;
+ }
// If user is not using mobile device and Flash is not available
// then show user error message for Flash
- if (!view.isMobileDevice() && !view.isSupported()) {
- view.backend.trigger(
+ if (!view.isMobileDevice() && !view.isSupported()) {
+ view.backend.trigger(
'error',
- gettext( "No Flash Detected" ),
- gettext( "You don't seem to have Flash installed. Get Flash to continue your verification." )
+ gettext('No Flash Detected'),
+ gettext("You don't seem to have Flash installed. Get Flash to continue your verification.")
);
- return view;
- }
+ return view;
+ }
// Last resort is HTML file input with image capture.
// This will work everywhere, and on iOS it will
// allow users to take a photo with the camera.
- return new edx.verify_student.ImageInputView( obj );
- };
-
- })( jQuery, _, Backbone, gettext );
+ return new edx.verify_student.ImageInputView(obj);
+ };
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/views/fields.js b/lms/static/js/views/fields.js
index 762f342234..c67f185711 100644
--- a/lms/static/js/views/fields.js
+++ b/lms/static/js/views/fields.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone',
@@ -9,14 +9,13 @@
'text!templates/fields/field_text.underscore',
'text!templates/fields/field_textarea.underscore',
'backbone-super'
- ], function (gettext, $, _, Backbone, HtmlUtils,
+ ], function(gettext, $, _, Backbone, HtmlUtils,
field_readonly_template,
field_dropdown_template,
field_link_template,
field_text_template,
field_textarea_template
) {
-
var messageRevertDelay = 6000;
var FieldViews = {};
@@ -24,7 +23,7 @@
fieldType: 'generic',
- className: function () {
+ className: function() {
return 'u-field' + ' u-field-' + this.fieldType + ' u-field-' + this.options.valueAttribute;
},
@@ -33,34 +32,34 @@
indicators: {
'canEdit': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Editable"),
+ gettext('Editable'),
HtmlUtils.HTML(' ')
),
'error': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Error"),
+ gettext('Error'),
HtmlUtils.HTML(' ')
),
'validationError': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Validation Error"),
+ gettext('Validation Error'),
HtmlUtils.HTML(' ')
),
'inProgress': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("In Progress"),
+ gettext('In Progress'),
HtmlUtils.HTML(' ')
),
'success': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Success"),
+ gettext('Success'),
HtmlUtils.HTML(' ')
),
'plus': HtmlUtils.joinHtml(
HtmlUtils.HTML(''),
- gettext("Placeholder"),
+ gettext('Placeholder'),
HtmlUtils.HTML(' ')
- ),
+ )
},
messages: {
@@ -76,20 +75,19 @@
Backbone.View.apply(this, arguments);
},
- initialize: function () {
-
+ initialize: function() {
this.template = _.template(this.fieldTemplate || '');
this.helpMessage = this.options.helpMessage || '';
this.showMessages = _.isUndefined(this.options.showMessages) ? true : this.options.showMessages;
- _.bindAll(this, 'modelValue', 'modelValueIsSet', 'showNotificationMessage','getNotificationMessage',
+ _.bindAll(this, 'modelValue', 'modelValueIsSet', 'showNotificationMessage', 'getNotificationMessage',
'getMessage', 'title', 'showHelpMessage', 'showInProgressMessage', 'showSuccessMessage',
'showErrorMessage'
);
},
- modelValue: function () {
+ modelValue: function() {
return this.model.get(this.options.valueAttribute);
},
@@ -97,7 +95,7 @@
return (this.modelValue() === true);
},
- title: function (title) {
+ title: function(title) {
return HtmlUtils.setHtml(this.$('.u-field-title'), title);
},
@@ -110,7 +108,7 @@
return this.indicators[message_status];
},
- showHelpMessage: function (message) {
+ showHelpMessage: function(message) {
if (_.isUndefined(message) || _.isNull(message)) {
message = this.helpMessage;
}
@@ -135,11 +133,11 @@
}
},
- showInProgressMessage: function () {
+ showInProgressMessage: function() {
this.showNotificationMessage(this.getMessage('inProgress'));
},
- showSuccessMessage: function () {
+ showSuccessMessage: function() {
var successMessage = this.getMessage('success');
this.showNotificationMessage(successMessage);
@@ -152,7 +150,7 @@
var context = Date.now();
this.lastSuccessMessageContext = context;
- setTimeout(function () {
+ setTimeout(function() {
if ((context === view.lastSuccessMessageContext) &&
(view.getNotificationMessage().toString() === successMessage.toString())) {
if (view.editable === 'toggle') {
@@ -164,7 +162,7 @@
}, messageRevertDelay);
},
- showErrorMessage: function (xhr) {
+ showErrorMessage: function(xhr) {
if (xhr.status === 400) {
try {
var errors = JSON.parse(xhr.responseText),
@@ -182,14 +180,14 @@
FieldViews.EditableFieldView = FieldViews.FieldView.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.persistChanges = _.isUndefined(options.persistChanges) ? false : options.persistChanges;
_.bindAll(this, 'saveAttributes', 'saveSucceeded', 'showDisplayMode', 'showEditMode',
'startEditing', 'finishEditing'
);
this._super(options);
- this.editable = _.isUndefined(this.options.editable) ? 'always': this.options.editable;
+ this.editable = _.isUndefined(this.options.editable) ? 'always' : this.options.editable;
this.$el.addClass('editable-' + this.editable);
if (this.editable === 'always') {
@@ -199,17 +197,17 @@
}
},
- saveAttributes: function (attributes, options) {
+ saveAttributes: function(attributes, options) {
if (this.persistChanges === true) {
var view = this;
var defaultOptions = {
contentType: 'application/merge-patch+json',
patch: true,
wait: true,
- success: function () {
+ success: function() {
view.saveSucceeded();
},
- error: function (model, xhr) {
+ error: function(model, xhr) {
view.showErrorMessage(xhr);
}
};
@@ -218,7 +216,7 @@
}
},
- saveSucceeded: function () {
+ saveSucceeded: function() {
this.showSuccessMessage();
},
@@ -247,7 +245,7 @@
this.$el.addClass('mode-edit');
},
- startEditing: function () {
+ startEditing: function() {
if (this.editable === 'toggle' && this.mode !== 'edit') {
this.showEditMode(true);
}
@@ -255,7 +253,7 @@
finishEditing: function() {
var modelValue;
- if (this.persistChanges === false || this.mode !== 'edit') {return;}
+ if (this.persistChanges === false || this.mode !== 'edit') { return; }
modelValue = this.modelValue();
if (!(_.isUndefined(modelValue) || _.isNull(modelValue))) {
@@ -273,11 +271,11 @@
}
},
- highlightFieldOnError: function () {
+ highlightFieldOnError: function() {
this.$el.addClass('error');
},
- unhighlightField: function () {
+ unhighlightField: function() {
this.$el.removeClass('error');
}
});
@@ -288,13 +286,13 @@
fieldTemplate: field_readonly_template,
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'fieldValue', 'updateValueInField');
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -306,11 +304,11 @@
return this;
},
- fieldValue: function () {
+ fieldValue: function() {
return this.$('.u-field-value').text();
},
- updateValueInField: function () {
+ updateValueInField: function() {
this.$('.u-field-value ').text(this.modelValue());
}
});
@@ -325,13 +323,13 @@
'change input': 'saveValue'
},
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'fieldValue', 'updateValueInField', 'saveValue');
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -342,16 +340,16 @@
return this;
},
- fieldValue: function () {
+ fieldValue: function() {
return this.$('.u-field-value input').val();
},
- updateValueInField: function () {
+ updateValueInField: function() {
var value = (_.isUndefined(this.modelValue()) || _.isNull(this.modelValue())) ? '' : this.modelValue();
this.$('.u-field-value input').val(value);
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
@@ -370,14 +368,15 @@
'focusout select': 'finishEditing'
},
- initialize: function (options) {
- _.bindAll(this, 'render', 'optionForValue', 'fieldValue', 'displayValue', 'updateValueInField', 'saveValue');
+ initialize: function(options) {
+ _.bindAll(this, 'render', 'optionForValue', 'fieldValue', 'displayValue', 'updateValueInField',
+ 'saveValue', 'createGroupOptions');
this._super(options);
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
mode: this.mode,
@@ -387,7 +386,7 @@
titleVisible: this.options.titleVisible !== undefined ? this.options.titleVisible : true,
iconName: this.options.iconName,
showBlankOption: (!this.options.required || !this.modelValueIsSet()),
- selectOptions: this.options.options,
+ groupOptions: this.createGroupOptions(),
message: this.helpMessage
}));
this.delegateEvents();
@@ -409,13 +408,23 @@
},
optionForValue: function(value) {
- return _.find(this.options.options, function(option) { return option[0] === value; });
+ var options = [];
+ if (_.isUndefined(this.options.groupOptions)) {
+ return _.find(this.options.options, function(option) { return option[0] === value; });
+ } else {
+ _.each(this.options.groupOptions, function(groupOption) {
+ options = options.concat(groupOption.selectOptions);
+ });
+ return _.find(options, function(option) {
+ return option[0] === value;
+ });
+ }
},
- fieldValue: function () {
+ fieldValue: function() {
var value;
if (this.editable === 'never') {
- value = this.modelValueIsSet() ? this.modelValue () : null;
+ value = this.modelValueIsSet() ? this.modelValue() : null;
}
else {
value = this.$('.u-field-value select').val();
@@ -423,7 +432,7 @@
return value === '' ? null : value;
},
- displayValue: function (value) {
+ displayValue: function(value) {
if (value) {
var option = this.optionForValue(value);
return (option ? option[1] : '');
@@ -432,7 +441,7 @@
}
},
- updateValueInField: function () {
+ updateValueInField: function() {
if (this.editable !== 'never') {
this.$('.u-field-value select').val(this.modelValue() || '');
}
@@ -449,7 +458,7 @@
}
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
@@ -485,6 +494,14 @@
if (this.editable !== 'never') {
this.$('.u-field-value select').prop('disabled', disable);
}
+ },
+
+ createGroupOptions: function() {
+ return !(_.isUndefined(this.options.groupOptions)) ? this.options.groupOptions :
+ [{
+ groupTitle: null,
+ selectOptions: this.options.options
+ }];
}
});
@@ -505,13 +522,13 @@
'cut textarea': 'adjustTextareaHeight'
},
- initialize: function (options) {
+ initialize: function(options) {
_.bindAll(this, 'render', 'onKeyDown', 'adjustTextareaHeight', 'fieldValue', 'saveValue', 'updateView');
this._super(options);
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateView);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateView);
},
- render: function () {
+ render: function() {
var value = this.modelValue();
if (this.mode === 'display') {
value = value || this.options.placeholderValue;
@@ -536,7 +553,7 @@
return this;
},
- onKeyDown: function (event) {
+ onKeyDown: function(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.finishEditing(event);
@@ -546,7 +563,7 @@
},
adjustTextareaHeight: function() {
- if (this.persistChanges === false) {return;}
+ if (this.persistChanges === false) { return; }
var textarea = this.$('textarea');
textarea.css('height', 'auto').css('height', textarea.prop('scrollHeight') + 10);
},
@@ -556,7 +573,7 @@
return value ? $.trim(value) : '';
},
- fieldValue: function () {
+ fieldValue: function() {
if (this.mode === 'edit') {
return this.$('.u-field-value textarea').val();
}
@@ -565,13 +582,13 @@
}
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
},
- updateView: function () {
+ updateView: function() {
if (this.mode !== 'edit') {
this.showDisplayMode(true);
}
@@ -606,12 +623,12 @@
'click a': 'linkClicked'
},
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'linkClicked');
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -624,7 +641,7 @@
return this;
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
}
});
diff --git a/lms/static/js/views/file_uploader.js b/lms/static/js/views/file_uploader.js
index 9dc064dd61..0f7c94280a 100644
--- a/lms/static/js/views/file_uploader.js
+++ b/lms/static/js/views/file_uploader.js
@@ -22,16 +22,16 @@
* @param errorNotification, optional callback that can return a success NotificationModel for display
* after a file failed to upload. This method will be passed the attempted file, event, and data.
*/
-(function (Backbone, $, _, gettext, interpolate_text, NotificationModel, NotificationView) {
+(function(Backbone, $, _, gettext, interpolate_text, NotificationModel, NotificationView) {
// Requires JQuery-File-Upload.
var FileUploaderView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.template = _.template($('#file-upload-tpl').text());
this.options = options;
},
- render: function () {
+ render: function() {
var options = this.options,
get_option_with_default = function(option, default_value) {
var optionVal = options[option];
@@ -40,12 +40,12 @@
submitButton, resultNotification;
this.$el.html(this.template({
- title: get_option_with_default("title", ""),
- inputLabel: get_option_with_default("inputLabel", ""),
- inputTip: get_option_with_default("inputTip", ""),
- extensions: get_option_with_default("extensions", ""),
- submitButtonText: get_option_with_default("submitButtonText", gettext("Upload File")),
- url: get_option_with_default("url", "")
+ title: get_option_with_default('title', ''),
+ inputLabel: get_option_with_default('inputLabel', ''),
+ inputTip: get_option_with_default('inputTip', ''),
+ extensions: get_option_with_default('extensions', ''),
+ submitButtonText: get_option_with_default('submitButtonText', gettext('Upload File')),
+ url: get_option_with_default('url', '')
}));
submitButton = this.$el.find('.submit-file-button');
@@ -58,22 +58,22 @@
fail: this.errorHandler.bind(this),
autoUpload: false,
replaceFileInput: false,
- add: function (e, data) {
+ add: function(e, data) {
var file = data.files[0];
- submitButton.removeClass("is-disabled").attr('aria-disabled', false);
+ submitButton.removeClass('is-disabled').attr('aria-disabled', false);
submitButton.unbind('click');
- submitButton.click(function (event) {
+ submitButton.click(function(event) {
event.preventDefault();
data.submit();
});
- resultNotification.html("");
+ resultNotification.html('');
}
});
return this;
},
- successHandler: function (event, data) {
+ successHandler: function(event, data) {
var file = data.files[0].name;
var notificationModel;
if (this.options.successNotification) {
@@ -81,7 +81,7 @@
}
else {
notificationModel = new NotificationModel({
- type: "confirmation",
+ type: 'confirmation',
title: interpolate_text(gettext("Your upload of '{file}' succeeded."), {file: file})
});
}
@@ -92,7 +92,7 @@
notification.render();
},
- errorHandler: function (event, data) {
+ errorHandler: function(event, data) {
var file = data.files[0].name, message = null, jqXHR = data.response().jqXHR;
var notificationModel;
if (this.options.errorNotification) {
@@ -110,7 +110,7 @@
message = interpolate_text(gettext("Your upload of '{file}' failed."), {file: file});
}
notificationModel = new NotificationModel({
- type: "error",
+ type: 'error',
title: message
});
}
diff --git a/lms/static/js/views/image_field.js b/lms/static/js/views/image_field.js
index 43bb565d26..ae3bbdf3e4 100644
--- a/lms/static/js/views/image_field.js
+++ b/lms/static/js/views/image_field.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'js/views/fields',
'text!templates/fields/field_image.underscore',
'backbone-super', 'jquery.fileupload'
- ], function (gettext, $, _, Backbone, FieldViews, field_image_template) {
-
+ ], function(gettext, $, _, Backbone, FieldViews, field_image_template) {
var ImageFieldView = FieldViews.FieldView.extend({
fieldType: 'image',
@@ -13,21 +12,21 @@
fieldTemplate: field_image_template,
uploadButtonSelector: '.upload-button-input',
- titleAdd: gettext("Upload an image"),
- titleEdit: gettext("Change image"),
- titleRemove: gettext("Remove"),
+ titleAdd: gettext('Upload an image'),
+ titleEdit: gettext('Change image'),
+ titleRemove: gettext('Remove'),
- titleUploading: gettext("Uploading"),
- titleRemoving: gettext("Removing"),
+ titleUploading: gettext('Uploading'),
+ titleRemoving: gettext('Removing'),
titleImageAlt: '',
- screenReaderTitle: gettext("Image"),
+ screenReaderTitle: gettext('Image'),
iconUpload: ' ',
iconRemove: ' ',
iconProgress: ' ',
- errorMessage: gettext("An error has occurred. Refresh the page, and then try again."),
+ errorMessage: gettext('An error has occurred. Refresh the page, and then try again.'),
events: {
'click .u-field-upload-button': 'clickedUploadButton',
@@ -37,14 +36,14 @@
'blur .upload-button-input': 'hideHoverState'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'render', 'imageChangeSucceeded', 'imageChangeFailed', 'fileSelected',
'watchForPageUnload', 'onBeforeUnload');
},
- render: function () {
+ render: function() {
this.$el.html(this.template({
id: this.options.valueAttribute,
inputName: (this.options.inputName || 'file'),
@@ -62,23 +61,23 @@
return this;
},
- showHoverState: function () {
+ showHoverState: function() {
this.$('.u-field-upload-button').addClass('button-visible');
},
- hideHoverState: function () {
+ hideHoverState: function() {
this.$('.u-field-upload-button').removeClass('button-visible');
},
- showErrorMessage: function (message) {
+ showErrorMessage: function(message) {
return message;
},
- imageUrl: function () {
+ imageUrl: function() {
return '';
},
- uploadButtonTitle: function () {
+ uploadButtonTitle: function() {
if (this.isShowingPlaceholder()) {
return _.result(this, 'titleAdd');
} else {
@@ -86,27 +85,27 @@
}
},
- removeButtonTitle: function () {
+ removeButtonTitle: function() {
return this.titleRemove;
},
- isEditingAllowed: function () {
+ isEditingAllowed: function() {
return true;
},
- isShowingPlaceholder: function () {
+ isShowingPlaceholder: function() {
return false;
},
- setUploadButtonVisibility: function (state) {
+ setUploadButtonVisibility: function(state) {
this.$('.u-field-upload-button').css('display', state);
},
- setRemoveButtonVisibility: function (state) {
+ setRemoveButtonVisibility: function(state) {
this.$('.u-field-remove-button').css('display', state);
},
- updateButtonsVisibility: function () {
+ updateButtonsVisibility: function() {
if (!this.isEditingAllowed() || !this.options.editable) {
this.setUploadButtonVisibility('none');
}
@@ -116,7 +115,7 @@
}
},
- clickedUploadButton: function () {
+ clickedUploadButton: function() {
$(this.uploadButtonSelector).fileupload({
url: this.options.imageUploadUrl,
type: 'POST',
@@ -126,7 +125,7 @@
});
},
- clickedRemoveButton: function () {
+ clickedRemoveButton: function() {
var view = this;
this.setCurrentStatus('removing');
this.setUploadButtonVisibility('none');
@@ -134,24 +133,24 @@
$.ajax({
type: 'POST',
url: this.options.imageRemoveUrl
- }).done(function () {
+ }).done(function() {
view.imageChangeSucceeded();
- }).fail(function (jqXHR) {
+ }).fail(function(jqXHR) {
view.showImageChangeFailedMessage(jqXHR.status, jqXHR.responseText);
});
},
- imageChangeSucceeded: function () {
+ imageChangeSucceeded: function() {
this.render();
},
- imageChangeFailed: function (e, data) {
+ imageChangeFailed: function(e, data) {
},
- showImageChangeFailedMessage: function (status, responseText) {
+ showImageChangeFailedMessage: function(status, responseText) {
},
- fileSelected: function (e, data) {
+ fileSelected: function(e, data) {
if (_.isUndefined(data.files[0].size) || this.validateImageSize(data.files[0].size)) {
this.setCurrentStatus('uploading');
this.setRemoveButtonVisibility('none');
@@ -160,13 +159,13 @@
}
},
- validateImageSize: function (imageBytes) {
+ validateImageSize: function(imageBytes) {
var humanReadableSize;
if (imageBytes < this.options.imageMinBytes) {
humanReadableSize = this.bytesToHumanReadable(this.options.imageMinBytes);
this.showErrorMessage(
interpolate_text(
- gettext("The file must be at least {size} in size."), {size: humanReadableSize}
+ gettext('The file must be at least {size} in size.'), {size: humanReadableSize}
)
);
return false;
@@ -174,7 +173,7 @@
humanReadableSize = this.bytesToHumanReadable(this.options.imageMaxBytes);
this.showErrorMessage(
interpolate_text(
- gettext("The file must be smaller than {size} in size."), {size: humanReadableSize}
+ gettext('The file must be smaller than {size} in size.'), {size: humanReadableSize}
)
);
return false;
@@ -182,47 +181,47 @@
return true;
},
- showUploadInProgressMessage: function () {
+ showUploadInProgressMessage: function() {
this.$('.u-field-upload-button').css('opacity', 1);
this.$('.upload-button-icon').html(this.iconProgress);
this.$('.upload-button-title').html(this.titleUploading);
},
- showRemovalInProgressMessage: function () {
+ showRemovalInProgressMessage: function() {
this.$('.u-field-remove-button').css('opacity', 1);
this.$('.remove-button-icon').html(this.iconProgress);
this.$('.remove-button-title').html(this.titleRemoving);
},
- setCurrentStatus: function (status) {
+ setCurrentStatus: function(status) {
this.$('.image-wrapper').attr('data-status', status);
},
- getCurrentStatus: function () {
+ getCurrentStatus: function() {
return this.$('.image-wrapper').attr('data-status');
},
- watchForPageUnload: function () {
+ watchForPageUnload: function() {
$(window).on('beforeunload', this.onBeforeUnload);
},
- onBeforeUnload: function () {
+ onBeforeUnload: function() {
var status = this.getCurrentStatus();
if (status === 'uploading') {
- return gettext("Upload is in progress. To avoid errors, stay on this page until the process is complete.");
+ return gettext('Upload is in progress. To avoid errors, stay on this page until the process is complete.');
} else if (status === 'removing') {
- return gettext("Removal is in progress. To avoid errors, stay on this page until the process is complete.");
+ return gettext('Removal is in progress. To avoid errors, stay on this page until the process is complete.');
}
},
- bytesToHumanReadable: function (size) {
+ bytesToHumanReadable: function(size) {
var units = [gettext('bytes'), gettext('KB'), gettext('MB')];
var i = 0;
- while(size >= 1024) {
+ while (size >= 1024) {
size /= 1024;
++i;
}
- return size.toFixed(1)*1 + ' ' + units[i];
+ return size.toFixed(1) * 1 + ' ' + units[i];
}
});
diff --git a/lms/static/js/views/message_banner.js b/lms/static/js/views/message_banner.js
index 8dc6157215..f256da61e8 100644
--- a/lms/static/js/views/message_banner.js
+++ b/lms/static/js/views/message_banner.js
@@ -1,19 +1,18 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/fields/message_banner.underscore'
- ], function (gettext, $, _, Backbone, messageBannerTemplate) {
-
+ ], function(gettext, $, _, Backbone, messageBannerTemplate) {
var MessageBannerView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
if (_.isUndefined(options)) {
options = {};
}
this.options = _.defaults(options, {urgency: 'high', type: ''});
},
- render: function () {
+ render: function() {
if (_.isUndefined(this.message) || _.isNull(this.message)) {
this.$el.html('');
} else {
@@ -24,12 +23,12 @@
return this;
},
- showMessage: function (message) {
+ showMessage: function(message) {
this.message = message;
this.render();
},
- hideMessage: function () {
+ hideMessage: function() {
this.message = null;
this.render();
}
diff --git a/lms/static/js/views/notification.js b/lms/static/js/views/notification.js
index f0d61b5f6b..a5cc328f17 100644
--- a/lms/static/js/views/notification.js
+++ b/lms/static/js/views/notification.js
@@ -1,7 +1,7 @@
(function(Backbone, $, _) {
var NotificationView = Backbone.View.extend({
- events : {
- "click .action-primary": "triggerCallback"
+ events: {
+ 'click .action-primary': 'triggerCallback'
},
initialize: function() {
@@ -10,13 +10,13 @@
render: function() {
this.$el.html(this.template({
- type: this.model.get("type"),
- title: this.model.get("title"),
- message: this.model.get("message"),
- details: this.model.get("details"),
- actionText: this.model.get("actionText"),
- actionClass: this.model.get("actionClass"),
- actionIconClass: this.model.get("actionIconClass")
+ type: this.model.get('type'),
+ title: this.model.get('title'),
+ message: this.model.get('message'),
+ details: this.model.get('details'),
+ actionText: this.model.get('actionText'),
+ actionClass: this.model.get('actionClass'),
+ actionIconClass: this.model.get('actionIconClass')
}));
this.$('.message').focus();
return this;
@@ -24,7 +24,7 @@
triggerCallback: function(event) {
event.preventDefault();
- var actionCallback = this.model.get("actionCallback");
+ var actionCallback = this.model.get('actionCallback');
if (actionCallback) {
actionCallback(this);
}
diff --git a/lms/static/js/wiki/CodeMirror.init.js b/lms/static/js/wiki/CodeMirror.init.js
index 76bfbfdd9f..c0f3515fb8 100644
--- a/lms/static/js/wiki/CodeMirror.init.js
+++ b/lms/static/js/wiki/CodeMirror.init.js
@@ -1,24 +1,22 @@
$(document).ready(function() {
+ var editor = CodeMirror.fromTextArea(document.getElementById('id_content'), {
+ mode: 'edx_markdown',
+ matchBrackets: true,
+ theme: 'default',
+ lineWrapping: true,
+ keyMap: 'accessible'
+ });
- var editor = CodeMirror.fromTextArea(document.getElementById("id_content"), {
- mode: 'edx_markdown',
- matchBrackets: true,
- theme: "default",
- lineWrapping: true,
- keyMap: "accessible"
- });
+ // Store the inital contents so we can compare for unsaved changes
+ var initial_contents = editor.getValue();
- //Store the inital contents so we can compare for unsaved changes
- var initial_contents = editor.getValue();
-
- window.onbeforeunload = function askConfirm() { //Warn the user before they navigate away
- if ( editor.getValue() != initial_contents ) {
- return "You have made changes to the article that have not been saved yet.";
- }
- };
-
- $(".btn-primary").click(function() {
- initial_contents = editor.getValue();
- });
+ window.onbeforeunload = function askConfirm() { // Warn the user before they navigate away
+ if (editor.getValue() != initial_contents) {
+ return 'You have made changes to the article that have not been saved yet.';
+ }
+ };
+ $('.btn-primary').click(function() {
+ initial_contents = editor.getValue();
+ });
});
diff --git a/lms/static/js/wiki/accessible.js b/lms/static/js/wiki/accessible.js
index 90a647ceaa..beb28082ac 100644
--- a/lms/static/js/wiki/accessible.js
+++ b/lms/static/js/wiki/accessible.js
@@ -1,11 +1,11 @@
/* By default, CodeMirror turns tabs into indents, which makes it difficult for keyboard-only
- users to "tab through" elements on a page. Including this file and setting keyMap to
+ users to "tab through" elements on a page. Including this file and setting keyMap to
"accessible" removes the "tab" from CodeMirror's default KeyMap to remedy this problem */
(function() {
- var keyMap = CodeMirror.keyMap.accessible = {
- "Tab": false,
- "Shift-Tab": false,
- fallthrough: "default"
- };
+ var keyMap = CodeMirror.keyMap.accessible = {
+ 'Tab': false,
+ 'Shift-Tab': false,
+ fallthrough: 'default'
+ };
})();
diff --git a/lms/static/karma_lms.conf.js b/lms/static/karma_lms.conf.js
index 75bd7b9322..0c48fa9784 100644
--- a/lms/static/karma_lms.conf.js
+++ b/lms/static/karma_lms.conf.js
@@ -54,6 +54,6 @@ var options = {
]
};
-module.exports = function (config) {
+module.exports = function(config) {
configModule.configure(config, options);
};
diff --git a/lms/static/karma_lms_coffee.conf.js b/lms/static/karma_lms_coffee.conf.js
index e65d9890ee..325bb7a92e 100644
--- a/lms/static/karma_lms_coffee.conf.js
+++ b/lms/static/karma_lms_coffee.conf.js
@@ -67,6 +67,6 @@ var options = {
]
};
-module.exports = function (config) {
+module.exports = function(config) {
configModule.configure(config, options);
};
diff --git a/lms/static/lms/js/build.js b/lms/static/lms/js/build.js
index 7579e00a7e..c774837178 100644
--- a/lms/static/lms/js/build.js
+++ b/lms/static/lms/js/build.js
@@ -162,4 +162,5 @@
*/
logLevel: 1
};
-}())
+}()) // eslint-disable-line semi
+// A semicolon on the line above will break the requirejs optimizer
diff --git a/lms/static/lms/js/preview/preview_factory.js b/lms/static/lms/js/preview/preview_factory.js
index 7def8f75c3..c8beba6282 100644
--- a/lms/static/lms/js/preview/preview_factory.js
+++ b/lms/static/lms/js/preview/preview_factory.js
@@ -1,10 +1,9 @@
-;(function(define) {
+(function(define) {
'use strict';
define(['jquery', 'common/js/components/utils/view_utils'],
function($, ViewUtils) {
return function(options) {
-
var $selectElement = $('.action-preview-select'),
$userNameElement = $('.action-preview-username'),
$userNameContainer = $('.action-preview-username-container');
diff --git a/lms/static/lms/js/require-config.js b/lms/static/lms/js/require-config.js
index 4630b7af32..741aefd58f 100644
--- a/lms/static/lms/js/require-config.js
+++ b/lms/static/lms/js/require-config.js
@@ -1,20 +1,20 @@
-;(function(require, define) {
+(function(require, define) {
'use strict';
// We do not wish to bundle common libraries (that may also be used by non-RequireJS code on the page
// into the optimized files. Therefore load these libraries through script tags and explicitly define them.
// Note that when the optimizer executes this code, window will not be defined.
if (window) {
- var defineDependency = function (globalName, name, noShim) {
+ var defineDependency = function(globalName, name, noShim) {
var getGlobalValue = function(name) {
- var globalNamePath = name.split('.'),
- result = window,
- i;
- for (i = 0; i < globalNamePath.length; i++) {
- result = result[globalNamePath[i]];
- }
- return result;
- },
+ var globalNamePath = name.split('.'),
+ result = window,
+ i;
+ for (i = 0; i < globalNamePath.length; i++) {
+ result = result[globalNamePath[i]];
+ }
+ return result;
+ },
globalValue = getGlobalValue(globalName);
if (globalValue) {
if (noShim) {
diff --git a/lms/static/lms/js/spec/main.js b/lms/static/lms/js/spec/main.js
index 5c4d42cf96..f7a8066c08 100644
--- a/lms/static/lms/js/spec/main.js
+++ b/lms/static/lms/js/spec/main.js
@@ -391,7 +391,7 @@
'underscore.string',
'edx-ui-toolkit/js/utils/html-utils',
'edx-ui-toolkit/js/utils/string-utils'
- ], function (_, str, HtmlUtils, StringUtils) {
+ ], function(_, str, HtmlUtils, StringUtils) {
window._ = _;
window._.str = str;
window.edx = edx || {};
diff --git a/lms/static/lms/js/spec/main_requirejs_coffee.js b/lms/static/lms/js/spec/main_requirejs_coffee.js
index c305f44cda..8b6098fecf 100644
--- a/lms/static/lms/js/spec/main_requirejs_coffee.js
+++ b/lms/static/lms/js/spec/main_requirejs_coffee.js
@@ -4,16 +4,16 @@
// into the optimized files. Therefore load these libraries through script tags and explicitly define them.
// Note that when the optimizer executes this code, window will not be defined.
if (window) {
- var defineDependency = function (globalName, name, noShim) {
+ var defineDependency = function(globalName, name, noShim) {
var getGlobalValue = function(name) {
- var globalNamePath = name.split('.'),
- result = window,
- i;
- for (i = 0; i < globalNamePath.length; i++) {
- result = result[globalNamePath[i]];
- }
- return result;
- },
+ var globalNamePath = name.split('.'),
+ result = window,
+ i;
+ for (i = 0; i < globalNamePath.length; i++) {
+ result = result[globalNamePath[i]];
+ }
+ return result;
+ },
globalValue = getGlobalValue(globalName);
if (globalValue) {
if (noShim) {
@@ -24,23 +24,22 @@
}
}
else {
- console.error("Expected library to be included on page, but not found on window object: " + name);
+ console.error('Expected library to be included on page, but not found on window object: ' + name);
}
};
- defineDependency("jQuery", "jquery");
- defineDependency("jQuery", "jquery-migrate");
- defineDependency("_", "underscore");
+ defineDependency('jQuery', 'jquery');
+ defineDependency('jQuery', 'jquery-migrate');
+ defineDependency('_', 'underscore');
}
requirejs.config({
baseUrl: '/base/',
paths: {
- "moment": "xmodule_js/common_static/js/vendor/moment.min",
- "draggabilly": "xmodule_js/common_static/js/vendor/draggabilly",
+ 'moment': 'xmodule_js/common_static/js/vendor/moment.min',
+ 'draggabilly': 'xmodule_js/common_static/js/vendor/draggabilly',
'edx-ui-toolkit': 'edx-ui-toolkit'
},
- "moment": {
- exports: "moment"
+ 'moment': {
+ exports: 'moment'
}
});
-
}).call(this, RequireJS.requirejs, RequireJS.define);
diff --git a/lms/static/lms/js/xblock/lms.runtime.v1.js b/lms/static/lms/js/xblock/lms.runtime.v1.js
index 362c760b2a..6f8e14a5f8 100644
--- a/lms/static/lms/js/xblock/lms.runtime.v1.js
+++ b/lms/static/lms/js/xblock/lms.runtime.v1.js
@@ -23,7 +23,6 @@
this.LmsRuntime = {};
this.LmsRuntime.v1 = (function(_super) {
-
__extends(v1, _super);
function v1() {
@@ -51,6 +50,5 @@
};
return v1;
-
})(XBlock.Runtime.v1);
}).call(this, URI);
diff --git a/lms/static/sass/_build-learner-dashboard.scss b/lms/static/sass/_build-learner-dashboard.scss
index b7d41431ee..e37c4dadf6 100644
--- a/lms/static/sass/_build-learner-dashboard.scss
+++ b/lms/static/sass/_build-learner-dashboard.scss
@@ -3,8 +3,8 @@
// Uses the Pattern Library
@import 'elements/banners';
-@import 'elements/program-card';
@import 'elements/course-card';
-@import 'elements/icons';
-@import 'views/program-list';
+@import 'elements/program-card';
+@import 'elements-v2/icons';
@import 'views/program-details';
+@import 'views/program-list';
diff --git a/lms/static/sass/_build-lms-v1.scss b/lms/static/sass/_build-lms-v1.scss
index 5a4d609076..bed818540f 100644
--- a/lms/static/sass/_build-lms-v1.scss
+++ b/lms/static/sass/_build-lms-v1.scss
@@ -13,11 +13,12 @@
@import 'base/base';
// base - elements
-@import 'elements/typography';
@import 'elements/controls';
+@import 'elements/creative-commons';
+@import 'elements/icons';
@import 'elements/navigation';
@import 'elements/pagination';
-@import 'elements/creative-commons';
+@import 'elements/typography';
// shared - course
@import 'shared/fields';
diff --git a/lms/static/sass/elements-v2/_icons.scss b/lms/static/sass/elements-v2/_icons.scss
new file mode 100644
index 0000000000..cdbddd4ada
--- /dev/null
+++ b/lms/static/sass/elements-v2/_icons.scss
@@ -0,0 +1,34 @@
+.xseries-icon {
+ background: url('#{$static-path}/images/programs/xseries-icon.svg') no-repeat;
+}
+
+.micromasters-icon {
+ margin-top: $baseline * 0.05;
+ background: url('#{$static-path}/images/programs/micromasters-icon.svg') no-repeat;
+}
+
+.certificate-body {
+ // Use the ampersand to reference parent selectors.
+ .certificate-icon & {
+ @include float(left);
+ @include margin-right($baseline*0.4);
+
+ margin-top: ($baseline/10);
+ width: 23px;
+ height: 20px;
+ padding: 2px;
+ background-color: $white;
+ border-style: solid;
+ border-width: 2px;
+ }
+
+ .green-icon & {
+ fill: palette(success, text);
+ border-color: palette(success, text);
+ }
+
+ .blue-icon & {
+ fill: palette(primary, dark);
+ border-color: palette(primary, dark);
+ }
+}
diff --git a/lms/static/sass/elements/_icons.scss b/lms/static/sass/elements/_icons.scss
index 10d07773c3..67dac4b611 100644
--- a/lms/static/sass/elements/_icons.scss
+++ b/lms/static/sass/elements/_icons.scss
@@ -1,22 +1,8 @@
-.certificate-icon .certificate-body {
- @include float(left);
- @include margin-right($baseline*0.4);
-
- margin-top: ($baseline/10);
- width: 23px;
- height: 20px;
- padding: 2px;
- background-color: $white;
- border-style: solid;
- border-width: 2px;
+.xseries-icon {
+ background: url('#{$static-path}/images/programs/xseries-icon.svg') no-repeat;
}
-.green-certificate-icon .certificate-body {
- fill: palette(success, accent);
- border-color: palette(success, accent);
-}
-
-.blue-certificate-icon .certificate-body {
- fill: palette(primary, dark);
- border-color: palette(primary, dark);
+.micromasters-icon {
+ margin-top: $baseline * 0.05;
+ background: url('#{$static-path}/images/programs/micromasters-icon.svg') no-repeat;
}
diff --git a/lms/static/sass/elements/_program-card.scss b/lms/static/sass/elements/_program-card.scss
index b619cdc04e..366bb471fb 100644
--- a/lms/static/sass/elements/_program-card.scss
+++ b/lms/static/sass/elements/_program-card.scss
@@ -97,15 +97,6 @@
width: ($baseline*0.7);
height: ($baseline*0.7);
}
-
- .xseries-icon{
- background: url('#{$static-path}/images/programs/xseries-icon.svg') no-repeat;
- }
-
- .micromasters-icon{
- margin-top: $baseline * 0.05;
- background: url('#{$static-path}/images/programs/micromasters-icon.svg') no-repeat;
- }
}
.hd-3 {
diff --git a/lms/static/sass/multicourse/_dashboard.scss b/lms/static/sass/multicourse/_dashboard.scss
index b5885236f5..308356f5be 100644
--- a/lms/static/sass/multicourse/_dashboard.scss
+++ b/lms/static/sass/multicourse/_dashboard.scss
@@ -62,32 +62,6 @@
}
}
- .wrapper-xseries-certificates{
- @include float(right);
- @include margin-left(flex-gutter());
- width: flex-grid(3);
-
- .title{
- @extend %t-title7;
- @extend %t-weight4;
- }
-
- ul{
- @include padding-left(0);
- margin-top: ($baseline/2);
- }
-
- li{
- @include line-height(20);
- list-style-type: none;
- }
-
- .copy {
- @extend %t-copy-sub1;
- margin-top: ($baseline/2);
- }
- }
-
.profile-sidebar {
background: transparent;
@include float(right);
@@ -304,31 +278,11 @@
border-bottom: 4px solid $border-color-l4;
padding-bottom: $baseline;
- .course-container{
+ .course-container {
border: 1px solid $border-color-l4;
border-radius: 3px;
-
- // CASE: Xseries associated course
- .label-xseries-association{
- @include margin($baseline/2, $baseline/5, 0, $baseline/2);
-
- .xseries-icon{
- @include float(left);
-
- @include margin-right($baseline*0.4);
- background: url('#{$static-path}/images/icon-sm-xseries-black.png') no-repeat;
- background-color: transparent;
-
- width: ($baseline*1.1);
- height: ($baseline*1.1);
- }
-
- .message-copy{
- padding-top: ($baseline/5);
- @extend %t-action3;
- }
- }
}
+
&:last-child {
margin-bottom: 0;
border-bottom: none;
@@ -860,100 +814,6 @@
}
}
- .xseries-action{
- .xseries-msg{
- @include float(left);
- width: flex-grid(9, 12);
- }
-
- .message-copy{
- @extend %t-demi-strong;
- margin-top: 0;
- }
-
- .message-copy-bold{
- @extend %t-strong;
- }
-
- .xseries-border-btn {
- @extend %btn-pl-black-border;
- @include float(right);
- position: relative;
- @include left(10px);
- padding: ($baseline*0.4) ($baseline*0.6);
- background-image: none ;
- text-shadow: none;
- box-shadow: none;
- text-transform: none;
-
- .action-xseries-icon{
- @include float(left);
- display: inline;
-
- @include margin-right($baseline*0.4);
- background: url('#{$static-path}/images/icon-sm-xseries-black.png') no-repeat;
- background-color: transparent;
-
- width: ($baseline*1.1);
- height: ($baseline*1.1);
- }
- &:hover,
- &:focus {
-
- .action-xseries-icon{
- @include float(left);
- display: inline;
-
- @include margin-right($baseline*0.4);
- background: url('#{$static-path}/images/icon-sm-xseries-white.png') no-repeat;
- background-color: transparent;
-
- width: ($baseline*1.1);
- height: ($baseline*1.1);
- }
- }
- }
-
- .xseries-base-btn {
- @extend %btn-pl-black-base;
- @include float(right);
- position: relative;
- @include left(10px);
- padding: ($baseline*0.4) ($baseline*0.6);
- background-image: none ;
- text-shadow: none;
- box-shadow: none;
- text-transform: none;
-
- .action-xseries-icon{
- @include float(left);
- display: inline;
-
- @include margin-right($baseline*0.4);
- background: url('#{$static-path}/images/icon-sm-xseries-white.png') no-repeat;
- background-color: transparent;
-
- width: ($baseline*1.1);
- height: ($baseline*1.1);
- }
- &:hover,
- &:focus {
-
- .action-xseries-icon {
- @include float(left);
- display: inline;
-
- @include margin-right($baseline*0.4);
- background: url('#{$static-path}/images/icon-sm-xseries-black.png') no-repeat;
- background-color: transparent;
-
- width: ($baseline*1.1);
- height: ($baseline*1.1);
- }
- }
- }
- }
-
.actions {
.action {
@@ -1129,6 +989,46 @@
}
}
+ &.message-related-programs {
+ background: none;
+ border: none;
+ margin-top: ($baseline/4);
+ padding-bottom: 0;
+
+ .related-programs-preface {
+ @include float(left);
+ font-weight: bold;
+ }
+
+ ul {
+ display: inline;
+ padding: 0;
+ margin: 0;
+ }
+
+ li {
+ @include float(left);
+ display: inline;
+ padding: 0 0.5em;
+ border-right: 1px solid;
+
+ .category-icon {
+ @include float(left);
+ @include margin-right($baseline/4);
+ margin-top: ($baseline/10);
+ background-color: transparent;
+ background-size: 100%;
+ width: ($baseline*0.7);
+ height: ($baseline*0.7);
+ }
+ }
+
+ // Remove separator from last list item.
+ li:last-child {
+ border: 0;
+ }
+ }
+
// TYPE: pre-requisites
.prerequisites {
@include clearfix;
diff --git a/lms/templates/dashboard.html b/lms/templates/dashboard.html
index 4cc0be1f36..1beaa56c4a 100644
--- a/lms/templates/dashboard.html
+++ b/lms/templates/dashboard.html
@@ -98,8 +98,8 @@ from openedx.core.djangolib.markup import HTML, Text
<% is_course_blocked = (enrollment.course_id in block_courses) %>
<% course_verification_status = verification_status_by_course.get(enrollment.course_id, {}) %>
<% course_requirements = courses_requirements_not_met.get(enrollment.course_id) %>
- <% course_program_info = course_programs.get(unicode(enrollment.course_id)) %>
- <%include file = 'dashboard/_dashboard_course_listing.html' args="course_overview=enrollment.course_overview, enrollment=enrollment, show_courseware_link=show_courseware_link, cert_status=cert_status, can_unenroll=can_unenroll, credit_status=credit_status, show_email_settings=show_email_settings, course_mode_info=course_mode_info, show_refund_option=show_refund_option, is_paid_course=is_paid_course, is_course_blocked=is_course_blocked, verification_status=course_verification_status, course_requirements=course_requirements, dashboard_index=dashboard_index, share_settings=share_settings, user=user, course_program_info=course_program_info" />
+ <% related_programs = programs_by_run.get(unicode(enrollment.course_id)) %>
+ <%include file = 'dashboard/_dashboard_course_listing.html' args="course_overview=enrollment.course_overview, enrollment=enrollment, show_courseware_link=show_courseware_link, cert_status=cert_status, can_unenroll=can_unenroll, credit_status=credit_status, show_email_settings=show_email_settings, course_mode_info=course_mode_info, show_refund_option=show_refund_option, is_paid_course=is_paid_course, is_course_blocked=is_course_blocked, verification_status=course_verification_status, course_requirements=course_requirements, dashboard_index=dashboard_index, share_settings=share_settings, user=user, related_programs=related_programs" />
% endfor
diff --git a/lms/templates/dashboard/_dashboard_course_listing.html b/lms/templates/dashboard/_dashboard_course_listing.html
index 1904dfc2ac..0bf4d6d1c5 100644
--- a/lms/templates/dashboard/_dashboard_course_listing.html
+++ b/lms/templates/dashboard/_dashboard_course_listing.html
@@ -1,4 +1,4 @@
-<%page args="course_overview, enrollment, show_courseware_link, cert_status, can_unenroll, credit_status, show_email_settings, course_mode_info, show_refund_option, is_paid_course, is_course_blocked, verification_status, course_requirements, dashboard_index, share_settings, course_program_info" expression_filter="h"/>
+<%page args="course_overview, enrollment, show_courseware_link, cert_status, can_unenroll, credit_status, show_email_settings, course_mode_info, show_refund_option, is_paid_course, is_course_blocked, verification_status, course_requirements, dashboard_index, share_settings, related_programs" expression_filter="h"/>
<%!
import urllib
@@ -53,12 +53,6 @@ from student.helpers import (
<% mode_class = '' %>
% endif
- % if course_program_info and course_program_info.get('category')=='XSeries':
-
-
-
${_("{category} Program Course").format(category=course_program_info['category'])}
-
- % endif
<% course_target = reverse('info', args=[unicode(course_overview.id)]) %>
@@ -283,6 +277,20 @@ from student.helpers import (
+ % if related_programs:
+
+ % endif
+
% if course_overview.may_certify() and cert_status:
<%include file='_dashboard_certificate_information.html' args='cert_status=cert_status,course_overview=course_overview, enrollment=enrollment, reverify_link=reverify_link'/>
% endif
diff --git a/lms/templates/dashboard/_dashboard_program_info.html b/lms/templates/dashboard/_dashboard_program_info.html
deleted file mode 100644
index 5615fb3eb3..0000000000
--- a/lms/templates/dashboard/_dashboard_program_info.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<%page expression_filter="h" args="program_data, enrollment_mode, category" />
-<%!
- from django.utils.translation import ugettext as _
- from openedx.core.djangolib.markup import HTML, Text
-%>
-<%namespace name='static' file='../static_content.html'/>
-
diff --git a/lms/templates/fields/field_dropdown.underscore b/lms/templates/fields/field_dropdown.underscore
index 8f0c61f5b2..097365c9dc 100644
--- a/lms/templates/fields/field_dropdown.underscore
+++ b/lms/templates/fields/field_dropdown.underscore
@@ -23,8 +23,13 @@
<% if (showBlankOption) { %>
<% } %>
- <% _.each(selectOptions, function(selectOption) { %>
- <%- selectOption[1] %>
+ <% _.each(groupOptions, function(groupOption) { %>
+ <% if (groupOption.groupTitle != null) { %>
+
+ <% } %>
+ <% _.each(groupOption.selectOptions, function(selectOption) { %>
+ <%- selectOption[1] %>
+ <% }); %>
<% }); %>
diff --git a/lms/templates/fields/field_dropdown_account.underscore b/lms/templates/fields/field_dropdown_account.underscore
index 535cee9a15..718fffb3eb 100644
--- a/lms/templates/fields/field_dropdown_account.underscore
+++ b/lms/templates/fields/field_dropdown_account.underscore
@@ -23,8 +23,13 @@
<% if (showBlankOption) { %>
<% } %>
- <% _.each(selectOptions, function(selectOption) { %>
- <%- selectOption[1] %>
+ <% _.each(groupOptions, function(groupOption) { %>
+ <% if (groupOption.groupTitle != null) { %>
+
+ <% } %>
+ <% _.each(groupOption.selectOptions, function(selectOption) { %>
+ <%- selectOption[1] %>
+ <% }); %>
<% }); %>
diff --git a/lms/templates/learner_dashboard/certificate_status.underscore b/lms/templates/learner_dashboard/certificate_status.underscore
index 1cca1038a9..035f49d41a 100644
--- a/lms/templates/learner_dashboard/certificate_status.underscore
+++ b/lms/templates/learner_dashboard/certificate_status.underscore
@@ -1,12 +1,12 @@
<% // safe-lint: disable=underscore-not-escaped %>
- <%= certificateSvg %>
+ <%= certificateSvg %>
<%- gettext('Congratulations! You have earned a certificate for this course.') %>
diff --git a/lms/templates/learner_dashboard/upgrade_message.underscore b/lms/templates/learner_dashboard/upgrade_message.underscore
index 2977a1f686..433c2f5520 100644
--- a/lms/templates/learner_dashboard/upgrade_message.underscore
+++ b/lms/templates/learner_dashboard/upgrade_message.underscore
@@ -1,12 +1,12 @@
<% // safe-lint: disable=underscore-not-escaped %>
- <%= certificateSvg %>
+ <%= certificateSvg %>
<%- gettext('You need a certificate in this course to be eligible for a program certificate.') %>
diff --git a/lms/templates/user_dropdown.html b/lms/templates/user_dropdown.html
index e754714111..1c272a812b 100644
--- a/lms/templates/user_dropdown.html
+++ b/lms/templates/user_dropdown.html
@@ -20,7 +20,7 @@ from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_
${username}
-
diff --git a/themes/edx.org/lms/templates/footer.html b/themes/edx.org/lms/templates/footer.html
index e6b1a09ec4..77949638f1 100644
--- a/themes/edx.org/lms/templates/footer.html
+++ b/themes/edx.org/lms/templates/footer.html
@@ -18,7 +18,9 @@