diff --git a/migrations/users/achievement-restore.js b/migrations/users/achievement-restore.js
index 7a790a7e28..75b8d456cb 100644
--- a/migrations/users/achievement-restore.js
+++ b/migrations/users/achievement-restore.js
@@ -79,7 +79,7 @@ module.exports = async function achievementRestore () {
const userIds = [
];
- Promise.all(userIds.map(userId => (async () => {
+ await Promise.all(userIds.map(userId => (async () => {
const oldUser = await UsersOld.findOne({ _id: userId }, 'achievements');
const newUser = await Users.findOne({ _id: userId }, 'achievements');
const achievementUpdate = getAchievementUpdate(newUser, oldUser);
diff --git a/package-lock.json b/package-lock.json
index a8139bd824..025124ae7e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -4476,9 +4476,9 @@
}
},
"eslint-config-habitrpg": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/eslint-config-habitrpg/-/eslint-config-habitrpg-6.0.3.tgz",
- "integrity": "sha512-TYDXHE40Yu65uMHDqqepX0apOQvOGKZhvjz0Rki9CqL4HWO0QfHxv9Vi3mvVzY6+vrNvnUKs1s37SLTUMakiAg==",
+ "version": "6.0.7",
+ "resolved": "https://registry.npmjs.org/eslint-config-habitrpg/-/eslint-config-habitrpg-6.0.7.tgz",
+ "integrity": "sha512-hda2IKsfwE/94CjLtPI3Cgsq0capQCFKCiqPPNM7foeO/E6cZpXCSvMHdGt5TXy66DQxF5h+kz4xcheHdcaRcA==",
"dev": true,
"requires": {
"eslint": "^6.5.1",
diff --git a/package.json b/package.json
index 72cb676b8d..21295d9d87 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,7 @@
"npm": "^6"
},
"scripts": {
- "lint": "eslint --ext .js ./test --fix",
+ "lint": "eslint --ext .js .",
"test": "npm run lint && gulp test && gulp apidoc",
"test:build": "gulp test:prepare:build",
"test:api-v3": "gulp test:api-v3",
@@ -103,7 +103,7 @@
"chai-as-promised": "^7.1.1",
"chalk": "^2.4.1",
"eslint": "^6.5.1",
- "eslint-config-habitrpg": "^6.0.3",
+ "eslint-config-habitrpg": "^6.0.7",
"eslint-plugin-mocha": "^5.0.0",
"expect.js": "^0.3.1",
"istanbul": "^1.1.0-alpha.1",
diff --git a/test/.eslintrc b/test/.eslintrc
deleted file mode 100644
index 10397df6d7..0000000000
--- a/test/.eslintrc
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": [
- "habitrpg/lib/mocha",
- ],
- "globals": {
- "_": true,
- }
-}
diff --git a/test/api/unit/libs/analyticsService.test.js b/test/api/unit/libs/analyticsService.test.js
index 055ac95028..27d78d3f3c 100644
--- a/test/api/unit/libs/analyticsService.test.js
+++ b/test/api/unit/libs/analyticsService.test.js
@@ -1,7 +1,7 @@
/* eslint-disable camelcase */
-import * as analyticsService from '../../../../website/server/libs/analyticsService';
import Amplitude from 'amplitude';
import { Visitor } from 'universal-analytics';
+import * as analyticsService from '../../../../website/server/libs/analyticsService';
describe('analyticsService', () => {
beforeEach(() => {
@@ -16,7 +16,8 @@ describe('analyticsService', () => {
});
describe('#track', () => {
- let eventType, data;
+ let eventType; let
+ data;
beforeEach(() => {
Visitor.prototype.event.yields();
@@ -35,12 +36,10 @@ describe('analyticsService', () => {
});
context('Amplitude', () => {
- it('calls out to amplitude', () => {
- return analyticsService.track(eventType, data)
- .then(() => {
- expect(Amplitude.prototype.track).to.be.calledOnce;
- });
- });
+ it('calls out to amplitude', () => analyticsService.track(eventType, data)
+ .then(() => {
+ expect(Amplitude.prototype.track).to.be.calledOnce;
+ }));
it('uses a dummy user id if none is provided', () => {
delete data.uuid;
@@ -55,7 +54,7 @@ describe('analyticsService', () => {
context('platform', () => {
it('logs web platform', () => {
- data.headers = {'x-client': 'habitica-web'};
+ data.headers = { 'x-client': 'habitica-web' };
return analyticsService.track(eventType, data)
.then(() => {
@@ -66,7 +65,7 @@ describe('analyticsService', () => {
});
it('logs iOS platform', () => {
- data.headers = {'x-client': 'habitica-ios'};
+ data.headers = { 'x-client': 'habitica-ios' };
return analyticsService.track(eventType, data)
.then(() => {
@@ -77,7 +76,7 @@ describe('analyticsService', () => {
});
it('logs Android platform', () => {
- data.headers = {'x-client': 'habitica-android'};
+ data.headers = { 'x-client': 'habitica-android' };
return analyticsService.track(eventType, data)
.then(() => {
@@ -88,7 +87,7 @@ describe('analyticsService', () => {
});
it('logs 3rd Party platform', () => {
- data.headers = {'x-client': 'some-third-party'};
+ data.headers = { 'x-client': 'some-third-party' };
return analyticsService.track(eventType, data)
.then(() => {
@@ -169,18 +168,16 @@ describe('analyticsService', () => {
});
});
- it('sends details about event', () => {
- return analyticsService.track(eventType, data)
- .then(() => {
- expect(Amplitude.prototype.track).to.be.calledWithMatch({
- event_properties: {
- category: 'behavior',
- resting: true,
- cronCount: 5,
- },
- });
+ it('sends details about event', () => analyticsService.track(eventType, data)
+ .then(() => {
+ expect(Amplitude.prototype.track).to.be.calledWithMatch({
+ event_properties: {
+ category: 'behavior',
+ resting: true,
+ cronCount: 5,
+ },
});
- });
+ }));
it('sends english item name for gear if itemKey is provided', () => {
data.itemKey = 'headAccessory_special_foxEars';
@@ -267,16 +264,18 @@ describe('analyticsService', () => {
});
it('sends user data if provided', () => {
- let stats = { class: 'wizard', exp: 5, gp: 23, hp: 10, lvl: 4, mp: 30 };
- let user = {
+ const stats = {
+ class: 'wizard', exp: 5, gp: 23, hp: 10, lvl: 4, mp: 30,
+ };
+ const user = {
stats,
contributor: { level: 1 },
purchased: { plan: { planId: 'foo-plan' } },
- flags: {tour: {intro: -2}},
- habits: [{_id: 'habit'}],
- dailys: [{_id: 'daily'}],
- todos: [{_id: 'todo'}],
- rewards: [{_id: 'reward'}],
+ flags: { tour: { intro: -2 } },
+ habits: [{ _id: 'habit' }],
+ dailys: [{ _id: 'daily' }],
+ todos: [{ _id: 'todo' }],
+ rewards: [{ _id: 'reward' }],
balance: 12,
loginIncentives: 1,
};
@@ -312,27 +311,24 @@ describe('analyticsService', () => {
});
context('GA', () => {
- it('calls out to GA', () => {
- return analyticsService.track(eventType, data)
- .then(() => {
- expect(Visitor.prototype.event).to.be.calledOnce;
- });
- });
+ it('calls out to GA', () => analyticsService.track(eventType, data)
+ .then(() => {
+ expect(Visitor.prototype.event).to.be.calledOnce;
+ }));
- it('sends details about event', () => {
- return analyticsService.track(eventType, data)
- .then(() => {
- expect(Visitor.prototype.event).to.be.calledWith({
- ea: 'Cron',
- ec: 'behavior',
- });
+ it('sends details about event', () => analyticsService.track(eventType, data)
+ .then(() => {
+ expect(Visitor.prototype.event).to.be.calledWith({
+ ea: 'Cron',
+ ec: 'behavior',
});
- });
+ }));
});
});
describe('#trackPurchase', () => {
- let data, itemSpy;
+ let data; let
+ itemSpy;
beforeEach(() => {
Visitor.prototype.event.yields();
@@ -361,12 +357,10 @@ describe('analyticsService', () => {
});
context('Amplitude', () => {
- it('calls out to amplitude', () => {
- return analyticsService.trackPurchase(data)
- .then(() => {
- expect(Amplitude.prototype.track).to.be.calledOnce;
- });
- });
+ it('calls out to amplitude', () => analyticsService.trackPurchase(data)
+ .then(() => {
+ expect(Amplitude.prototype.track).to.be.calledOnce;
+ }));
it('uses a dummy user id if none is provided', () => {
delete data.uuid;
@@ -381,7 +375,7 @@ describe('analyticsService', () => {
context('platform', () => {
it('logs web platform', () => {
- data.headers = {'x-client': 'habitica-web'};
+ data.headers = { 'x-client': 'habitica-web' };
return analyticsService.trackPurchase(data)
.then(() => {
@@ -392,7 +386,7 @@ describe('analyticsService', () => {
});
it('logs iOS platform', () => {
- data.headers = {'x-client': 'habitica-ios'};
+ data.headers = { 'x-client': 'habitica-ios' };
return analyticsService.trackPurchase(data)
.then(() => {
@@ -403,7 +397,7 @@ describe('analyticsService', () => {
});
it('logs Android platform', () => {
- data.headers = {'x-client': 'habitica-android'};
+ data.headers = { 'x-client': 'habitica-android' };
return analyticsService.trackPurchase(data)
.then(() => {
@@ -414,7 +408,7 @@ describe('analyticsService', () => {
});
it('logs 3rd Party platform', () => {
- data.headers = {'x-client': 'some-third-party'};
+ data.headers = { 'x-client': 'some-third-party' };
return analyticsService.trackPurchase(data)
.then(() => {
@@ -495,33 +489,33 @@ describe('analyticsService', () => {
});
});
- it('sends details about purchase', () => {
- return analyticsService.trackPurchase(data)
- .then(() => {
- expect(Amplitude.prototype.track).to.be.calledWithMatch({
- event_properties: {
- gift: false,
- itemPurchased: 'Gems',
- paymentMethod: 'PayPal',
- purchaseType: 'checkout',
- quantity: 1,
- sku: 'paypal-checkout',
- },
- });
+ it('sends details about purchase', () => analyticsService.trackPurchase(data)
+ .then(() => {
+ expect(Amplitude.prototype.track).to.be.calledWithMatch({
+ event_properties: {
+ gift: false,
+ itemPurchased: 'Gems',
+ paymentMethod: 'PayPal',
+ purchaseType: 'checkout',
+ quantity: 1,
+ sku: 'paypal-checkout',
+ },
});
- });
+ }));
it('sends user data if provided', () => {
- let stats = { class: 'wizard', exp: 5, gp: 23, hp: 10, lvl: 4, mp: 30 };
- let user = {
+ const stats = {
+ class: 'wizard', exp: 5, gp: 23, hp: 10, lvl: 4, mp: 30,
+ };
+ const user = {
stats,
contributor: { level: 1 },
purchased: { plan: { planId: 'foo-plan' } },
- flags: {tour: {intro: -2}},
- habits: [{_id: 'habit'}],
- dailys: [{_id: 'daily'}],
- todos: [{_id: 'todo'}],
- rewards: [{_id: 'reward'}],
+ flags: { tour: { intro: -2 } },
+ habits: [{ _id: 'habit' }],
+ dailys: [{ _id: 'daily' }],
+ todos: [{ _id: 'todo' }],
+ rewards: [{ _id: 'reward' }],
};
data.user = user;
@@ -552,27 +546,23 @@ describe('analyticsService', () => {
});
context('GA', () => {
- it('calls out to GA', () => {
- return analyticsService.trackPurchase(data)
- .then(() => {
- expect(Visitor.prototype.event).to.be.calledOnce;
- expect(Visitor.prototype.transaction).to.be.calledOnce;
- });
- });
+ it('calls out to GA', () => analyticsService.trackPurchase(data)
+ .then(() => {
+ expect(Visitor.prototype.event).to.be.calledOnce;
+ expect(Visitor.prototype.transaction).to.be.calledOnce;
+ }));
- it('sends details about purchase', () => {
- return analyticsService.trackPurchase(data)
- .then(() => {
- expect(Visitor.prototype.event).to.be.calledWith({
- ea: 'checkout',
- ec: 'commerce',
- el: 'PayPal',
- ev: 8,
- });
- expect(Visitor.prototype.transaction).to.be.calledWith('user-id', 8);
- expect(itemSpy).to.be.calledWith(8, 1, 'paypal-checkout', 'Gems', 'checkout');
+ it('sends details about purchase', () => analyticsService.trackPurchase(data)
+ .then(() => {
+ expect(Visitor.prototype.event).to.be.calledWith({
+ ea: 'checkout',
+ ec: 'commerce',
+ el: 'PayPal',
+ ev: 8,
});
- });
+ expect(Visitor.prototype.transaction).to.be.calledWith('user-id', 8);
+ expect(itemSpy).to.be.calledWith(8, 1, 'paypal-checkout', 'Gems', 'checkout');
+ }));
});
});
diff --git a/test/api/unit/libs/apiError.js b/test/api/unit/libs/apiError.js
index fda9b1788b..c9c8357f2f 100644
--- a/test/api/unit/libs/apiError.js
+++ b/test/api/unit/libs/apiError.js
@@ -11,7 +11,7 @@ describe('API Messages', () => {
});
it('clones the passed variables', () => {
- let vars = {a: 1};
+ const vars = { a: 1 };
sandbox.stub(_, 'clone').returns({});
apiError('guildsOnlyPaginate', vars);
expect(_.clone).to.have.been.calledOnce;
@@ -19,8 +19,8 @@ describe('API Messages', () => {
});
it('pass the message through _.template', () => {
- let vars = {a: 1};
- let stub = sinon.stub().returns('string');
+ const vars = { a: 1 };
+ const stub = sinon.stub().returns('string');
sandbox.stub(_, 'template').returns(stub);
apiError('guildsOnlyPaginate', vars);
expect(_.template).to.have.been.calledOnce;
diff --git a/test/api/unit/libs/baseModel.test.js b/test/api/unit/libs/baseModel.test.js
index 28e85aea50..44fbf1854c 100644
--- a/test/api/unit/libs/baseModel.test.js
+++ b/test/api/unit/libs/baseModel.test.js
@@ -1,5 +1,5 @@
-import baseModel from '../../../../website/server/libs/baseModel';
import mongoose from 'mongoose';
+import baseModel from '../../../../website/server/libs/baseModel';
describe('Base model plugin', () => {
let schema;
@@ -25,7 +25,7 @@ describe('Base model plugin', () => {
});
it('can add timestamps fields', () => {
- schema.plugin(baseModel, {timestamps: true});
+ schema.plugin(baseModel, { timestamps: true });
expect(schema.add).to.be.calledTwice;
});
@@ -36,7 +36,7 @@ describe('Base model plugin', () => {
});
expect(schema.statics.sanitize).to.exist;
- let sanitized = schema.statics.sanitize({ok: true, noUpdateForMe: true});
+ const sanitized = schema.statics.sanitize({ ok: true, noUpdateForMe: true });
expect(sanitized).to.have.property('ok');
expect(sanitized).not.to.have.property('noUpdateForMe');
@@ -49,7 +49,7 @@ describe('Base model plugin', () => {
});
expect(schema.statics.sanitize).to.exist;
- let sanitized = schema.statics.sanitize({ok: true, noUpdateForMe: true, usuallySettable: true}, ['usuallySettable']);
+ const sanitized = schema.statics.sanitize({ ok: true, noUpdateForMe: true, usuallySettable: true }, ['usuallySettable']);
expect(sanitized).to.have.property('ok');
expect(sanitized).not.to.have.property('noUpdateForMe');
@@ -63,31 +63,31 @@ describe('Base model plugin', () => {
});
expect(schema.options.toJSON.transform).to.exist;
- let objToTransform = {ok: true, amPrivate: true};
- let privatized = schema.options.toJSON.transform({}, objToTransform);
+ const objToTransform = { ok: true, amPrivate: true };
+ const privatized = schema.options.toJSON.transform({}, objToTransform);
expect(privatized).to.have.property('ok');
expect(privatized).not.to.have.property('amPrivate');
});
it('accepts a further transform function for toJSON', () => {
- let options = {
+ const options = {
private: ['amPrivate'],
toJSONTransform: sandbox.stub().returns(true),
};
schema.plugin(baseModel, options);
- let objToTransform = {ok: true, amPrivate: true};
- let doc = {doc: true};
- let privatized = schema.options.toJSON.transform(doc, objToTransform);
+ const objToTransform = { ok: true, amPrivate: true };
+ const doc = { doc: true };
+ const privatized = schema.options.toJSON.transform(doc, objToTransform);
expect(privatized).to.equals(true);
expect(options.toJSONTransform).to.be.calledWith(objToTransform, doc);
});
it('accepts a transform function for sanitize', () => {
- let options = {
+ const options = {
private: ['amPrivate'],
sanitizeTransform: sandbox.stub().returns(true),
};
@@ -95,8 +95,8 @@ describe('Base model plugin', () => {
schema.plugin(baseModel, options);
expect(schema.options.toJSON.transform).to.exist;
- let objToSanitize = {ok: true, noUpdateForMe: true};
- let sanitized = schema.statics.sanitize(objToSanitize);
+ const objToSanitize = { ok: true, noUpdateForMe: true };
+ const sanitized = schema.statics.sanitize(objToSanitize);
expect(sanitized).to.equals(true);
expect(options.sanitizeTransform).to.be.calledWith(objToSanitize);
diff --git a/test/api/unit/libs/collectionManipulators.test.js b/test/api/unit/libs/collectionManipulators.test.js
index 3d4fb70d6d..3c524d3af7 100644
--- a/test/api/unit/libs/collectionManipulators.test.js
+++ b/test/api/unit/libs/collectionManipulators.test.js
@@ -6,7 +6,7 @@ import {
describe('Collection Manipulators', () => {
describe('removeFromArray', () => {
it('removes element from array', () => {
- let array = ['a', 'b', 'c', 'd'];
+ const array = ['a', 'b', 'c', 'd'];
removeFromArray(array, 'c');
@@ -14,7 +14,7 @@ describe('Collection Manipulators', () => {
});
it('removes object from array', () => {
- let array = [
+ const array = [
{ id: 'a', foo: 'bar' },
{ id: 'b', foo: 'bar' },
{ id: 'c', foo: 'bar' },
@@ -28,7 +28,7 @@ describe('Collection Manipulators', () => {
});
it('does not change array if value is not found', () => {
- let array = ['a', 'b', 'c', 'd'];
+ const array = ['a', 'b', 'c', 'd'];
removeFromArray(array, 'z');
@@ -40,15 +40,15 @@ describe('Collection Manipulators', () => {
});
it('returns the removed element', () => {
- let array = ['a', 'b', 'c'];
+ const array = ['a', 'b', 'c'];
- let result = removeFromArray(array, 'b');
+ const result = removeFromArray(array, 'b');
expect(result).to.eql('b');
});
it('returns the removed object element', () => {
- let array = [
+ const array = [
{ id: 'a', foo: 'bar' },
{ id: 'b', foo: 'bar' },
{ id: 'c', foo: 'bar' },
@@ -56,31 +56,31 @@ describe('Collection Manipulators', () => {
{ id: 'e', foo: 'bar' },
];
- let result = removeFromArray(array, { id: 'c' });
+ const result = removeFromArray(array, { id: 'c' });
expect(result).to.eql({ id: 'c', foo: 'bar' });
});
it('returns false if item is not found', () => {
- let array = ['a', 'b', 'c'];
+ const array = ['a', 'b', 'c'];
- let result = removeFromArray(array, 'z');
+ const result = removeFromArray(array, 'z');
expect(result).to.eql(false);
});
it('persists removal of element when mongoose document is saved', async () => {
- let schema = new mongoose.Schema({
+ const schema = new mongoose.Schema({
array: Array,
});
- let Model = mongoose.model('ModelToTestRemoveFromArray', schema);
- let model = await new Model({
+ const Model = mongoose.model('ModelToTestRemoveFromArray', schema);
+ const model = await new Model({
array: ['a', 'b', 'c'],
}).save(); // Initial creation
removeFromArray(model.array, 'b');
- let savedModel = await model.save();
+ const savedModel = await model.save();
expect(savedModel.array).to.not.include('b');
});
diff --git a/test/api/unit/libs/cron.test.js b/test/api/unit/libs/cron.test.js
index 30e6d6adb4..5f6c6c95d8 100644
--- a/test/api/unit/libs/cron.test.js
+++ b/test/api/unit/libs/cron.test.js
@@ -10,12 +10,14 @@ import * as analytics from '../../../../website/server/libs/analyticsService';
// const scoreTask = common.ops.scoreTask;
-let pathToCronLib = '../../../../website/server/libs/cron';
+const pathToCronLib = '../../../../website/server/libs/cron';
describe('cron', () => {
let clock = null;
let user;
- let tasksByType = {habits: [], dailys: [], todos: [], rewards: []};
+ const tasksByType = {
+ habits: [], dailys: [], todos: [], rewards: [],
+ };
let daysMissed = 0;
beforeEach(() => {
@@ -35,39 +37,48 @@ describe('cron', () => {
});
afterEach(() => {
- if (clock !== null)
- clock.restore();
+ if (clock !== null) clock.restore();
analytics.track.restore();
});
it('updates user.preferences.timezoneOffsetAtLastCron', () => {
- let timezoneOffsetFromUserPrefs = 1;
+ const timezoneOffsetFromUserPrefs = 1;
- cron({user, tasksByType, daysMissed, analytics, timezoneOffsetFromUserPrefs});
+ cron({
+ user, tasksByType, daysMissed, analytics, timezoneOffsetFromUserPrefs,
+ });
expect(user.preferences.timezoneOffsetAtLastCron).to.equal(timezoneOffsetFromUserPrefs);
});
it('resets user.items.lastDrop.count', () => {
user.items.lastDrop.count = 4;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.items.lastDrop.count).to.equal(0);
});
it('increments user cron count', () => {
- let cronCountBefore = user.flags.cronCount;
- cron({user, tasksByType, daysMissed, analytics});
+ const cronCountBefore = user.flags.cronCount;
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.flags.cronCount).to.be.greaterThan(cronCountBefore);
});
it('calls analytics', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(analytics.track.callCount).to.equal(1);
});
it('calls analytics when user is sleeping', () => {
user.preferences.sleep = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(analytics.track.callCount).to.equal(1);
});
@@ -79,14 +90,18 @@ describe('cron', () => {
it('resets plan.gemsBought on a new month', () => {
user.purchased.plan.gemsBought = 10;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.gemsBought).to.equal(0);
});
it('resets plan.gemsBought on a new month if user does not have purchased.plan.dateUpdated', () => {
user.purchased.plan.gemsBought = 10;
user.purchased.plan.dateUpdated = undefined;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.gemsBought).to.equal(0);
});
@@ -95,32 +110,42 @@ describe('cron', () => {
user.purchased.plan.dateUpdated = moment().startOf('month').toDate();
user.purchased.plan.gemsBought = 10;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.gemsBought).to.equal(10);
});
it('resets plan.dateUpdated on a new month', () => {
- let currentMonth = moment().startOf('month');
- cron({user, tasksByType, daysMissed, analytics});
+ const currentMonth = moment().startOf('month');
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(moment(user.purchased.plan.dateUpdated).startOf('month').isSame(currentMonth)).to.eql(true);
});
it('increments plan.consecutive.count', () => {
user.purchased.plan.consecutive.count = 0;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.count).to.equal(1);
});
it('increments plan.consecutive.count by more than 1 if user skipped months between logins', () => {
user.purchased.plan.dateUpdated = moment().subtract(2, 'months').toDate();
user.purchased.plan.consecutive.count = 0;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.count).to.equal(2);
});
it('decrements plan.consecutive.offset when offset is greater than 0', () => {
user.purchased.plan.consecutive.offset = 2;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.offset).to.equal(1);
});
@@ -130,7 +155,9 @@ describe('cron', () => {
user.purchased.plan.consecutive.count = 5;
user.purchased.plan.consecutive.trinkets = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.trinkets).to.equal(1);
});
@@ -138,23 +165,29 @@ describe('cron', () => {
it('does not increment plan.consecutive.gemCapExtra when user has reached the gemCap limit', () => {
user.purchased.plan.consecutive.gemCapExtra = 25;
user.purchased.plan.consecutive.count = 5;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.gemCapExtra).to.equal(25);
});
it('does not reset plan stats if we are before the last day of the cancelled month', () => {
- user.purchased.plan.dateTerminated = moment(new Date()).add({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ user.purchased.plan.dateTerminated = moment(new Date()).add({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.customerId).to.exist;
});
it('does reset plan stats if we are after the last day of the cancelled month', () => {
- user.purchased.plan.dateTerminated = moment(new Date()).subtract({days: 1});
+ user.purchased.plan.dateTerminated = moment(new Date()).subtract({ days: 1 });
user.purchased.plan.consecutive.gemCapExtra = 20;
user.purchased.plan.consecutive.count = 5;
user.purchased.plan.consecutive.offset = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.customerId).to.not.exist;
expect(user.purchased.plan.consecutive.gemCapExtra).to.equal(0);
@@ -164,7 +197,7 @@ describe('cron', () => {
describe('for a 1-month recurring subscription', () => {
// create a user that will be used for all of these tests without a reset before each
- let user1 = new User({
+ const user1 = new User({
auth: {
local: {
username: 'username1',
@@ -185,10 +218,15 @@ describe('cron', () => {
user1.purchased.plan.consecutive.gemCapExtra = 0;
it('does not increment consecutive benefits after the first month', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
// Add 1 month to simulate what happens a month after the subscription was created.
- // Add 2 days so that we're sure we're not affected by any start-of-month effects e.g., from time zone oddness.
- cron({user: user1, tasksByType, daysMissed, analytics});
+ // Add 2 days so that we're sure we're not affected by any start-of-month effects
+ // e.g., from time zone oddness.
+ cron({
+ user: user1, tasksByType, daysMissed, analytics,
+ });
expect(user1.purchased.plan.consecutive.count).to.equal(1);
expect(user1.purchased.plan.consecutive.offset).to.equal(0);
expect(user1.purchased.plan.consecutive.trinkets).to.equal(0);
@@ -196,10 +234,15 @@ describe('cron', () => {
});
it('does not increment consecutive benefits after the second month', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months').add(2, 'days').toDate());
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months')
+ .add(2, 'days')
+ .toDate());
// Add 1 month to simulate what happens a month after the subscription was created.
- // Add 2 days so that we're sure we're not affected by any start-of-month effects e.g., from time zone oddness.
- cron({user: user1, tasksByType, daysMissed, analytics});
+ // Add 2 days so that we're sure we're not affected by any start-of-month effects
+ // e.g., from time zone oddness.
+ cron({
+ user: user1, tasksByType, daysMissed, analytics,
+ });
expect(user1.purchased.plan.consecutive.count).to.equal(2);
expect(user1.purchased.plan.consecutive.offset).to.equal(0);
expect(user1.purchased.plan.consecutive.trinkets).to.equal(0);
@@ -207,10 +250,15 @@ describe('cron', () => {
});
it('increments consecutive benefits after the third month', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months').add(2, 'days').toDate());
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months')
+ .add(2, 'days')
+ .toDate());
// Add 1 month to simulate what happens a month after the subscription was created.
- // Add 2 days so that we're sure we're not affected by any start-of-month effects e.g., from time zone oddness.
- cron({user: user1, tasksByType, daysMissed, analytics});
+ // Add 2 days so that we're sure we're not affected by any start-of-month effects
+ // e.g., from time zone oddness.
+ cron({
+ user: user1, tasksByType, daysMissed, analytics,
+ });
expect(user1.purchased.plan.consecutive.count).to.equal(3);
expect(user1.purchased.plan.consecutive.offset).to.equal(0);
expect(user1.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -218,10 +266,15 @@ describe('cron', () => {
});
it('does not increment consecutive benefits after the fourth month', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months').add(2, 'days').toDate());
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months')
+ .add(2, 'days')
+ .toDate());
// Add 1 month to simulate what happens a month after the subscription was created.
- // Add 2 days so that we're sure we're not affected by any start-of-month effects e.g., from time zone oddness.
- cron({user: user1, tasksByType, daysMissed, analytics});
+ // Add 2 days so that we're sure we're not affected by any start-of-month effects
+ // e.g., from time zone oddness.
+ cron({
+ user: user1, tasksByType, daysMissed, analytics,
+ });
expect(user1.purchased.plan.consecutive.count).to.equal(4);
expect(user1.purchased.plan.consecutive.offset).to.equal(0);
expect(user1.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -229,8 +282,12 @@ describe('cron', () => {
});
it('increments consecutive benefits correctly if user has been absent with continuous subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(10, 'months').add(2, 'days').toDate());
- cron({user: user1, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(10, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user1, tasksByType, daysMissed, analytics,
+ });
expect(user1.purchased.plan.consecutive.count).to.equal(10);
expect(user1.purchased.plan.consecutive.offset).to.equal(0);
expect(user1.purchased.plan.consecutive.trinkets).to.equal(3);
@@ -239,7 +296,7 @@ describe('cron', () => {
});
describe('for a 3-month recurring subscription', () => {
- let user3 = new User({
+ const user3 = new User({
auth: {
local: {
username: 'username3',
@@ -260,8 +317,12 @@ describe('cron', () => {
user3.purchased.plan.consecutive.gemCapExtra = 5;
it('does not increment consecutive benefits in the first month of the first paid period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(1);
expect(user3.purchased.plan.consecutive.offset).to.equal(2);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -269,8 +330,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the middle of the period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(2);
expect(user3.purchased.plan.consecutive.offset).to.equal(1);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -278,8 +343,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the final month of the period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(3);
expect(user3.purchased.plan.consecutive.offset).to.equal(0);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -287,8 +356,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the second paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(4);
expect(user3.purchased.plan.consecutive.offset).to.equal(2);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(2);
@@ -296,8 +369,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the second month of the second period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(5, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(5, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(5);
expect(user3.purchased.plan.consecutive.offset).to.equal(1);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(2);
@@ -305,8 +382,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the final month of the second period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(6, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(6, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(6);
expect(user3.purchased.plan.consecutive.offset).to.equal(0);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(2);
@@ -314,8 +395,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the third paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(7);
expect(user3.purchased.plan.consecutive.offset).to.equal(2);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(3);
@@ -323,8 +408,12 @@ describe('cron', () => {
});
it('increments consecutive benefits correctly if user has been absent with continuous subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(10, 'months').add(2, 'days').toDate());
- cron({user: user3, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(10, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3, tasksByType, daysMissed, analytics,
+ });
expect(user3.purchased.plan.consecutive.count).to.equal(10);
expect(user3.purchased.plan.consecutive.offset).to.equal(2);
expect(user3.purchased.plan.consecutive.trinkets).to.equal(4);
@@ -333,7 +422,7 @@ describe('cron', () => {
});
describe('for a 6-month recurring subscription', () => {
- let user6 = new User({
+ const user6 = new User({
auth: {
local: {
username: 'username6',
@@ -354,8 +443,12 @@ describe('cron', () => {
user6.purchased.plan.consecutive.gemCapExtra = 10;
it('does not increment consecutive benefits in the first month of the first paid period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
- cron({user: user6, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6, tasksByType, daysMissed, analytics,
+ });
expect(user6.purchased.plan.consecutive.count).to.equal(1);
expect(user6.purchased.plan.consecutive.offset).to.equal(5);
expect(user6.purchased.plan.consecutive.trinkets).to.equal(2);
@@ -363,8 +456,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the final month of the period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(6, 'months').add(2, 'days').toDate());
- cron({user: user6, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(6, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6, tasksByType, daysMissed, analytics,
+ });
expect(user6.purchased.plan.consecutive.count).to.equal(6);
expect(user6.purchased.plan.consecutive.offset).to.equal(0);
expect(user6.purchased.plan.consecutive.trinkets).to.equal(2);
@@ -372,8 +469,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the second paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months').add(2, 'days').toDate());
- cron({user: user6, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6, tasksByType, daysMissed, analytics,
+ });
expect(user6.purchased.plan.consecutive.count).to.equal(7);
expect(user6.purchased.plan.consecutive.offset).to.equal(5);
expect(user6.purchased.plan.consecutive.trinkets).to.equal(4);
@@ -381,8 +482,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the third paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(13, 'months').add(2, 'days').toDate());
- cron({user: user6, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(13, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6, tasksByType, daysMissed, analytics,
+ });
expect(user6.purchased.plan.consecutive.count).to.equal(13);
expect(user6.purchased.plan.consecutive.offset).to.equal(5);
expect(user6.purchased.plan.consecutive.trinkets).to.equal(6);
@@ -390,8 +495,12 @@ describe('cron', () => {
});
it('increments consecutive benefits correctly if user has been absent with continuous subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(19, 'months').add(2, 'days').toDate());
- cron({user: user6, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(19, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6, tasksByType, daysMissed, analytics,
+ });
expect(user6.purchased.plan.consecutive.count).to.equal(19);
expect(user6.purchased.plan.consecutive.offset).to.equal(5);
expect(user6.purchased.plan.consecutive.trinkets).to.equal(8);
@@ -400,7 +509,7 @@ describe('cron', () => {
});
describe('for a 12-month recurring subscription', () => {
- let user12 = new User({
+ const user12 = new User({
auth: {
local: {
username: 'username12',
@@ -421,8 +530,12 @@ describe('cron', () => {
user12.purchased.plan.consecutive.gemCapExtra = 20;
it('does not increment consecutive benefits in the first month of the first paid period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
- cron({user: user12, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user12, tasksByType, daysMissed, analytics,
+ });
expect(user12.purchased.plan.consecutive.count).to.equal(1);
expect(user12.purchased.plan.consecutive.offset).to.equal(11);
expect(user12.purchased.plan.consecutive.trinkets).to.equal(4);
@@ -430,8 +543,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the final month of the period that they already have benefits for', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(12, 'months').add(2, 'days').toDate());
- cron({user: user12, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(12, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user12, tasksByType, daysMissed, analytics,
+ });
expect(user12.purchased.plan.consecutive.count).to.equal(12);
expect(user12.purchased.plan.consecutive.offset).to.equal(0);
expect(user12.purchased.plan.consecutive.trinkets).to.equal(4);
@@ -439,8 +556,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the second paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(13, 'months').add(2, 'days').toDate());
- cron({user: user12, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(13, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user12, tasksByType, daysMissed, analytics,
+ });
expect(user12.purchased.plan.consecutive.count).to.equal(13);
expect(user12.purchased.plan.consecutive.offset).to.equal(11);
expect(user12.purchased.plan.consecutive.trinkets).to.equal(8);
@@ -448,8 +569,12 @@ describe('cron', () => {
});
it('increments consecutive benefits the month after the third paid period has started', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(25, 'months').add(2, 'days').toDate());
- cron({user: user12, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(25, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user12, tasksByType, daysMissed, analytics,
+ });
expect(user12.purchased.plan.consecutive.count).to.equal(25);
expect(user12.purchased.plan.consecutive.offset).to.equal(11);
expect(user12.purchased.plan.consecutive.trinkets).to.equal(12);
@@ -457,8 +582,12 @@ describe('cron', () => {
});
it('increments consecutive benefits correctly if user has been absent with continuous subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(37, 'months').add(2, 'days').toDate());
- cron({user: user12, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(37, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user12, tasksByType, daysMissed, analytics,
+ });
expect(user12.purchased.plan.consecutive.count).to.equal(37);
expect(user12.purchased.plan.consecutive.offset).to.equal(11);
expect(user12.purchased.plan.consecutive.trinkets).to.equal(16);
@@ -467,7 +596,7 @@ describe('cron', () => {
});
describe('for a 3-month gift subscription (non-recurring)', () => {
- let user3g = new User({
+ const user3g = new User({
auth: {
local: {
username: 'username3g',
@@ -481,7 +610,8 @@ describe('cron', () => {
// user3g has a 3-month gift subscription starting today
user3g.purchased.plan.customerId = 'Gift';
user3g.purchased.plan.dateUpdated = moment().toDate();
- user3g.purchased.plan.dateTerminated = moment().startOf('month').add(3, 'months').add(15, 'days').toDate();
+ user3g.purchased.plan.dateTerminated = moment().startOf('month').add(3, 'months').add(15, 'days')
+ .toDate();
user3g.purchased.plan.planId = null;
user3g.purchased.plan.consecutive.count = 0;
user3g.purchased.plan.consecutive.offset = 3;
@@ -489,8 +619,12 @@ describe('cron', () => {
user3g.purchased.plan.consecutive.gemCapExtra = 5;
it('does not increment consecutive benefits in the first month of the gift subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
- cron({user: user3g, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3g, tasksByType, daysMissed, analytics,
+ });
expect(user3g.purchased.plan.consecutive.count).to.equal(1);
expect(user3g.purchased.plan.consecutive.offset).to.equal(2);
expect(user3g.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -498,8 +632,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the second month of the gift subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months').add(2, 'days').toDate());
- cron({user: user3g, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3g, tasksByType, daysMissed, analytics,
+ });
expect(user3g.purchased.plan.consecutive.count).to.equal(2);
expect(user3g.purchased.plan.consecutive.offset).to.equal(1);
expect(user3g.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -507,8 +645,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the third month of the gift subscription', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months').add(2, 'days').toDate());
- cron({user: user3g, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3g, tasksByType, daysMissed, analytics,
+ });
expect(user3g.purchased.plan.consecutive.count).to.equal(3);
expect(user3g.purchased.plan.consecutive.offset).to.equal(0);
expect(user3g.purchased.plan.consecutive.trinkets).to.equal(1);
@@ -516,9 +658,14 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the month after the gift subscription has ended', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months').add(2, 'days').toDate());
- cron({user: user3g, tasksByType, daysMissed, analytics});
- expect(user3g.purchased.plan.consecutive.count).to.equal(0); // subscription has been erased by now
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(4, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user3g, tasksByType, daysMissed, analytics,
+ });
+ // subscription has been erased by now
+ expect(user3g.purchased.plan.consecutive.count).to.equal(0);
expect(user3g.purchased.plan.consecutive.offset).to.equal(0);
expect(user3g.purchased.plan.consecutive.trinkets).to.equal(1);
expect(user3g.purchased.plan.consecutive.gemCapExtra).to.equal(0); // erased
@@ -526,7 +673,7 @@ describe('cron', () => {
});
describe('for a 6-month recurring subscription where the user has incorrect consecutive month data from prior bugs', () => {
- let user6x = new User({
+ const user6x = new User({
auth: {
local: {
username: 'username6x',
@@ -537,7 +684,8 @@ describe('cron', () => {
},
},
});
- // user6x has a 6-month recurring subscription starting 8 months in the past before issue #4819 was fixed
+ // user6x has a 6-month recurring subscription starting 8 months in the past
+ // before issue #4819 was fixed
user6x.purchased.plan.customerId = 'subscribedId';
user6x.purchased.plan.dateUpdated = moment().toDate();
user6x.purchased.plan.planId = 'basic_6mo';
@@ -547,8 +695,12 @@ describe('cron', () => {
user6x.purchased.plan.consecutive.gemCapExtra = 15;
it('increments consecutive benefits in the first month since the fix for #4819 goes live', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months').add(2, 'days').toDate());
- cron({user: user6x, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(1, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6x, tasksByType, daysMissed, analytics,
+ });
expect(user6x.purchased.plan.consecutive.count).to.equal(9);
expect(user6x.purchased.plan.consecutive.offset).to.equal(5);
expect(user6x.purchased.plan.consecutive.trinkets).to.equal(5);
@@ -556,8 +708,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the second month after the fix goes live', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months').add(2, 'days').toDate());
- cron({user: user6x, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(2, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6x, tasksByType, daysMissed, analytics,
+ });
expect(user6x.purchased.plan.consecutive.count).to.equal(10);
expect(user6x.purchased.plan.consecutive.offset).to.equal(4);
expect(user6x.purchased.plan.consecutive.trinkets).to.equal(5);
@@ -565,8 +721,12 @@ describe('cron', () => {
});
it('does not increment consecutive benefits in the third month after the fix goes live', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months').add(2, 'days').toDate());
- cron({user: user6x, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(3, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6x, tasksByType, daysMissed, analytics,
+ });
expect(user6x.purchased.plan.consecutive.count).to.equal(11);
expect(user6x.purchased.plan.consecutive.offset).to.equal(3);
expect(user6x.purchased.plan.consecutive.trinkets).to.equal(5);
@@ -574,8 +734,12 @@ describe('cron', () => {
});
it('increments consecutive benefits in the seventh month after the fix goes live', () => {
- clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months').add(2, 'days').toDate());
- cron({user: user6x, tasksByType, daysMissed, analytics});
+ clock = sinon.useFakeTimers(moment().zone(0).startOf('month').add(7, 'months')
+ .add(2, 'days')
+ .toDate());
+ cron({
+ user: user6x, tasksByType, daysMissed, analytics,
+ });
expect(user6x.purchased.plan.consecutive.count).to.equal(15);
expect(user6x.purchased.plan.consecutive.offset).to.equal(5);
expect(user6x.purchased.plan.consecutive.trinkets).to.equal(7);
@@ -591,7 +755,9 @@ describe('cron', () => {
it('resets plan.gemsBought on a new month', () => {
user.purchased.plan.gemsBought = 10;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.gemsBought).to.equal(0);
});
@@ -600,59 +766,77 @@ describe('cron', () => {
user.purchased.plan.dateUpdated = moment().startOf('month').toDate();
user.purchased.plan.gemsBought = 10;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.gemsBought).to.equal(10);
});
it('does not reset plan.dateUpdated on a new month', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.dateUpdated).to.be.empty;
});
it('does not increment plan.consecutive.count', () => {
user.purchased.plan.consecutive.count = 0;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.count).to.equal(0);
});
it('does not decrement plan.consecutive.offset when offset is greater than 0', () => {
user.purchased.plan.consecutive.offset = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.offset).to.equal(1);
});
it('does not increment plan.consecutive.trinkets when user has reached a month that is a multiple of 3', () => {
user.purchased.plan.consecutive.count = 5;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.trinkets).to.equal(0);
});
it('does not increment plan.consecutive.gemCapExtra when user has reached a month that is a multiple of 3', () => {
user.purchased.plan.consecutive.count = 5;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.gemCapExtra).to.equal(0);
});
it('does not increment plan.consecutive.gemCapExtra when user has reached the gemCap limit', () => {
user.purchased.plan.consecutive.gemCapExtra = 25;
user.purchased.plan.consecutive.count = 5;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.consecutive.gemCapExtra).to.equal(25);
});
it('does nothing to plan stats if we are before the last day of the cancelled month', () => {
- user.purchased.plan.dateTerminated = moment(new Date()).add({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ user.purchased.plan.dateTerminated = moment(new Date()).add({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.customerId).to.not.exist;
});
xit('does nothing to plan stats when we are after the last day of the cancelled month', () => {
- user.purchased.plan.dateTerminated = moment(new Date()).subtract({days: 1});
+ user.purchased.plan.dateTerminated = moment(new Date()).subtract({ days: 1 });
user.purchased.plan.consecutive.gemCapExtra = 20;
user.purchased.plan.consecutive.count = 5;
user.purchased.plan.consecutive.offset = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.purchased.plan.customerId).to.exist;
expect(user.purchased.plan.consecutive.gemCapExtra).to.exist;
@@ -663,26 +847,30 @@ describe('cron', () => {
describe('todos', () => {
beforeEach(() => {
- let todo = {
+ const todo = {
text: 'test todo',
type: 'todo',
value: 0,
};
- let task = new Tasks.todo(Tasks.Task.sanitize(todo)); // eslint-disable-line new-cap
+ const task = new Tasks.todo(Tasks.Task.sanitize(todo)); // eslint-disable-line new-cap
tasksByType.todos.push(task);
});
it('should make uncompleted todos redder', () => {
- let valueBefore = tasksByType.todos[0].value;
- cron({user, tasksByType, daysMissed, analytics});
+ const valueBefore = tasksByType.todos[0].value;
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.todos[0].value).to.be.lessThan(valueBefore);
});
it('should add history of completed todos to user history', () => {
tasksByType.todos[0].completed = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.history.todos).to.be.lengthOf(1);
});
@@ -690,7 +878,7 @@ describe('cron', () => {
it('should remove completed todos from users taskOrder list', () => {
tasksByType.todos = [];
user.tasksOrder.todos = [];
- let todo = {
+ const todo = {
text: 'test todo',
type: 'todo',
value: 0,
@@ -702,16 +890,17 @@ describe('cron', () => {
tasksByType.todos.push(task);
tasksByType.todos[0].completed = true;
- user.tasksOrder.todos = tasksByType.todos.map(taskTodo => {
- return taskTodo._id;
- });
- // Since ideally tasksByType should not contain completed todos, fake ids should be filtered too
+ user.tasksOrder.todos = tasksByType.todos.map(taskTodo => taskTodo._id);
+ // Since ideally tasksByType should not contain completed todos,
+ // fake ids should be filtered too
user.tasksOrder.todos.push('00000000-0000-0000-0000-000000000000');
expect(tasksByType.todos).to.be.lengthOf(2);
expect(user.tasksOrder.todos).to.be.lengthOf(3);
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
// user.tasksOrder.todos should be filtered while tasks by type remains unchanged
expect(tasksByType.todos).to.be.lengthOf(2);
@@ -721,7 +910,7 @@ describe('cron', () => {
it('should preserve todos order in task list', () => {
tasksByType.todos = [];
user.tasksOrder.todos = [];
- let todo = {
+ const todo = {
text: 'test todo',
type: 'todo',
value: 0,
@@ -735,12 +924,12 @@ describe('cron', () => {
tasksByType.todos.push(task);
// Set up user.tasksOrder list in a specific order
- user.tasksOrder.todos = tasksByType.todos.map(todoTask => {
- return todoTask._id;
- }).reverse();
- let original = user.tasksOrder.todos; // Preserve the original order
+ user.tasksOrder.todos = tasksByType.todos.map(todoTask => todoTask._id).reverse();
+ const original = user.tasksOrder.todos; // Preserve the original order
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
let listsAreEqual = true;
user.tasksOrder.todos.forEach((taskId, index) => {
@@ -756,18 +945,18 @@ describe('cron', () => {
describe('dailys', () => {
beforeEach(() => {
- let daily = {
+ const daily = {
text: 'test daily',
type: 'daily',
};
- let task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
+ const task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
tasksByType.dailys = [];
tasksByType.dailys.push(task);
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {con: 1}));
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { con: 1 }));
});
afterEach(() => {
@@ -778,7 +967,9 @@ describe('cron', () => {
tasksByType.dailys[0].frequency = 'daily';
tasksByType.dailys[0].everyX = 5;
tasksByType.dailys[0].startDate = moment().add(1, 'days').toDate();
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].isDue).to.be.false;
});
@@ -787,7 +978,9 @@ describe('cron', () => {
tasksByType.dailys[0].frequency = 'daily';
tasksByType.dailys[0].everyX = 5;
tasksByType.dailys[0].startDate = moment().toDate();
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].isDue).to.exist;
});
@@ -795,88 +988,110 @@ describe('cron', () => {
tasksByType.dailys[0].frequency = 'daily';
tasksByType.dailys[0].everyX = 5;
tasksByType.dailys[0].startDate = moment().add(1, 'days').toDate();
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].nextDue.length).to.eql(6);
});
it('should add history', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].history).to.be.lengthOf(1);
});
it('should set tasks completed to false', () => {
tasksByType.dailys[0].completed = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].completed).to.be.false;
});
it('should set tasks completed to false when user is sleeping', () => {
user.preferences.sleep = true;
tasksByType.dailys[0].completed = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].completed).to.be.false;
});
it('should reset task checklist for completed dailys', () => {
- tasksByType.dailys[0].checklist.push({title: 'test', completed: false});
+ tasksByType.dailys[0].checklist.push({ title: 'test', completed: false });
tasksByType.dailys[0].completed = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].checklist[0].completed).to.be.false;
});
it('should reset task checklist for completed dailys when user is sleeping', () => {
user.preferences.sleep = true;
- tasksByType.dailys[0].checklist.push({title: 'test', completed: false});
+ tasksByType.dailys[0].checklist.push({ title: 'test', completed: false });
tasksByType.dailys[0].completed = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].checklist[0].completed).to.be.false;
});
it('should reset task checklist for dailys with scheduled misses', () => {
daysMissed = 10;
- tasksByType.dailys[0].checklist.push({title: 'test', completed: false});
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ tasksByType.dailys[0].checklist.push({ title: 'test', completed: false });
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.dailys[0].checklist[0].completed).to.be.false;
});
it('should do damage for missing a daily', () => {
daysMissed = 1;
- let hpBefore = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ const hpBefore = user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.hp).to.be.lessThan(hpBefore);
});
it('should not do damage for missing a daily when user is sleeping', () => {
user.preferences.sleep = true;
daysMissed = 1;
- let hpBefore = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ const hpBefore = user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.hp).to.equal(hpBefore);
});
it('should not do damage for missing a daily when CRON_SAFE_MODE is set', () => {
sandbox.stub(nconf, 'get').withArgs('CRON_SAFE_MODE').returns('true');
- let cronOverride = requireAgain(pathToCronLib).cron;
+ const cronOverride = requireAgain(pathToCronLib).cron;
daysMissed = 1;
- let hpBefore = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ const hpBefore = user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- cronOverride({user, tasksByType, daysMissed, analytics});
+ cronOverride({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.hp).to.equal(hpBefore);
});
it('should not do damage for missing a daily if user stealth buff is greater than or equal to days missed', () => {
daysMissed = 1;
- let hpBefore = user.stats.hp;
+ const hpBefore = user.stats.hp;
user.stats.buffs.stealth = 2;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.hp).to.equal(hpBefore);
});
@@ -884,24 +1099,31 @@ describe('cron', () => {
it('should do less damage for missing a daily with partial completion', () => {
daysMissed = 1;
let hpBefore = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
- let hpDifferenceOfFullyIncompleteDaily = hpBefore - user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
+ const hpDifferenceOfFullyIncompleteDaily = hpBefore - user.stats.hp;
hpBefore = user.stats.hp;
- tasksByType.dailys[0].checklist.push({title: 'test', completed: true});
- tasksByType.dailys[0].checklist.push({title: 'test2', completed: false});
- cron({user, tasksByType, daysMissed, analytics});
- let hpDifferenceOfPartiallyIncompleteDaily = hpBefore - user.stats.hp;
+ tasksByType.dailys[0].checklist.push({ title: 'test', completed: true });
+ tasksByType.dailys[0].checklist.push({ title: 'test2', completed: false });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
+ const hpDifferenceOfPartiallyIncompleteDaily = hpBefore - user.stats.hp;
- expect(hpDifferenceOfPartiallyIncompleteDaily).to.be.lessThan(hpDifferenceOfFullyIncompleteDaily);
+ expect(hpDifferenceOfPartiallyIncompleteDaily)
+ .to.be.lessThan(hpDifferenceOfFullyIncompleteDaily);
});
it('should decrement quest.progress.down for missing a daily', () => {
daysMissed = 1;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let progress = cron({user, tasksByType, daysMissed, analytics});
+ const progress = cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(progress.down).to.equal(-1);
});
@@ -909,28 +1131,32 @@ describe('cron', () => {
it('should not decrement quest.progress.down for missing a daily when user is sleeping', () => {
user.preferences.sleep = true;
daysMissed = 1;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let progress = cron({user, tasksByType, daysMissed, analytics});
+ const progress = cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(progress.down).to.equal(0);
});
it('should do damage for only yesterday\'s dailies', () => {
daysMissed = 3;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let daily = {
+ const daily = {
text: 'test daily',
type: 'daily',
};
- let task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
+ const task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
tasksByType.dailys.push(task);
- tasksByType.dailys[1].startDate = moment(new Date()).subtract({days: 2});
+ tasksByType.dailys[1].startDate = moment(new Date()).subtract({ days: 2 });
tasksByType.dailys[1].everyX = 2;
tasksByType.dailys[1].frequency = 'daily';
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.hp).to.equal(48);
});
@@ -938,12 +1164,12 @@ describe('cron', () => {
describe('habits', () => {
beforeEach(() => {
- let habit = {
+ const habit = {
text: 'test habit',
type: 'habit',
};
- let task = new Tasks.habit(Tasks.Task.sanitize(habit)); // eslint-disable-line new-cap
+ const task = new Tasks.habit(Tasks.Task.sanitize(habit)); // eslint-disable-line new-cap
tasksByType.habits = [];
tasksByType.habits.push(task);
});
@@ -952,7 +1178,9 @@ describe('cron', () => {
tasksByType.habits[0].value = 1;
tasksByType.habits[0].down = false;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].value).to.be.lessThan(1);
});
@@ -961,7 +1189,9 @@ describe('cron', () => {
tasksByType.habits[0].value = 1;
tasksByType.habits[0].up = false;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].value).to.be.lessThan(1);
});
@@ -971,13 +1201,15 @@ describe('cron', () => {
tasksByType.habits[0].up = true;
tasksByType.habits[0].down = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].value).to.equal(1);
});
describe('counters', () => {
- let notStartOfWeekOrMonth = new Date(2016, 9, 28).getTime(); // a Friday
+ const notStartOfWeekOrMonth = new Date(2016, 9, 28).getTime(); // a Friday
beforeEach(() => {
// Replace system clocks so we can get predictable results
@@ -988,7 +1220,9 @@ describe('cron', () => {
tasksByType.habits[0].counterUp = 1;
tasksByType.habits[0].counterDown = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -999,7 +1233,9 @@ describe('cron', () => {
tasksByType.habits[0].counterUp = 1;
tasksByType.habits[0].counterDown = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1011,14 +1247,18 @@ describe('cron', () => {
tasksByType.habits[0].counterDown = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
// should reset
daysMissed = 8;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1040,7 +1280,9 @@ describe('cron', () => {
daysMissed = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
@@ -1052,7 +1294,9 @@ describe('cron', () => {
clock = sinon.useFakeTimers(monday);
// should reset after user CDS
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1062,7 +1306,7 @@ describe('cron', () => {
clock.restore();
// Server clock: Monday 11pm UTC
- let monday = new Date('May 22, 2017 23:00:00 GMT').getTime();
+ const monday = new Date('May 22, 2017 23:00:00 GMT').getTime();
clock = sinon.useFakeTimers(monday);
// User clock: Tuesday 1am UTC + 2
@@ -1074,7 +1318,9 @@ describe('cron', () => {
daysMissed = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
@@ -1082,7 +1328,9 @@ describe('cron', () => {
// User missed one cron, which will subtract User clock back to Monday 1am UTC + 2
// should reset
daysMissed = 2;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1092,7 +1340,7 @@ describe('cron', () => {
clock.restore();
// Server clock: Sunday 11pm UTC
- let sunday = new Date('May 21, 2017 23:00:00 GMT').getTime();
+ const sunday = new Date('May 21, 2017 23:00:00 GMT').getTime();
clock = sinon.useFakeTimers(sunday);
// User clock: Monday 2am UTC + 3
@@ -1104,7 +1352,9 @@ describe('cron', () => {
daysMissed = 1;
// should reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1114,7 +1364,7 @@ describe('cron', () => {
clock.restore();
// Server clock: Monday 2am UTC
- let monday = new Date('May 22, 2017 02:00:00 GMT').getTime();
+ const monday = new Date('May 22, 2017 02:00:00 GMT').getTime();
clock = sinon.useFakeTimers(monday);
// User clock: Sunday 11pm UTC - 3
@@ -1126,7 +1376,9 @@ describe('cron', () => {
daysMissed = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
@@ -1138,14 +1390,18 @@ describe('cron', () => {
tasksByType.habits[0].counterDown = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
// should reset
daysMissed = 32;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1156,7 +1412,7 @@ describe('cron', () => {
daysMissed = 0;
// Server clock: 4/30/17 11pm UTC
- let monday = new Date('April 30, 2017 23:00:00 GMT').getTime();
+ const monday = new Date('April 30, 2017 23:00:00 GMT').getTime();
clock = sinon.useFakeTimers(monday);
// User clock: 5/1/17 2am UTC + 3
@@ -1168,7 +1424,9 @@ describe('cron', () => {
daysMissed = 1;
// should reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1178,7 +1436,7 @@ describe('cron', () => {
clock.restore();
// Server clock: 5/1/17 11pm UTC
- let monday = new Date('May 1, 2017 23:00:00 GMT').getTime();
+ const monday = new Date('May 1, 2017 23:00:00 GMT').getTime();
clock = sinon.useFakeTimers(monday);
// User clock: 5/2/17 2am UTC + 3
@@ -1190,7 +1448,9 @@ describe('cron', () => {
daysMissed = 1;
// should not reset
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(1);
expect(tasksByType.habits[0].counterDown).to.equal(1);
@@ -1198,7 +1458,9 @@ describe('cron', () => {
// User missed one day, which will subtract User clock back to 5/1/17 2am UTC + 3
// should reset
daysMissed = 2;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(tasksByType.habits[0].counterUp).to.equal(0);
expect(tasksByType.habits[0].counterDown).to.equal(0);
@@ -1208,18 +1470,18 @@ describe('cron', () => {
describe('perfect day', () => {
beforeEach(() => {
- let daily = {
+ const daily = {
text: 'test daily',
type: 'daily',
};
- let task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
+ const task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
tasksByType.dailys = [];
tasksByType.dailys.push(task);
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {con: 1}));
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { con: 1 }));
});
afterEach(() => {
@@ -1229,7 +1491,9 @@ describe('cron', () => {
it('stores a new entry in user.history.exp', () => {
user.stats.lvl = 2;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.history.exp).to.have.lengthOf(1);
expect(user.history.exp[0].value).to.equal(25);
@@ -1238,9 +1502,11 @@ describe('cron', () => {
it('increments perfect day achievement if all (at least 1) due dailies were completed', () => {
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.achievements.perfect).to.equal(1);
});
@@ -1248,9 +1514,11 @@ describe('cron', () => {
it('does not increment perfect day achievement if no due dailies', () => {
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).add({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).add({ days: 1 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.achievements.perfect).to.equal(0);
});
@@ -1258,11 +1526,13 @@ describe('cron', () => {
it('gives perfect day buff if all (at least 1) due dailies were completed', () => {
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let previousBuffs = user.stats.buffs.toObject();
+ const previousBuffs = user.stats.buffs.toObject();
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.be.greaterThan(previousBuffs.str);
expect(user.stats.buffs.int).to.be.greaterThan(previousBuffs.int);
@@ -1274,11 +1544,13 @@ describe('cron', () => {
user.preferences.sleep = true;
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let previousBuffs = user.stats.buffs.toObject();
+ const previousBuffs = user.stats.buffs.toObject();
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.be.greaterThan(previousBuffs.str);
expect(user.stats.buffs.int).to.be.greaterThan(previousBuffs.int);
@@ -1289,7 +1561,7 @@ describe('cron', () => {
it('clears buffs if user does not have a perfect day (no due dailys)', () => {
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).add({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).add({ days: 1 });
user.stats.buffs = {
str: 1,
@@ -1300,7 +1572,9 @@ describe('cron', () => {
streaks: true,
};
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.equal(0);
expect(user.stats.buffs.int).to.equal(0);
@@ -1314,7 +1588,7 @@ describe('cron', () => {
user.preferences.sleep = true;
daysMissed = 1;
tasksByType.dailys[0].completed = true;
- tasksByType.dailys[0].startDate = moment(new Date()).add({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).add({ days: 1 });
user.stats.buffs = {
str: 1,
@@ -1325,7 +1599,9 @@ describe('cron', () => {
streaks: true,
};
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.equal(0);
expect(user.stats.buffs.int).to.equal(0);
@@ -1338,7 +1614,7 @@ describe('cron', () => {
it('clears buffs if user does not have a perfect day (at least one due daily not completed)', () => {
daysMissed = 1;
tasksByType.dailys[0].completed = false;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
user.stats.buffs = {
str: 1,
@@ -1349,7 +1625,9 @@ describe('cron', () => {
streaks: true,
};
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.equal(0);
expect(user.stats.buffs.int).to.equal(0);
@@ -1363,7 +1641,7 @@ describe('cron', () => {
user.preferences.sleep = true;
daysMissed = 1;
tasksByType.dailys[0].completed = false;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
user.stats.buffs = {
str: 1,
@@ -1374,7 +1652,9 @@ describe('cron', () => {
streaks: true,
};
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.equal(0);
expect(user.stats.buffs.int).to.equal(0);
@@ -1386,14 +1666,16 @@ describe('cron', () => {
it('always grants a perfect day buff when CRON_SAFE_MODE is set', () => {
sandbox.stub(nconf, 'get').withArgs('CRON_SAFE_MODE').returns('true');
- let cronOverride = requireAgain(pathToCronLib).cron;
+ const cronOverride = requireAgain(pathToCronLib).cron;
daysMissed = 1;
tasksByType.dailys[0].completed = false;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let previousBuffs = user.stats.buffs.toObject();
+ const previousBuffs = user.stats.buffs.toObject();
- cronOverride({user, tasksByType, daysMissed, analytics});
+ cronOverride({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.be.greaterThan(previousBuffs.str);
expect(user.stats.buffs.int).to.be.greaterThan(previousBuffs.int);
@@ -1404,14 +1686,16 @@ describe('cron', () => {
it('always grants a perfect day buff when CRON_SAFE_MODE is set when user is sleeping', () => {
user.preferences.sleep = true;
sandbox.stub(nconf, 'get').withArgs('CRON_SAFE_MODE').returns('true');
- let cronOverride = requireAgain(pathToCronLib).cron;
+ const cronOverride = requireAgain(pathToCronLib).cron;
daysMissed = 1;
tasksByType.dailys[0].completed = false;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- let previousBuffs = user.stats.buffs.toObject();
+ const previousBuffs = user.stats.buffs.toObject();
- cronOverride({user, tasksByType, daysMissed, analytics});
+ cronOverride({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.buffs.str).to.be.greaterThan(previousBuffs.str);
expect(user.stats.buffs.int).to.be.greaterThan(previousBuffs.int);
@@ -1425,10 +1709,12 @@ describe('cron', () => {
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- let mpBefore = user.stats.mp;
+ const mpBefore = user.stats.mp;
tasksByType.dailys[0].completed = true;
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {maxMP: 100}));
- cron({user, tasksByType, daysMissed, analytics});
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { maxMP: 100 }));
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.mp).to.be.greaterThan(mpBefore);
common.statsComputed.restore();
@@ -1439,10 +1725,12 @@ describe('cron', () => {
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
user.preferences.sleep = true;
- let mpBefore = user.stats.mp;
+ const mpBefore = user.stats.mp;
tasksByType.dailys[0].completed = true;
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {maxMP: 100}));
- cron({user, tasksByType, daysMissed, analytics});
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { maxMP: 100 }));
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.mp).to.equal(mpBefore);
common.statsComputed.restore();
@@ -1452,8 +1740,10 @@ describe('cron', () => {
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
user.stats.mp = 120;
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {maxMP: 100}));
- cron({user, tasksByType, daysMissed, analytics});
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { maxMP: 100 }));
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.stats.mp).to.equal(common.statsComputed(user).maxMP);
common.statsComputed.restore();
@@ -1462,21 +1752,21 @@ describe('cron', () => {
describe('quest progress', () => {
beforeEach(() => {
- let daily = {
+ const daily = {
text: 'test daily',
type: 'daily',
};
- let task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
+ const task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
tasksByType.dailys = [];
tasksByType.dailys.push(task);
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {con: 1}));
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { con: 1 }));
daysMissed = 1;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
});
afterEach(() => {
@@ -1484,32 +1774,38 @@ describe('cron', () => {
});
it('resets user progress', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.party.quest.progress.up).to.equal(0);
expect(user.party.quest.progress.down).to.equal(0);
expect(user.party.quest.progress.collectedItems).to.equal(0);
});
it('applies the user progress', () => {
- let progress = cron({user, tasksByType, daysMissed, analytics});
+ const progress = cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(progress.down).to.equal(-1);
});
});
describe('notifications', () => {
it('adds a user notification', () => {
- let mpBefore = user.stats.mp;
+ const mpBefore = user.stats.mp;
tasksByType.dailys[0].completed = true;
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {maxMP: 100}));
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { maxMP: 100 }));
daysMissed = 1;
- let hpBefore = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ const hpBefore = user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.notifications.length).to.be.greaterThan(0);
expect(user.notifications[1].type).to.equal('CRON');
@@ -1522,18 +1818,20 @@ describe('cron', () => {
});
it('condenses multiple notifications into one', () => {
- let mpBefore1 = user.stats.mp;
+ const mpBefore1 = user.stats.mp;
tasksByType.dailys[0].completed = true;
const statsComputedRes = common.statsComputed(user);
const stubbedStatsComputed = sinon.stub(common, 'statsComputed');
- stubbedStatsComputed.returns(Object.assign(statsComputedRes, {maxMP: 100}));
+ stubbedStatsComputed.returns(Object.assign(statsComputedRes, { maxMP: 100 }));
daysMissed = 1;
- let hpBefore1 = user.stats.hp;
- tasksByType.dailys[0].startDate = moment(new Date()).subtract({days: 1});
+ const hpBefore1 = user.stats.hp;
+ tasksByType.dailys[0].startDate = moment(new Date()).subtract({ days: 1 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.notifications.length).to.be.greaterThan(0);
expect(user.notifications[1].type).to.equal('CRON');
@@ -1542,13 +1840,15 @@ describe('cron', () => {
mp: user.stats.mp - mpBefore1,
});
- let notifsBefore2 = user.notifications.length;
- let hpBefore2 = user.stats.hp;
- let mpBefore2 = user.stats.mp;
+ const notifsBefore2 = user.notifications.length;
+ const hpBefore2 = user.stats.hp;
+ const mpBefore2 = user.stats.mp;
- user.lastCron = moment(new Date()).subtract({days: 2});
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.notifications.length - notifsBefore2).to.equal(0);
expect(user.notifications[0].type).to.not.equal('CRON');
@@ -1566,9 +1866,9 @@ describe('cron', () => {
let lastMessageId;
beforeEach(() => {
- let maxPMs = 200;
+ const maxPMs = 200;
for (let index = 0; index < maxPMs - 1; index += 1) {
- let messageId = common.uuid();
+ const messageId = common.uuid();
user.inbox.messages[messageId] = {
id: messageId,
text: `test ${index}`,
@@ -1593,43 +1893,61 @@ describe('cron', () => {
describe('login incentives', () => {
it('increments incentive counter each cron', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(1);
- user.lastCron = moment(new Date()).subtract({days: 1});
- cron({user, tasksByType, daysMissed, analytics});
+ user.lastCron = moment(new Date()).subtract({ days: 1 });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(2);
});
it('pushes a notification of the day\'s incentive each cron', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.notifications.length).to.be.greaterThan(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
});
it('replaces previous notifications', () => {
- cron({user, tasksByType, daysMissed, analytics});
- cron({user, tasksByType, daysMissed, analytics});
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
- let filteredNotifications = user.notifications.filter(n => n.type === 'LOGIN_INCENTIVE');
+ const filteredNotifications = user.notifications.filter(n => n.type === 'LOGIN_INCENTIVE');
expect(filteredNotifications.length).to.equal(1);
});
it('increments loginIncentives by 1 even if days are skipped in between', () => {
daysMissed = 3;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(1);
});
it('increments loginIncentives by 1 even if user is sleeping', () => {
user.preferences.sleep = true;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(1);
});
it('awards user bard robes if login incentive is 1', () => {
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(1);
expect(user.items.gear.owned.armor_special_bardRobes).to.eql(true);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1637,7 +1955,9 @@ describe('cron', () => {
it('awards user incentive backgrounds if login incentive is 2', () => {
user.loginIncentives = 1;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(2);
expect(user.purchased.background.blue).to.eql(true);
expect(user.purchased.background.green).to.eql(true);
@@ -1649,7 +1969,9 @@ describe('cron', () => {
it('awards user Bard Hat if login incentive is 3', () => {
user.loginIncentives = 2;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(3);
expect(user.items.gear.owned.head_special_bardHat).to.eql(true);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1657,7 +1979,9 @@ describe('cron', () => {
it('awards user RoyalPurple Hatching Potion if login incentive is 4', () => {
user.loginIncentives = 3;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(4);
expect(user.items.hatchingPotions.RoyalPurple).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1665,7 +1989,9 @@ describe('cron', () => {
it('awards user a Chocolate, Meat and Pink Contton Candy if login incentive is 5', () => {
user.loginIncentives = 4;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(5);
expect(user.items.food.Chocolate).to.eql(1);
@@ -1677,7 +2003,9 @@ describe('cron', () => {
it('awards user moon quest if login incentive is 7', () => {
user.loginIncentives = 6;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(7);
expect(user.items.quests.moon1).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1685,7 +2013,9 @@ describe('cron', () => {
it('awards user RoyalPurple Hatching Potion if login incentive is 10', () => {
user.loginIncentives = 9;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(10);
expect(user.items.hatchingPotions.RoyalPurple).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1693,7 +2023,9 @@ describe('cron', () => {
it('awards user a Strawberry, Patato and Blue Contton Candy if login incentive is 14', () => {
user.loginIncentives = 13;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(14);
expect(user.items.food.Strawberry).to.eql(1);
@@ -1705,7 +2037,9 @@ describe('cron', () => {
it('awards user a bard instrument if login incentive is 18', () => {
user.loginIncentives = 17;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(18);
expect(user.items.gear.owned.weapon_special_bardInstrument).to.eql(true);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1713,7 +2047,9 @@ describe('cron', () => {
it('awards user second moon quest if login incentive is 22', () => {
user.loginIncentives = 21;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(22);
expect(user.items.quests.moon2).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1721,7 +2057,9 @@ describe('cron', () => {
it('awards user a RoyalPurple hatching potion if login incentive is 26', () => {
user.loginIncentives = 25;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(26);
expect(user.items.hatchingPotions.RoyalPurple).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1729,7 +2067,9 @@ describe('cron', () => {
it('awards user Fish, Milk, Rotten Meat and Honey if login incentive is 30', () => {
user.loginIncentives = 29;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(30);
expect(user.items.food.Fish).to.eql(1);
@@ -1742,7 +2082,9 @@ describe('cron', () => {
it('awards user a RoyalPurple hatching potion if login incentive is 35', () => {
user.loginIncentives = 34;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(35);
expect(user.items.hatchingPotions.RoyalPurple).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1750,7 +2092,9 @@ describe('cron', () => {
it('awards user the third moon quest if login incentive is 40', () => {
user.loginIncentives = 39;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(40);
expect(user.items.quests.moon3).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1758,7 +2102,9 @@ describe('cron', () => {
it('awards user a RoyalPurple hatching potion if login incentive is 45', () => {
user.loginIncentives = 44;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(45);
expect(user.items.hatchingPotions.RoyalPurple).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1766,7 +2112,9 @@ describe('cron', () => {
it('awards user a saddle if login incentive is 50', () => {
user.loginIncentives = 49;
- cron({user, tasksByType, daysMissed, analytics});
+ cron({
+ user, tasksByType, daysMissed, analytics,
+ });
expect(user.loginIncentives).to.eql(50);
expect(user.items.food.Saddle).to.eql(1);
expect(user.notifications[0].type).to.eql('LOGIN_INCENTIVE');
@@ -1775,7 +2123,8 @@ describe('cron', () => {
});
describe('recoverCron', () => {
- let locals, status, execStub;
+ let locals; let status; let
+ execStub;
beforeEach(() => {
execStub = sandbox.stub();
@@ -1813,17 +2162,17 @@ describe('recoverCron', () => {
});
it('increases status.times count and reruns up to 4 times', async () => {
- execStub.returns(Promise.resolve({_cronSignature: 'RUNNING_CRON'}));
- execStub.onCall(4).returns(Promise.resolve({_cronSignature: 'NOT_RUNNING'}));
+ execStub.returns(Promise.resolve({ _cronSignature: 'RUNNING_CRON' }));
+ execStub.onCall(4).returns(Promise.resolve({ _cronSignature: 'NOT_RUNNING' }));
await recoverCron(status, locals);
expect(status.times).to.eql(4);
- expect(locals.user).to.eql({_cronSignature: 'NOT_RUNNING'});
+ expect(locals.user).to.eql({ _cronSignature: 'NOT_RUNNING' });
});
it('throws an error if recoverCron runs 5 times', async () => {
- execStub.returns(Promise.resolve({_cronSignature: 'RUNNING_CRON'}));
+ execStub.returns(Promise.resolve({ _cronSignature: 'RUNNING_CRON' }));
try {
await recoverCron(status, locals);
diff --git a/test/api/unit/libs/email.test.js b/test/api/unit/libs/email.test.js
index 6b4d368aa6..057766eddd 100644
--- a/test/api/unit/libs/email.test.js
+++ b/test/api/unit/libs/email.test.js
@@ -31,20 +31,20 @@ function getUser () {
}
describe('emails', () => {
- let pathToEmailLib = '../../../../website/server/libs/email';
+ const pathToEmailLib = '../../../../website/server/libs/email';
describe('getUserInfo', () => {
it('returns an empty object if no field request', () => {
- let attachEmail = requireAgain(pathToEmailLib);
- let getUserInfo = attachEmail.getUserInfo;
+ const attachEmail = requireAgain(pathToEmailLib);
+ const { getUserInfo } = attachEmail;
expect(getUserInfo({}, [])).to.be.empty;
});
it('returns correct user data', () => {
- let attachEmail = requireAgain(pathToEmailLib);
- let getUserInfo = attachEmail.getUserInfo;
- let user = getUser();
- let data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
+ const attachEmail = requireAgain(pathToEmailLib);
+ const { getUserInfo } = attachEmail;
+ const user = getUser();
+ const data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
expect(data).to.have.property('name', user.auth.local.username);
expect(data).to.have.property('email', user.auth.local.email);
@@ -53,13 +53,13 @@ describe('emails', () => {
});
it('returns correct user data [facebook users]', () => {
- let attachEmail = requireAgain(pathToEmailLib);
- let getUserInfo = attachEmail.getUserInfo;
- let user = getUser();
+ const attachEmail = requireAgain(pathToEmailLib);
+ const { getUserInfo } = attachEmail;
+ const user = getUser();
delete user.profile.name;
delete user.auth.local.email;
- let data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
+ const data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
expect(data).to.have.property('name', user.auth.local.username);
expect(data).to.have.property('email', user.auth.facebook.emails[0].value);
@@ -68,13 +68,13 @@ describe('emails', () => {
});
it('has fallbacks for missing data', () => {
- let attachEmail = requireAgain(pathToEmailLib);
- let getUserInfo = attachEmail.getUserInfo;
- let user = getUser();
+ const attachEmail = requireAgain(pathToEmailLib);
+ const { getUserInfo } = attachEmail;
+ const user = getUser();
delete user.auth.local.email;
delete user.auth.facebook;
- let data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
+ const data = getUserInfo(user, ['name', 'email', '_id', 'canSend']);
expect(data).to.have.property('name', user.auth.local.username);
expect(data).not.to.have.property('email');
@@ -85,18 +85,18 @@ describe('emails', () => {
describe('getGroupUrl', () => {
it('returns correct url if group is the tavern', () => {
- let getGroupUrl = require(pathToEmailLib).getGroupUrl;
- expect(getGroupUrl({_id: TAVERN_ID, type: 'guild'})).to.eql('/groups/tavern');
+ const { getGroupUrl } = require(pathToEmailLib); // eslint-disable-line import/no-dynamic-require, max-len
+ expect(getGroupUrl({ _id: TAVERN_ID, type: 'guild' })).to.eql('/groups/tavern');
});
it('returns correct url if group is a guild', () => {
- let getGroupUrl = require(pathToEmailLib).getGroupUrl;
- expect(getGroupUrl({_id: 'random _id', type: 'guild'})).to.eql('/groups/guild/random _id');
+ const { getGroupUrl } = require(pathToEmailLib); // eslint-disable-line import/no-dynamic-require, max-len
+ expect(getGroupUrl({ _id: 'random _id', type: 'guild' })).to.eql('/groups/guild/random _id');
});
it('returns correct url if group is a party', () => {
- let getGroupUrl = require(pathToEmailLib).getGroupUrl;
- expect(getGroupUrl({_id: 'random _id', type: 'party'})).to.eql('party');
+ const { getGroupUrl } = require(pathToEmailLib); // eslint-disable-line import/no-dynamic-require, max-len
+ expect(getGroupUrl({ _id: 'random _id', type: 'party' })).to.eql('party');
});
});
@@ -111,10 +111,10 @@ describe('emails', () => {
it('can send a txn email to one recipient', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(true);
- let attachEmail = requireAgain(pathToEmailLib);
- let sendTxnEmail = attachEmail.sendTxn;
- let emailType = 'an email type';
- let mailingInfo = {
+ const attachEmail = requireAgain(pathToEmailLib);
+ const sendTxnEmail = attachEmail.sendTxn;
+ const emailType = 'an email type';
+ const mailingInfo = {
name: 'my name',
email: 'my@email',
};
@@ -125,9 +125,7 @@ describe('emails', () => {
body: {
data: {
emailType: sinon.match.same(emailType),
- to: sinon.match((value) => {
- return Array.isArray(value) && value[0].name === mailingInfo.name;
- }, 'matches mailing info array'),
+ to: sinon.match(value => Array.isArray(value) && value[0].name === mailingInfo.name, 'matches mailing info array'),
},
},
}));
@@ -135,10 +133,10 @@ describe('emails', () => {
it('does not send email if address is missing', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(true);
- let attachEmail = requireAgain(pathToEmailLib);
- let sendTxnEmail = attachEmail.sendTxn;
- let emailType = 'an email type';
- let mailingInfo = {
+ const attachEmail = requireAgain(pathToEmailLib);
+ const sendTxnEmail = attachEmail.sendTxn;
+ const emailType = 'an email type';
+ const mailingInfo = {
name: 'my name',
// email: 'my@email',
};
@@ -149,10 +147,10 @@ describe('emails', () => {
it('uses getUserInfo in case of user data', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(true);
- let attachEmail = requireAgain(pathToEmailLib);
- let sendTxnEmail = attachEmail.sendTxn;
- let emailType = 'an email type';
- let mailingInfo = getUser();
+ const attachEmail = requireAgain(pathToEmailLib);
+ const sendTxnEmail = attachEmail.sendTxn;
+ const emailType = 'an email type';
+ const mailingInfo = getUser();
sendTxnEmail(mailingInfo, emailType);
expect(got.post).to.be.calledWith('undefined/job', sinon.match({
@@ -168,28 +166,24 @@ describe('emails', () => {
it('sends email with some default variables', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(true);
- let attachEmail = requireAgain(pathToEmailLib);
- let sendTxnEmail = attachEmail.sendTxn;
- let emailType = 'an email type';
- let mailingInfo = {
+ const attachEmail = requireAgain(pathToEmailLib);
+ const sendTxnEmail = attachEmail.sendTxn;
+ const emailType = 'an email type';
+ const mailingInfo = {
name: 'my name',
email: 'my@email',
};
- let variables = [1, 2, 3];
+ const variables = [1, 2, 3];
sendTxnEmail(mailingInfo, emailType, variables);
expect(got.post).to.be.calledWith('undefined/job', sinon.match({
json: true,
body: {
data: {
- variables: sinon.match((value) => {
- return value[0].name === 'BASE_URL';
- }, 'matches variables'),
- personalVariables: sinon.match((value) => {
- return value[0].rcpt === mailingInfo.email &&
- value[0].vars[0].name === 'RECIPIENT_NAME' &&
- value[0].vars[1].name === 'RECIPIENT_UNSUB_URL';
- }, 'matches personal variables'),
+ variables: sinon.match(value => value[0].name === 'BASE_URL', 'matches variables'),
+ personalVariables: sinon.match(value => value[0].rcpt === mailingInfo.email
+ && value[0].vars[0].name === 'RECIPIENT_NAME'
+ && value[0].vars[1].name === 'RECIPIENT_UNSUB_URL', 'matches personal variables'),
},
},
}));
diff --git a/test/api/unit/libs/encryption.test.js b/test/api/unit/libs/encryption.test.js
index 60522d1927..fdfdb39e75 100644
--- a/test/api/unit/libs/encryption.test.js
+++ b/test/api/unit/libs/encryption.test.js
@@ -5,9 +5,9 @@ import {
describe('encryption', () => {
it('can encrypt and decrypt', () => {
- let data = 'some secret text';
- let encrypted = encrypt(data);
- let decrypted = decrypt(encrypted);
+ const data = 'some secret text';
+ const encrypted = encrypt(data);
+ const decrypted = decrypt(encrypted);
expect(encrypted).not.to.equal(data);
expect(data).to.equal(decrypted);
diff --git a/test/api/unit/libs/errors.test.js b/test/api/unit/libs/errors.test.js
index b7e3657ff4..4de2e4499f 100644
--- a/test/api/unit/libs/errors.test.js
+++ b/test/api/unit/libs/errors.test.js
@@ -12,7 +12,7 @@ import i18n from '../../../../website/common/script/i18n';
describe('Custom Errors', () => {
describe('CustomError', () => {
it('is an instance of Error', () => {
- let customError = new CustomError();
+ const customError = new CustomError();
expect(customError).to.be.an.instanceOf(Error);
});
@@ -20,25 +20,25 @@ describe('Custom Errors', () => {
describe('NotAuthorized', () => {
it('is an instance of CustomError', () => {
- let notAuthorizedError = new NotAuthorized();
+ const notAuthorizedError = new NotAuthorized();
expect(notAuthorizedError).to.be.an.instanceOf(CustomError);
});
it('it returns an http code of 401', () => {
- let notAuthorizedError = new NotAuthorized();
+ const notAuthorizedError = new NotAuthorized();
expect(notAuthorizedError.httpCode).to.eql(401);
});
it('returns a default message', () => {
- let notAuthorizedError = new NotAuthorized();
+ const notAuthorizedError = new NotAuthorized();
expect(notAuthorizedError.message).to.eql('Not authorized.');
});
it('allows a custom message', () => {
- let notAuthorizedError = new NotAuthorized('Custom Error Message');
+ const notAuthorizedError = new NotAuthorized('Custom Error Message');
expect(notAuthorizedError.message).to.eql('Custom Error Message');
});
@@ -46,25 +46,25 @@ describe('Custom Errors', () => {
describe('NotFound', () => {
it('is an instance of CustomError', () => {
- let notAuthorizedError = new NotFound();
+ const notAuthorizedError = new NotFound();
expect(notAuthorizedError).to.be.an.instanceOf(CustomError);
});
it('it returns an http code of 404', () => {
- let notAuthorizedError = new NotFound();
+ const notAuthorizedError = new NotFound();
expect(notAuthorizedError.httpCode).to.eql(404);
});
it('returns a default message', () => {
- let notAuthorizedError = new NotFound();
+ const notAuthorizedError = new NotFound();
expect(notAuthorizedError.message).to.eql('Not found.');
});
it('allows a custom message', () => {
- let notAuthorizedError = new NotFound('Custom Error Message');
+ const notAuthorizedError = new NotFound('Custom Error Message');
expect(notAuthorizedError.message).to.eql('Custom Error Message');
});
@@ -89,25 +89,25 @@ describe('Custom Errors', () => {
describe('BadRequest', () => {
it('is an instance of CustomError', () => {
- let badRequestError = new BadRequest();
+ const badRequestError = new BadRequest();
expect(badRequestError).to.be.an.instanceOf(CustomError);
});
it('it returns an http code of 401', () => {
- let badRequestError = new BadRequest();
+ const badRequestError = new BadRequest();
expect(badRequestError.httpCode).to.eql(400);
});
it('returns a default message', () => {
- let badRequestError = new BadRequest();
+ const badRequestError = new BadRequest();
expect(badRequestError.message).to.eql('Bad request.');
});
it('allows a custom message', () => {
- let badRequestError = new BadRequest('Custom Error Message');
+ const badRequestError = new BadRequest('Custom Error Message');
expect(badRequestError.message).to.eql('Custom Error Message');
});
@@ -115,25 +115,25 @@ describe('Custom Errors', () => {
describe('InternalServerError', () => {
it('is an instance of CustomError', () => {
- let internalServerError = new InternalServerError();
+ const internalServerError = new InternalServerError();
expect(internalServerError).to.be.an.instanceOf(CustomError);
});
it('it returns an http code of 500', () => {
- let internalServerError = new InternalServerError();
+ const internalServerError = new InternalServerError();
expect(internalServerError.httpCode).to.eql(500);
});
it('returns a default message', () => {
- let internalServerError = new InternalServerError();
+ const internalServerError = new InternalServerError();
expect(internalServerError.message).to.eql('An unexpected error occurred.');
});
it('allows a custom message', () => {
- let internalServerError = new InternalServerError('Custom Error Message');
+ const internalServerError = new InternalServerError('Custom Error Message');
expect(internalServerError.message).to.eql('Custom Error Message');
});
diff --git a/test/api/unit/libs/i18n.test.js b/test/api/unit/libs/i18n.test.js
index e276ee5dc1..bc1c436332 100644
--- a/test/api/unit/libs/i18n.test.js
+++ b/test/api/unit/libs/i18n.test.js
@@ -5,11 +5,11 @@ import {
} from '../../../../website/server/libs/i18n';
describe('i18n', () => {
- let listOfLocales = approvedLanguages.sort();
+ const listOfLocales = approvedLanguages.sort();
describe('translations', () => {
it('includes a translation object for each locale', () => {
- listOfLocales.forEach((locale) => {
+ listOfLocales.forEach(locale => {
expect(translations[locale]).to.be.an('object');
});
});
diff --git a/test/api/unit/libs/logger.js b/test/api/unit/libs/logger.js
index bf6f2a2f9f..c9878f36fa 100644
--- a/test/api/unit/libs/logger.js
+++ b/test/api/unit/libs/logger.js
@@ -2,7 +2,7 @@ import winston from 'winston';
import logger from '../../../../website/server/libs/logger';
import {
NotFound,
-} from '../../../../website/server/libs//errors';
+} from '../../../../website/server/libs/errors';
describe('logger', () => {
let logSpy;
@@ -34,7 +34,7 @@ describe('logger', () => {
context('error object', () => {
it('logs the stack and the err data', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, {
data: 1,
}, 2, 3);
@@ -45,13 +45,13 @@ describe('logger', () => {
errInstance.stack,
{ data: 1, fullError: errInstance },
2,
- 3
+ 3,
);
});
it('logs the stack and the err data with it\'s own fullError property', () => {
- let errInstance = new Error('An error.');
- let anotherError = new Error('another error');
+ const errInstance = new Error('An error.');
+ const anotherError = new Error('another error');
logger.error(errInstance, {
data: 1,
@@ -64,12 +64,12 @@ describe('logger', () => {
errInstance.stack,
{ data: 1, fullError: anotherError },
2,
- 3
+ 3,
);
});
it('logs the error when errorData is null', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, null, 2, 3);
@@ -79,12 +79,12 @@ describe('logger', () => {
errInstance.stack,
null,
2,
- 3
+ 3,
);
});
it('logs the error when errorData is not an object', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, true, 2, 3);
@@ -94,12 +94,12 @@ describe('logger', () => {
errInstance.stack,
true,
2,
- 3
+ 3,
);
});
it('logs the error when errorData does not include isHandledError property', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, { httpCode: 400 }, 2, 3);
@@ -109,12 +109,12 @@ describe('logger', () => {
errInstance.stack,
{ httpCode: 400, fullError: errInstance },
2,
- 3
+ 3,
);
});
it('logs the error when errorData includes isHandledError property but is a 500 error', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, {
isHandledError: true,
@@ -127,12 +127,12 @@ describe('logger', () => {
errInstance.stack,
{ httpCode: 502, isHandledError: true, fullError: errInstance },
2,
- 3
+ 3,
);
});
it('logs a warning when errorData includes isHandledError property and is not a 500 error', () => {
- let errInstance = new Error('An error.');
+ const errInstance = new Error('An error.');
logger.error(errInstance, {
isHandledError: true,
@@ -145,12 +145,12 @@ describe('logger', () => {
errInstance.stack,
{ httpCode: 403, isHandledError: true, fullError: errInstance },
2,
- 3
+ 3,
);
});
it('logs additional data from a CustomError', () => {
- let errInstance = new NotFound('An error.');
+ const errInstance = new NotFound('An error.');
errInstance.customField = 'Some interesting data';
@@ -166,7 +166,7 @@ describe('logger', () => {
},
},
2,
- 3
+ 3,
);
});
});
diff --git a/test/api/unit/libs/password.test.js b/test/api/unit/libs/password.test.js
index 66fccbfe51..3ca2643b6d 100644
--- a/test/api/unit/libs/password.test.js
+++ b/test/api/unit/libs/password.test.js
@@ -1,9 +1,9 @@
/* eslint-disable camelcase */
+import moment from 'moment';
import {
encrypt,
} from '../../../../website/server/libs/encryption';
-import moment from 'moment';
import {
generateUser,
} from '../../../helpers/api-integration/v3';
@@ -20,11 +20,11 @@ import {
describe('Password Utilities', () => {
describe('compare', () => {
it('can compare a correct password hashed with SHA1', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let hashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const hashedPassword = sha1EncryptPassword(textPassword, salt);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -34,16 +34,16 @@ describe('Password Utilities', () => {
},
};
- let isValidPassword = await compare(user, textPassword);
+ const isValidPassword = await compare(user, textPassword);
expect(isValidPassword).to.eql(true);
});
it('can compare an invalid password hashed with SHA1', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let hashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const hashedPassword = sha1EncryptPassword(textPassword, salt);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -53,15 +53,15 @@ describe('Password Utilities', () => {
},
};
- let isValidPassword = await compare(user, 'wrongPassword');
+ const isValidPassword = await compare(user, 'wrongPassword');
expect(isValidPassword).to.eql(false);
});
it('can compare a correct password hashed with bcrypt', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -70,15 +70,15 @@ describe('Password Utilities', () => {
},
};
- let isValidPassword = await compare(user, textPassword);
+ const isValidPassword = await compare(user, textPassword);
expect(isValidPassword).to.eql(true);
});
it('can compare an invalid password hashed with bcrypt', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -87,7 +87,7 @@ describe('Password Utilities', () => {
},
};
- let isValidPassword = await compare(user, 'wrongPassword');
+ const isValidPassword = await compare(user, 'wrongPassword');
expect(isValidPassword).to.eql(false);
});
@@ -101,18 +101,18 @@ describe('Password Utilities', () => {
it('throws an error if passwordToCheck is missing', async () => {
try {
- await compare({a: true});
+ await compare({ a: true });
} catch (e) {
expect(e.toString()).to.equal('Error: user and passwordToCheck are required parameters.');
}
});
it('defaults to SHA1 encryption if salt is provided', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let hashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const hashedPassword = sha1EncryptPassword(textPassword, salt);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -122,7 +122,7 @@ describe('Password Utilities', () => {
},
};
- let isValidPassword = await compare(user, textPassword);
+ const isValidPassword = await compare(user, textPassword);
expect(isValidPassword).to.eql(true);
});
@@ -141,29 +141,29 @@ describe('Password Utilities', () => {
});
it('returns true if comparing the same password', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let isValidPassword = await bcryptCompare(textPassword, hashedPassword);
+ const isValidPassword = await bcryptCompare(textPassword, hashedPassword);
expect(isValidPassword).to.eql(true);
});
it('returns true if comparing a different password', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let isValidPassword = await bcryptCompare('anotherPassword', hashedPassword);
+ const isValidPassword = await bcryptCompare('anotherPassword', hashedPassword);
expect(isValidPassword).to.eql(false);
});
});
describe('convertToBcrypt', () => {
it('converts an user password hashed with sha1 to bcrypt', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let hashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const hashedPassword = sha1EncryptPassword(textPassword, salt);
- let user = {
+ const user = {
auth: {
local: {
hashed_password: hashedPassword,
@@ -178,7 +178,7 @@ describe('Password Utilities', () => {
expect(user.auth.local.passwordHashMethod).to.equal('bcrypt');
expect(user.auth.local.hashed_password).to.be.a.string;
- let isValidPassword = await compare(user, textPassword);
+ const isValidPassword = await compare(user, textPassword);
expect(isValidPassword).to.eql(true);
});
@@ -192,7 +192,7 @@ describe('Password Utilities', () => {
it('throws an error if plainTextPassword is missing', async () => {
try {
- await convertToBcrypt({a: true});
+ await convertToBcrypt({ a: true });
} catch (e) {
expect(e.toString()).to.equal('Error: user and plainTextPassword are required parameters.');
}
@@ -201,18 +201,18 @@ describe('Password Utilities', () => {
describe('validatePasswordResetCodeAndFindUser', () => {
it('returns false if the code is missing', async () => {
- let res = await validatePasswordResetCodeAndFindUser();
+ const res = await validatePasswordResetCodeAndFindUser();
expect(res).to.equal(false);
});
it('returns false if the code is invalid json', async () => {
- let res = await validatePasswordResetCodeAndFindUser('invalid json');
+ const res = await validatePasswordResetCodeAndFindUser('invalid json');
expect(res).to.equal(false);
});
it('returns false if the code cannot be decrypted', async () => {
- let user = await generateUser();
- let res = await validatePasswordResetCodeAndFindUser(JSON.stringify({ // not encrypted
+ const user = await generateUser();
+ const res = await validatePasswordResetCodeAndFindUser(JSON.stringify({ // not encrypted
userId: user._id,
expiresAt: new Date(),
}));
@@ -220,71 +220,71 @@ describe('Password Utilities', () => {
});
it('returns false if the code is expired', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().subtract({minutes: 1}),
+ expiresAt: moment().subtract({ minutes: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
});
- let res = await validatePasswordResetCodeAndFindUser(code);
+ const res = await validatePasswordResetCodeAndFindUser(code);
expect(res).to.equal(false);
});
it('returns false if the user does not exist', async () => {
- let res = await validatePasswordResetCodeAndFindUser(encrypt(JSON.stringify({
+ const res = await validatePasswordResetCodeAndFindUser(encrypt(JSON.stringify({
userId: Date.now().toString(),
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
})));
expect(res).to.equal(false);
});
it('returns false if the user has no local auth', async () => {
- let user = await generateUser({
+ const user = await generateUser({
auth: {
facebook: {},
},
});
- let res = await validatePasswordResetCodeAndFindUser(encrypt(JSON.stringify({
+ const res = await validatePasswordResetCodeAndFindUser(encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
})));
expect(res).to.equal(false);
});
it('returns false if the code doesn\'t match the one saved at user.auth.passwordResetCode', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': 'invalid',
});
- let res = await validatePasswordResetCodeAndFindUser(code);
+ const res = await validatePasswordResetCodeAndFindUser(code);
expect(res).to.equal(false);
});
it('returns the user if the password reset code is valid', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
});
- let res = await validatePasswordResetCodeAndFindUser(code);
+ const res = await validatePasswordResetCodeAndFindUser(code);
expect(res).not.to.equal(false);
expect(res._id).to.equal(user._id);
});
@@ -293,8 +293,8 @@ describe('Password Utilities', () => {
describe('bcrypt', () => {
describe('Hash', () => {
it('returns a hashed string', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
expect(hashedPassword).to.be.a.string;
});
@@ -302,18 +302,18 @@ describe('Password Utilities', () => {
describe('Compare', () => {
it('returns true if comparing the same password', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let isValidPassword = await bcryptCompare(textPassword, hashedPassword);
+ const isValidPassword = await bcryptCompare(textPassword, hashedPassword);
expect(isValidPassword).to.eql(true);
});
it('returns true if comparing a different password', async () => {
- let textPassword = 'mySecretPassword';
- let hashedPassword = await bcryptHash(textPassword);
+ const textPassword = 'mySecretPassword';
+ const hashedPassword = await bcryptHash(textPassword);
- let isValidPassword = await bcryptCompare('anotherPassword', hashedPassword);
+ const isValidPassword = await bcryptCompare('anotherPassword', hashedPassword);
expect(isValidPassword).to.eql(false);
});
});
@@ -322,19 +322,19 @@ describe('Password Utilities', () => {
describe('SHA1', () => {
describe('Encrypt', () => {
it('always encrypt the same password to the same value when using the same salt', () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let encryptedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const encryptedPassword = sha1EncryptPassword(textPassword, salt);
expect(sha1EncryptPassword(textPassword, salt)).to.eql(encryptedPassword);
});
it('never encrypt the same password to the same value when using a different salt', () => {
- let textPassword = 'mySecretPassword';
- let aSalt = sha1MakeSalt();
- let anotherSalt = sha1MakeSalt();
- let anEncryptedPassword = sha1EncryptPassword(textPassword, aSalt);
- let anotherEncryptedPassword = sha1EncryptPassword(textPassword, anotherSalt);
+ const textPassword = 'mySecretPassword';
+ const aSalt = sha1MakeSalt();
+ const anotherSalt = sha1MakeSalt();
+ const anEncryptedPassword = sha1EncryptPassword(textPassword, aSalt);
+ const anotherEncryptedPassword = sha1EncryptPassword(textPassword, anotherSalt);
expect(anEncryptedPassword).not.to.eql(anotherEncryptedPassword);
});
@@ -342,14 +342,14 @@ describe('Password Utilities', () => {
describe('Make Salt', () => {
it('creates a salt with length 10 by default', () => {
- let salt = sha1MakeSalt();
+ const salt = sha1MakeSalt();
expect(salt.length).to.eql(10);
});
it('can create a salt of any length', () => {
- let length = 24;
- let salt = sha1MakeSalt(length);
+ const length = 24;
+ const salt = sha1MakeSalt(length);
expect(salt.length).to.eql(length);
});
diff --git a/test/api/unit/libs/payments/amazon/cancel.test.js b/test/api/unit/libs/payments/amazon/cancel.test.js
index ab0f2ebf8c..e24d3dbf52 100644
--- a/test/api/unit/libs/payments/amazon/cancel.test.js
+++ b/test/api/unit/libs/payments/amazon/cancel.test.js
@@ -2,19 +2,20 @@ import moment from 'moment';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
import { createNonLeaderGroupMember } from '../paymentHelpers';
-const i18n = common.i18n;
+const { i18n } = common;
describe('Amazon Payments - Cancel Subscription', () => {
const subKey = 'basic_3mo';
- let user, group, headers, billingAgreementId, subscriptionBlock, subscriptionLength;
+ let user; let group; let headers; let billingAgreementId; let subscriptionBlock; let
+ subscriptionLength;
let getBillingAgreementDetailsSpy;
let paymentCancelSubscriptionSpy;
@@ -50,7 +51,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
getBillingAgreementDetailsSpy = sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
- BillingAgreementStatus: {State: 'Open'},
+ BillingAgreementStatus: { State: 'Open' },
},
});
}
@@ -81,7 +82,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
getBillingAgreementDetailsSpy = sinon.stub(amzLib, 'getBillingAgreementDetails');
getBillingAgreementDetailsSpy.resolves({
BillingAgreementDetails: {
- BillingAgreementStatus: {State: 'Closed'},
+ BillingAgreementStatus: { State: 'Closed' },
},
});
@@ -89,7 +90,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
paymentCancelSubscriptionSpy.resolves({});
});
- afterEach(function () {
+ afterEach(() => {
amzLib.getBillingAgreementDetails.restore();
payments.cancelSubscription.restore();
});
@@ -97,7 +98,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should throw an error if we are missing a subscription', async () => {
user.purchased.plan.customerId = undefined;
- await expect(amzLib.cancelSubscription({user}))
+ await expect(amzLib.cancelSubscription({ user }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -108,7 +109,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should cancel a user subscription', async () => {
billingAgreementId = user.purchased.plan.customerId;
- await amzLib.cancelSubscription({user, headers});
+ await amzLib.cancelSubscription({ user, headers });
expectAmazonCancelUserSubscriptionSpy();
expectAmazonStubs();
@@ -117,10 +118,10 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should close a user subscription if amazon not closed', async () => {
amzLib.getBillingAgreementDetails.restore();
expectBillingAggreementDetailSpy();
- let closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
+ const closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
billingAgreementId = user.purchased.plan.customerId;
- await amzLib.cancelSubscription({user, headers});
+ await amzLib.cancelSubscription({ user, headers });
expectAmazonStubs();
expect(closeBillingAgreementSpy).to.be.calledOnce;
@@ -132,7 +133,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
});
it('should throw an error if group is not found', async () => {
- await expect(amzLib.cancelSubscription({user, groupId: 'fake-id'}))
+ await expect(amzLib.cancelSubscription({ user, groupId: 'fake-id' }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 404,
name: 'NotFound',
@@ -141,9 +142,9 @@ describe('Amazon Payments - Cancel Subscription', () => {
});
it('should throw an error if user is not group leader', async () => {
- let nonLeader = await createNonLeaderGroupMember(group);
+ const nonLeader = await createNonLeaderGroupMember(group);
- await expect(amzLib.cancelSubscription({user: nonLeader, groupId: group._id}))
+ await expect(amzLib.cancelSubscription({ user: nonLeader, groupId: group._id }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -154,7 +155,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should cancel a group subscription', async () => {
billingAgreementId = group.purchased.plan.customerId;
- await amzLib.cancelSubscription({user, groupId: group._id, headers});
+ await amzLib.cancelSubscription({ user, groupId: group._id, headers });
expectAmazonCancelGroupSubscriptionSpy(group._id);
expectAmazonStubs();
@@ -163,10 +164,10 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should close a group subscription if amazon not closed', async () => {
amzLib.getBillingAgreementDetails.restore();
expectBillingAggreementDetailSpy();
- let closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
+ const closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
billingAgreementId = group.purchased.plan.customerId;
- await amzLib.cancelSubscription({user, groupId: group._id, headers});
+ await amzLib.cancelSubscription({ user, groupId: group._id, headers });
expectAmazonStubs();
expect(closeBillingAgreementSpy).to.be.calledOnce;
diff --git a/test/api/unit/libs/payments/amazon/checkout.test.js b/test/api/unit/libs/payments/amazon/checkout.test.js
index 4e220bb26b..ee4ab9cee7 100644
--- a/test/api/unit/libs/payments/amazon/checkout.test.js
+++ b/test/api/unit/libs/payments/amazon/checkout.test.js
@@ -3,11 +3,12 @@ import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('Amazon Payments - Checkout', () => {
const subKey = 'basic_3mo';
- let user, orderReferenceId, headers;
+ let user; let orderReferenceId; let
+ headers;
let setOrderReferenceDetailsSpy;
let confirmOrderReferenceSpy;
let authorizeSpy;
@@ -62,7 +63,7 @@ describe('Amazon Payments - Checkout', () => {
expect(closeOrderReferenceSpy).to.be.calledWith({ AmazonOrderReferenceId: orderReferenceId });
}
- beforeEach(function () {
+ beforeEach(() => {
user = new User();
headers = {};
orderReferenceId = 'orderReferenceId';
@@ -88,7 +89,7 @@ describe('Amazon Payments - Checkout', () => {
sinon.stub(common, 'uuid').returns('uuid-generated');
});
- afterEach(function () {
+ afterEach(() => {
amzLib.setOrderReferenceDetails.restore();
amzLib.confirmOrderReference.restore();
amzLib.authorize.restore();
@@ -101,7 +102,7 @@ describe('Amazon Payments - Checkout', () => {
function expectBuyGemsStub (paymentMethod, gift) {
expect(paymentBuyGemsStub).to.be.calledOnce;
- let expectedArgs = {
+ const expectedArgs = {
user,
paymentMethod,
headers,
@@ -112,7 +113,7 @@ describe('Amazon Payments - Checkout', () => {
it('should purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
- await amzLib.checkout({user, orderReferenceId, headers});
+ await amzLib.checkout({ user, orderReferenceId, headers });
expectBuyGemsStub(amzLib.constants.PAYMENT_METHOD);
expectAmazonStubs();
@@ -121,9 +122,9 @@ describe('Amazon Payments - Checkout', () => {
});
it('should error if gem amount is too low', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
- let gift = {
+ const gift = {
type: 'gems',
gems: {
amount: 0,
@@ -131,7 +132,9 @@ describe('Amazon Payments - Checkout', () => {
},
};
- await expect(amzLib.checkout({gift, user, orderReferenceId, headers}))
+ await expect(amzLib.checkout({
+ gift, user, orderReferenceId, headers,
+ }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
message: 'Amount must be at least 1.',
@@ -141,18 +144,19 @@ describe('Amazon Payments - Checkout', () => {
it('should error if user cannot get gems gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
- await expect(amzLib.checkout({user, orderReferenceId, headers})).to.eventually.be.rejected.and.to.eql({
- httpCode: 401,
- message: i18n.t('groupPolicyCannotGetGems'),
- name: 'NotAuthorized',
- });
+ await expect(amzLib.checkout({ user, orderReferenceId, headers }))
+ .to.eventually.be.rejected.and.to.eql({
+ httpCode: 401,
+ message: i18n.t('groupPolicyCannotGetGems'),
+ name: 'NotAuthorized',
+ });
user.canGetGems.restore();
});
it('should gift gems', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
await receivingUser.save();
- let gift = {
+ const gift = {
type: 'gems',
uuid: receivingUser._id,
gems: {
@@ -160,16 +164,18 @@ describe('Amazon Payments - Checkout', () => {
},
};
amount = 16 / 4;
- await amzLib.checkout({gift, user, orderReferenceId, headers});
+ await amzLib.checkout({
+ gift, user, orderReferenceId, headers,
+ });
expectBuyGemsStub(amzLib.constants.PAYMENT_METHOD_GIFT, gift);
expectAmazonStubs();
});
it('should gift a subscription', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
- let gift = {
+ const gift = {
type: 'subscription',
subscription: {
key: subKey,
@@ -178,7 +184,9 @@ describe('Amazon Payments - Checkout', () => {
};
amount = common.content.subscriptionBlocks[subKey].price;
- await amzLib.checkout({user, orderReferenceId, headers, gift});
+ await amzLib.checkout({
+ user, orderReferenceId, headers, gift,
+ });
gift.member = receivingUser;
expect(paymentCreateSubscritionStub).to.be.calledOnce;
diff --git a/test/api/unit/libs/payments/amazon/subscribe.test.js b/test/api/unit/libs/payments/amazon/subscribe.test.js
index d42c80d96c..03cef6b0bc 100644
--- a/test/api/unit/libs/payments/amazon/subscribe.test.js
+++ b/test/api/unit/libs/payments/amazon/subscribe.test.js
@@ -2,18 +2,19 @@ import cc from 'coupon-code';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('Amazon Payments - Subscribe', () => {
const subKey = 'basic_3mo';
- let user, group, amount, billingAgreementId, sub, coupon, groupId, headers;
+ let user; let group; let amount; let billingAgreementId; let sub; let coupon; let groupId; let
+ headers;
let amazonSetBillingAgreementDetailsSpy;
let amazonConfirmBillingAgreementSpy;
let amazonAuthorizeOnBillingAgreementSpy;
@@ -60,7 +61,7 @@ describe('Amazon Payments - Subscribe', () => {
sinon.stub(common, 'uuid').returns('uuid-generated');
});
- afterEach(function () {
+ afterEach(() => {
amzLib.setBillingAgreementDetails.restore();
amzLib.confirmBillingAgreement.restore();
amzLib.authorizeOnBillingAgreement.restore();
@@ -168,7 +169,7 @@ describe('Amazon Payments - Subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
@@ -195,9 +196,9 @@ describe('Amazon Payments - Subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
- let updatedCouponModel = await couponModel.save();
+ const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);
diff --git a/test/api/unit/libs/payments/amazon/upgrade-groupplan.test.js b/test/api/unit/libs/payments/amazon/upgrade-groupplan.test.js
index f846738acc..b47ed59257 100644
--- a/test/api/unit/libs/payments/amazon/upgrade-groupplan.test.js
+++ b/test/api/unit/libs/payments/amazon/upgrade-groupplan.test.js
@@ -2,16 +2,17 @@ import uuid from 'uuid';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
describe('#upgradeGroupPlan', () => {
- let spy, data, user, group, uuidString;
+ let spy; let data; let user; let group; let
+ uuidString;
- beforeEach(async function () {
+ beforeEach(async () => {
user = new User();
user.profile.name = 'sender';
@@ -46,7 +47,7 @@ describe('#upgradeGroupPlan', () => {
data.sub.quantity = 3;
});
- afterEach(function () {
+ afterEach(() => {
amzLib.authorizeOnBillingAgreement.restore();
uuid.v4.restore();
});
@@ -55,7 +56,7 @@ describe('#upgradeGroupPlan', () => {
data.paymentMethod = amzLib.constants.PAYMENT_METHOD;
await payments.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
updatedGroup.memberCount += 1;
await updatedGroup.save();
diff --git a/test/api/unit/libs/payments/apple.test.js b/test/api/unit/libs/payments/apple.test.js
index 10029b6c3b..82fea35eec 100644
--- a/test/api/unit/libs/payments/apple.test.js
+++ b/test/api/unit/libs/payments/apple.test.js
@@ -1,21 +1,22 @@
/* eslint-disable camelcase */
-import iapModule from '../../../../../website/server/libs/inAppPurchases';
+import moment from 'moment';
import payments from '../../../../../website/server/libs/payments/payments';
import applePayments from '../../../../../website/server/libs/payments/apple';
import iap from '../../../../../website/server/libs/inAppPurchases';
-import {model as User} from '../../../../../website/server/models/user';
+import { model as User } from '../../../../../website/server/models/user';
import common from '../../../../../website/common';
-import moment from 'moment';
-import {mockFindById, restoreFindById} from '../../../../helpers/mongoose.helper';
+import { mockFindById, restoreFindById } from '../../../../helpers/mongoose.helper';
-const i18n = common.i18n;
+const { i18n } = common;
-describe('Apple Payments', () => {
- let subKey = 'basic_3mo';
+describe('Apple Payments', () => {
+ const subKey = 'basic_3mo';
describe('verifyGemPurchase', () => {
- let sku, user, token, receipt, headers;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentBuyGemsStub, iapGetPurchaseDataStub;
+ let sku; let user; let token; let receipt; let
+ headers;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let paymentBuyGemsStub; let
+ iapGetPurchaseDataStub;
beforeEach(() => {
token = 'testToken';
@@ -24,33 +25,34 @@ describe('Apple Payments', () => {
receipt = `{"token": "${token}", "productId": "${sku}"}`;
headers = {};
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{productId: 'com.habitrpg.ios.Habitica.21gems',
- transactionId: token,
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{
+ productId: 'com.habitrpg.ios.Habitica.21gems',
+ transactionId: token,
}]);
paymentBuyGemsStub = sinon.stub(payments, 'buyGems').resolves({});
});
afterEach(() => {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
- iapModule.getPurchaseData.restore();
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
+ iap.getPurchaseData.restore();
payments.buyGems.restore();
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
- await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
+ await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -60,9 +62,9 @@ describe('Apple Payments', () => {
it('should throw an error if getPurchaseData is invalid', async () => {
iapGetPurchaseDataStub.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData').returns([]);
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData').returns([]);
- await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
+ await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -72,7 +74,7 @@ describe('Apple Payments', () => {
it('errors if the user cannot purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
- await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
+ await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -85,12 +87,13 @@ describe('Apple Payments', () => {
it('errors if amount does not exist', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
iapGetPurchaseDataStub.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{productId: 'badProduct',
- transactionId: token,
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{
+ productId: 'badProduct',
+ transactionId: token,
}]);
- await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
+ await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -126,13 +129,14 @@ describe('Apple Payments', () => {
gemsCanPurchase.forEach(gemTest => {
it(`purchases ${gemTest.productId} gems`, async () => {
iapGetPurchaseDataStub.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{productId: gemTest.productId,
- transactionId: token,
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{
+ productId: gemTest.productId,
+ transactionId: token,
}]);
sinon.stub(user, 'canGetGems').resolves(true);
- await applePayments.verifyGemPurchase({user, receipt, headers});
+ await applePayments.verifyGemPurchase({ user, receipt, headers });
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -160,13 +164,16 @@ describe('Apple Payments', () => {
mockFindById(receivingUser);
iapGetPurchaseDataStub.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{productId: gemsCanPurchase[0].productId,
- transactionId: token,
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{
+ productId: gemsCanPurchase[0].productId,
+ transactionId: token,
}]);
- const gift = {uuid: receivingUser._id};
- await applePayments.verifyGemPurchase({user, gift, receipt, headers});
+ const gift = { uuid: receivingUser._id };
+ await applePayments.verifyGemPurchase({
+ user, gift, receipt, headers,
+ });
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -187,8 +194,11 @@ describe('Apple Payments', () => {
});
describe('subscribe', () => {
- let sub, sku, user, token, receipt, headers, nextPaymentProcessing;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentsCreateSubscritionStub, iapGetPurchaseDataStub;
+ let sub; let sku; let user; let token; let receipt; let headers; let
+ nextPaymentProcessing;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub;
+ let paymentsCreateSubscritionStub; let
+ iapGetPurchaseDataStub;
beforeEach(() => {
sub = common.content.subscriptionBlocks[subKey];
@@ -197,25 +207,25 @@ describe('Apple Payments', () => {
token = 'test-token';
headers = {};
receipt = `{"token": "${token}"}`;
- nextPaymentProcessing = moment.utc().add({days: 2});
+ nextPaymentProcessing = moment.utc().add({ days: 2 });
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
- expirationDate: moment.utc().subtract({day: 1}).toDate(),
+ expirationDate: moment.utc().subtract({ day: 1 }).toDate(),
productId: sku,
transactionId: token,
}, {
- expirationDate: moment.utc().add({day: 1}).toDate(),
+ expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: 'wrongsku',
transactionId: token,
}, {
- expirationDate: moment.utc().add({day: 1}).toDate(),
+ expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: sku,
transactionId: token,
}]);
@@ -223,10 +233,10 @@ describe('Apple Payments', () => {
});
afterEach(() => {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
- iapModule.getPurchaseData.restore();
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
+ iap.getPurchaseData.restore();
if (payments.createSubscription.restore) payments.createSubscription.restore();
});
@@ -240,8 +250,8 @@ describe('Apple Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(applePayments.subscribe(sku, user, receipt, headers, nextPaymentProcessing))
@@ -272,10 +282,10 @@ describe('Apple Payments', () => {
];
subOptions.forEach(option => {
it(`creates a user subscription for ${option.sku}`, async () => {
- iapModule.getPurchaseData.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
+ iap.getPurchaseData.restore();
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
- expirationDate: moment.utc().add({day: 1}).toDate(),
+ expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: option.sku,
transactionId: token,
}]);
@@ -319,8 +329,10 @@ describe('Apple Payments', () => {
});
describe('cancelSubscribe ', () => {
- let user, token, receipt, headers, customerId, expirationDate;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, iapGetPurchaseDataStub, paymentCancelSubscriptionSpy;
+ let user; let token; let receipt; let headers; let customerId; let
+ expirationDate;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let iapGetPurchaseDataStub; let
+ paymentCancelSubscriptionSpy;
beforeEach(async () => {
token = 'test-token';
@@ -329,15 +341,15 @@ describe('Apple Payments', () => {
customerId = 'test-customerId';
expirationDate = moment.utc();
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({
expirationDate,
});
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{expirationDate: expirationDate.toDate()}]);
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{ expirationDate: expirationDate.toDate() }]);
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
user = new User();
@@ -350,11 +362,11 @@ describe('Apple Payments', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
- afterEach(function () {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
- iapModule.getPurchaseData.restore();
+ afterEach(() => {
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
+ iap.getPurchaseData.restore();
payments.cancelSubscription.restore();
});
@@ -370,9 +382,9 @@ describe('Apple Payments', () => {
});
it('should throw an error if subscription is still valid', async () => {
- iapModule.getPurchaseData.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{expirationDate: expirationDate.add({day: 1}).toDate()}]);
+ iap.getPurchaseData.restore();
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{ expirationDate: expirationDate.add({ day: 1 }).toDate() }]);
await expect(applePayments.cancelSubscribe(user, headers))
.to.eventually.be.rejected.and.to.eql({
@@ -383,8 +395,8 @@ describe('Apple Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(applePayments.cancelSubscribe(user, headers))
diff --git a/test/api/unit/libs/payments/google.test.js b/test/api/unit/libs/payments/google.test.js
index c80639957c..c8383fa828 100644
--- a/test/api/unit/libs/payments/google.test.js
+++ b/test/api/unit/libs/payments/google.test.js
@@ -1,21 +1,22 @@
/* eslint-disable camelcase */
-import iapModule from '../../../../../website/server/libs/inAppPurchases';
+import moment from 'moment';
import payments from '../../../../../website/server/libs/payments/payments';
import googlePayments from '../../../../../website/server/libs/payments/google';
import iap from '../../../../../website/server/libs/inAppPurchases';
-import {model as User} from '../../../../../website/server/models/user';
+import { model as User } from '../../../../../website/server/models/user';
import common from '../../../../../website/common';
-import moment from 'moment';
-import {mockFindById, restoreFindById} from '../../../../helpers/mongoose.helper';
+import { mockFindById, restoreFindById } from '../../../../helpers/mongoose.helper';
-const i18n = common.i18n;
+const { i18n } = common;
-describe('Google Payments', () => {
- let subKey = 'basic_3mo';
+describe('Google Payments', () => {
+ const subKey = 'basic_3mo';
describe('verifyGemPurchase', () => {
- let sku, user, token, receipt, signature, headers;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentBuyGemsStub;
+ let sku; let user; let token; let receipt; let signature; let
+ headers;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let
+ paymentBuyGemsStub;
beforeEach(() => {
sku = 'com.habitrpg.android.habitica.iap.21gems';
@@ -24,28 +25,30 @@ describe('Google Payments', () => {
signature = '';
headers = {};
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
paymentBuyGemsStub = sinon.stub(payments, 'buyGems').resolves({});
});
afterEach(() => {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
payments.buyGems.restore();
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
- await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
+ await expect(googlePayments.verifyGemPurchase({
+ user, receipt, signature, headers,
+ }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -56,7 +59,9 @@ describe('Google Payments', () => {
it('should throw an error if productId is invalid', async () => {
receipt = `{"token": "${token}", "productId": "invalid"}`;
- await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
+ await expect(googlePayments.verifyGemPurchase({
+ user, receipt, signature, headers,
+ }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -67,7 +72,9 @@ describe('Google Payments', () => {
it('should throw an error if user cannot purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
- await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
+ await expect(googlePayments.verifyGemPurchase({
+ user, receipt, signature, headers,
+ }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -79,7 +86,9 @@ describe('Google Payments', () => {
it('purchases gems', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
- await googlePayments.verifyGemPurchase({user, receipt, signature, headers});
+ await googlePayments.verifyGemPurchase({
+ user, receipt, signature, headers,
+ });
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -107,8 +116,10 @@ describe('Google Payments', () => {
mockFindById(receivingUser);
- const gift = {uuid: receivingUser._id};
- await googlePayments.verifyGemPurchase({user, gift, receipt, signature, headers});
+ const gift = { uuid: receivingUser._id };
+ await googlePayments.verifyGemPurchase({
+ user, gift, receipt, signature, headers,
+ });
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -131,8 +142,10 @@ describe('Google Payments', () => {
});
describe('subscribe', () => {
- let sub, sku, user, token, receipt, signature, headers, nextPaymentProcessing;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentsCreateSubscritionStub;
+ let sub; let sku; let user; let token; let receipt; let signature; let headers; let
+ nextPaymentProcessing;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let
+ paymentsCreateSubscritionStub;
beforeEach(() => {
sub = common.content.subscriptionBlocks[subKey];
@@ -142,30 +155,31 @@ describe('Google Payments', () => {
headers = {};
receipt = `{"token": "${token}"}`;
signature = '';
- nextPaymentProcessing = moment.utc().add({days: 2});
+ nextPaymentProcessing = moment.utc().add({ days: 2 });
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
paymentsCreateSubscritionStub = sinon.stub(payments, 'createSubscription').resolves({});
});
afterEach(() => {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
payments.createSubscription.restore();
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
- await expect(googlePayments.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
+ await expect(googlePayments
+ .subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -176,7 +190,8 @@ describe('Google Payments', () => {
it('should throw an error if sku is invalid', async () => {
sku = 'invalid';
- await expect(googlePayments.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
+ await expect(googlePayments
+ .subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -203,15 +218,17 @@ describe('Google Payments', () => {
paymentMethod: googlePayments.constants.PAYMENT_METHOD_GOOGLE,
sub,
headers,
- additionalData: {data: receipt, signature},
+ additionalData: { data: receipt, signature },
nextPaymentProcessing,
});
});
});
describe('cancelSubscribe ', () => {
- let user, token, receipt, signature, headers, customerId, expirationDate;
- let iapSetupStub, iapValidateStub, iapIsValidatedStub, iapGetPurchaseDataStub, paymentCancelSubscriptionSpy;
+ let user; let token; let receipt; let signature; let headers; let customerId; let
+ expirationDate;
+ let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let iapGetPurchaseDataStub; let
+ paymentCancelSubscriptionSpy;
beforeEach(async () => {
token = 'test-token';
@@ -221,15 +238,15 @@ describe('Google Payments', () => {
customerId = 'test-customerId';
expirationDate = moment.utc();
- iapSetupStub = sinon.stub(iapModule, 'setup')
+ iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
- iapValidateStub = sinon.stub(iapModule, 'validate')
+ iapValidateStub = sinon.stub(iap, 'validate')
.resolves({
expirationDate,
});
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{expirationDate: expirationDate.toDate()}]);
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{ expirationDate: expirationDate.toDate() }]);
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
user = new User();
@@ -237,16 +254,16 @@ describe('Google Payments', () => {
user.purchased.plan.customerId = customerId;
user.purchased.plan.paymentMethod = googlePayments.constants.PAYMENT_METHOD_GOOGLE;
user.purchased.plan.planId = subKey;
- user.purchased.plan.additionalData = {data: receipt, signature};
+ user.purchased.plan.additionalData = { data: receipt, signature };
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
- afterEach(function () {
- iapModule.setup.restore();
- iapModule.validate.restore();
- iapModule.isValidated.restore();
- iapModule.getPurchaseData.restore();
+ afterEach(() => {
+ iap.setup.restore();
+ iap.validate.restore();
+ iap.isValidated.restore();
+ iap.getPurchaseData.restore();
payments.cancelSubscription.restore();
});
@@ -262,9 +279,9 @@ describe('Google Payments', () => {
});
it('should throw an error if subscription is still valid', async () => {
- iapModule.getPurchaseData.restore();
- iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
- .returns([{expirationDate: expirationDate.add({day: 1}).toDate()}]);
+ iap.getPurchaseData.restore();
+ iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
+ .returns([{ expirationDate: expirationDate.add({ day: 1 }).toDate() }]);
await expect(googlePayments.cancelSubscribe(user, headers))
.to.eventually.be.rejected.and.to.eql({
@@ -275,8 +292,8 @@ describe('Google Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
- iapModule.isValidated.restore();
- iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
+ iap.isValidated.restore();
+ iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(googlePayments.cancelSubscribe(user, headers))
diff --git a/test/api/unit/libs/payments/group-plans/group-payments-cancel.test.js b/test/api/unit/libs/payments/group-plans/group-payments-cancel.test.js
index d89b3cc32d..ccbe63f328 100644
--- a/test/api/unit/libs/payments/group-plans/group-payments-cancel.test.js
+++ b/test/api/unit/libs/payments/group-plans/group-payments-cancel.test.js
@@ -6,11 +6,12 @@ import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import i18n from '../../../../../../website/common/script/i18n';
describe('Canceling a subscription for group', () => {
- let plan, group, user, data;
+ let plan; let group; let user; let
+ data;
beforeEach(async () => {
user = new User();
@@ -67,9 +68,9 @@ describe('Canceling a subscription for group', () => {
data.groupId = group._id;
await api.cancelSubscription(data);
- let now = new Date();
- let updatedGroup = await Group.findById(group._id).exec();
- let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const updatedGroup = await Group.findById(group._id).exec();
+ const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(29, 30); // 1 month +/- 1 days
});
@@ -81,9 +82,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let updatedGroup = await Group.findById(group._id).exec();
- let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const updatedGroup = await Group.findById(group._id).exec();
+ const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(89, 90); // 3 months +/- 1 days
});
@@ -95,9 +96,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let updatedGroup = await Group.findById(group._id).exec();
- let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const updatedGroup = await Group.findById(group._id).exec();
+ const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(38, 39); // should be about 1 month + 1/3 month
});
@@ -108,9 +109,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let updatedGroup = await Group.findById(group._id).exec();
- let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const updatedGroup = await Group.findById(group._id).exec();
+ const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -122,7 +123,7 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.eql(0);
});
@@ -134,12 +135,12 @@ describe('Canceling a subscription for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(user._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-cancel-subscription');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
- {name: 'GROUP_NAME', content: group.name},
+ { name: 'GROUP_NAME', content: group.name },
]);
});
it('prevents non group leader from managing subscription', async () => {
- let groupMember = new User();
+ const groupMember = new User();
data.user = groupMember;
data.groupId = group._id;
@@ -160,7 +161,7 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
- let newLeader = new User();
+ const newLeader = new User();
updatedGroup.leader = newLeader._id;
await updatedGroup.save();
@@ -192,15 +193,15 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let now = new Date();
+ const now = new Date();
now.setHours(0, 0, 0, 0);
- let updatedLeader = await User.findById(user._id).exec();
- let daysTillTermination = moment(updatedLeader.purchased.plan.dateTerminated).diff(now, 'days');
+ const updatedLeader = await User.findById(user._id).exec();
+ const daysTillTermination = moment(updatedLeader.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(2, 3); // only a few days
});
it('sends an email to members of group', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.guilds.push(group._id);
await recipient.save();
@@ -214,8 +215,8 @@ describe('Canceling a subscription for group', () => {
expect(sender.sendTxn.thirdCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.thirdCall.args[1]).to.equal('group-member-cancel');
expect(sender.sendTxn.thirdCall.args[2]).to.eql([
- {name: 'LEADER', content: user.profile.name},
- {name: 'GROUP_NAME', content: group.name},
+ { name: 'LEADER', content: user.profile.name },
+ { name: 'GROUP_NAME', content: group.name },
]);
});
@@ -223,7 +224,7 @@ describe('Canceling a subscription for group', () => {
plan.key = 'basic_earned';
plan.customerId = api.constants.UNLIMITED_CUSTOMER_ID;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -233,12 +234,12 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
- let updatedLeader = await User.findById(user._id).exec();
+ const updatedLeader = await User.findById(user._id).exec();
expect(updatedLeader.purchased.plan.dateTerminated).to.not.exist;
});
it('does not cancel a user subscription if they are still in another active group plan', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -252,10 +253,10 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
- let firstDateCreated = updatedUser.purchased.plan.dateCreated;
- let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
+ const firstDateCreated = updatedUser.purchased.plan.dateCreated;
+ const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
- let group2 = generateGroup({
+ const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -291,10 +292,10 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(user._id).exec();
- let firstDateCreated = updatedUser.purchased.plan.dateCreated;
- let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
+ const firstDateCreated = updatedUser.purchased.plan.dateCreated;
+ const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
- let group2 = generateGroup({
+ const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
diff --git a/test/api/unit/libs/payments/group-plans/group-payments-create.test.js b/test/api/unit/libs/payments/group-plans/group-payments-create.test.js
index b16716cd2e..ca6c921f80 100644
--- a/test/api/unit/libs/payments/group-plans/group-payments-create.test.js
+++ b/test/api/unit/libs/payments/group-plans/group-payments-create.test.js
@@ -11,7 +11,7 @@ import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
describe('Purchasing a group plan for group', () => {
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE = 'Google_subscription';
@@ -19,10 +19,11 @@ describe('Purchasing a group plan for group', () => {
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL = 'normal_subscription';
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE = 'no_subscription';
- let plan, group, user, data;
- let stripe = stripeModule('test');
- let groupLeaderName = 'sender';
- let groupName = 'test group';
+ let plan; let group; let user; let
+ data;
+ const stripe = stripeModule('test');
+ const groupLeaderName = 'sender';
+ const groupName = 'test group';
beforeEach(async () => {
user = new User();
@@ -68,14 +69,17 @@ describe('Purchasing a group plan for group', () => {
},
};
- let subscriptionId = 'subId';
+ const subscriptionId = 'subId';
sinon.stub(stripe.customers, 'del').resolves({});
- let currentPeriodEndTimeStamp = moment().add(3, 'months').unix();
+ const currentPeriodEndTimeStamp = moment().add(3, 'months').unix();
sinon.stub(stripe.customers, 'retrieve')
.resolves({
subscriptions: {
- data: [{id: subscriptionId, current_period_end: currentPeriodEndTimeStamp}], // eslint-disable-line camelcase
+ data: [{
+ id: subscriptionId,
+ current_period_end: currentPeriodEndTimeStamp,
+ }], // eslint-disable-line camelcase
},
});
@@ -95,7 +99,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedGroup.purchased.plan.customerId).to.eql('customer-id');
@@ -126,7 +130,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.within(1.9, 2);
});
@@ -139,7 +143,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.eql(0);
});
@@ -150,7 +154,7 @@ describe('Purchasing a group plan for group', () => {
data.groupId = group._id;
await api.createSubscription(data);
- let updatedLeader = await User.findById(user._id).exec();
+ const updatedLeader = await User.findById(user._id).exec();
expect(updatedLeader.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedLeader.purchased.plan.customerId).to.eql('group-plan');
@@ -166,7 +170,7 @@ describe('Purchasing a group plan for group', () => {
});
it('sends an email to member of group who was not a subscriber', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.guilds.push(group._id);
await recipient.save();
@@ -179,9 +183,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
- {name: 'LEADER', content: user.profile.name},
- {name: 'GROUP_NAME', content: group.name},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE},
+ { name: 'LEADER', content: user.profile.name },
+ { name: 'GROUP_NAME', content: group.name },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE },
]);
// confirm that the other email sent is appropriate:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -189,7 +193,7 @@ describe('Purchasing a group plan for group', () => {
});
it('sends one email to subscribed member of group, stating subscription is cancelled (Stripe)', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -205,9 +209,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
- {name: 'LEADER', content: user.profile.name},
- {name: 'GROUP_NAME', content: group.name},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
+ { name: 'LEADER', content: user.profile.name },
+ { name: 'GROUP_NAME', content: group.name },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -218,11 +222,11 @@ describe('Purchasing a group plan for group', () => {
sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
- BillingAgreementStatus: {State: 'Closed'},
+ BillingAgreementStatus: { State: 'Closed' },
},
});
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = amzLib.constants.PAYMENT_METHOD;
@@ -238,9 +242,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
- {name: 'LEADER', content: user.profile.name},
- {name: 'GROUP_NAME', content: group.name},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
+ { name: 'LEADER', content: user.profile.name },
+ { name: 'GROUP_NAME', content: group.name },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -259,7 +263,7 @@ describe('Purchasing a group plan for group', () => {
},
});
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = paypalPayments.constants.PAYMENT_METHOD;
@@ -275,9 +279,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
- {name: 'LEADER', content: user.profile.name},
- {name: 'GROUP_NAME', content: group.name},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
+ { name: 'LEADER', content: user.profile.name },
+ { name: 'GROUP_NAME', content: group.name },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -292,7 +296,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.GOOGLE_PAYMENT_METHOD;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -310,9 +314,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.args[1][0]._id).to.equal(recipient._id);
expect(sender.sendTxn.args[1][1]).to.equal('group-member-join');
expect(sender.sendTxn.args[1][2]).to.eql([
- {name: 'LEADER', content: groupLeaderName},
- {name: 'GROUP_NAME', content: groupName},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE},
+ { name: 'LEADER', content: groupLeaderName },
+ { name: 'GROUP_NAME', content: groupName },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE },
]);
expect(sender.sendTxn.args[2][0]._id).to.equal(group.leader);
expect(sender.sendTxn.args[2][1]).to.equal('group-member-join');
@@ -325,7 +329,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.IOS_PAYMENT_METHOD;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -343,9 +347,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.args[1][0]._id).to.equal(recipient._id);
expect(sender.sendTxn.args[1][1]).to.equal('group-member-join');
expect(sender.sendTxn.args[1][2]).to.eql([
- {name: 'LEADER', content: groupLeaderName},
- {name: 'GROUP_NAME', content: groupName},
- {name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_IOS},
+ { name: 'LEADER', content: groupLeaderName },
+ { name: 'GROUP_NAME', content: groupName },
+ { name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_IOS },
]);
expect(sender.sendTxn.args[2][0]._id).to.equal(group.leader);
expect(sender.sendTxn.args[2][1]).to.equal('group-member-join');
@@ -354,7 +358,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing gift subscription', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -378,7 +382,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -392,7 +396,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing multi-month gift subscription', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -414,7 +418,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -428,7 +432,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing recurring subscription (Stripe)', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -450,11 +454,11 @@ describe('Purchasing a group plan for group', () => {
sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
- BillingAgreementStatus: {State: 'Closed'},
+ BillingAgreementStatus: { State: 'Closed' },
},
});
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = amzLib.constants.PAYMENT_METHOD;
@@ -470,7 +474,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(3, 5);
});
@@ -485,7 +489,7 @@ describe('Purchasing a group plan for group', () => {
},
});
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = paypalPayments.constants.PAYMENT_METHOD;
@@ -500,7 +504,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
paypalPayments.paypalBillingAgreementGet.restore();
@@ -511,7 +515,7 @@ describe('Purchasing a group plan for group', () => {
it('adds months to members with existing recurring subscription (iOS)');
it('adds months to members who already cancelled but not yet terminated recurring subscription', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -527,13 +531,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
});
it('adds months to members who already cancelled but not yet terminated group plan subscription', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = api.constants.GROUP_PLAN_PAYMENT_METHOD;
@@ -550,12 +554,12 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(3, 4);
});
it('resets date terminated if user has old subscription', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -570,13 +574,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.dateTerminated).to.not.exist;
});
it('adds months to members with existing recurring subscription and includes existing extraMonths', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -591,13 +595,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(7, 9);
});
it('adds months to members with existing recurring subscription and ignores existing negative extraMonths', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -612,23 +616,23 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
});
it('does not override gemsBought, mysteryItems, dateCreated, and consective fields', async () => {
- let planCreatedDate = moment().toDate();
- let mysteryItem = {title: 'item'};
- let mysteryItems = [mysteryItem];
- let consecutive = {
+ const planCreatedDate = moment().toDate();
+ const mysteryItem = { title: 'item' };
+ const mysteryItems = [mysteryItem];
+ const consecutive = {
trinkets: 3,
gemCapExtra: 20,
offset: 1,
count: 13,
};
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
@@ -647,7 +651,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.gemsBought).to.equal(3);
expect(updatedUser.purchased.plan.mysteryItems[0]).to.eql(mysteryItem);
@@ -659,7 +663,7 @@ describe('Purchasing a group plan for group', () => {
});
it('does not modify a user with a group subscription when they join another group', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -673,10 +677,10 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
- let firstDateCreated = updatedUser.purchased.plan.dateCreated;
- let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
+ const firstDateCreated = updatedUser.purchased.plan.dateCreated;
+ const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
- let group2 = generateGroup({
+ const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -703,7 +707,7 @@ describe('Purchasing a group plan for group', () => {
});
it('does not remove a user who is in two groups plans and leaves one', async () => {
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -717,10 +721,10 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
- let firstDateCreated = updatedUser.purchased.plan.dateCreated;
- let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
+ const firstDateCreated = updatedUser.purchased.plan.dateCreated;
+ const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
- let group2 = generateGroup({
+ const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -733,7 +737,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
await updatedGroup.leave(recipient);
updatedUser = await User.findById(recipient._id).exec();
@@ -753,7 +757,7 @@ describe('Purchasing a group plan for group', () => {
plan.key = 'basic_earned';
plan.customerId = api.constants.UNLIMITED_CUSTOMER_ID;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -765,7 +769,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql(api.constants.UNLIMITED_CUSTOMER_ID);
@@ -782,7 +786,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.GOOGLE_PAYMENT_METHOD;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -794,7 +798,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql('random');
@@ -811,7 +815,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.IOS_PAYMENT_METHOD;
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -823,7 +827,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql('random');
@@ -841,7 +845,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = api.constants.GROUP_PLAN_CUSTOMER_ID;
plan.dateTerminated = moment().add(1, 'months');
- let recipient = new User();
+ const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -853,7 +857,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
- let updatedUser = await User.findById(recipient._id).exec();
+ const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql(api.constants.GROUP_PLAN_CUSTOMER_ID);
diff --git a/test/api/unit/libs/payments/paymentHelpers.js b/test/api/unit/libs/payments/paymentHelpers.js
index 6ea70a5504..7bed28e44b 100644
--- a/test/api/unit/libs/payments/paymentHelpers.js
+++ b/test/api/unit/libs/payments/paymentHelpers.js
@@ -1,7 +1,7 @@
import { model as User } from '../../../../../website/server/models/user';
-export async function createNonLeaderGroupMember (group) {
- let nonLeader = new User();
+export async function createNonLeaderGroupMember (group) { // eslint-disable-line import/prefer-default-export, max-len
+ const nonLeader = new User();
nonLeader.guilds.push(group._id);
- return await nonLeader.save();
+ return nonLeader.save();
}
diff --git a/test/api/unit/libs/payments/payments.test.js b/test/api/unit/libs/payments/payments.test.js
index 48b05d4cd5..76d0d3d00e 100644
--- a/test/api/unit/libs/payments/payments.test.js
+++ b/test/api/unit/libs/payments/payments.test.js
@@ -8,10 +8,11 @@ import { model as User } from '../../../../../website/server/models/user';
import { translate as t } from '../../../../helpers/api-integration/v3';
import {
generateGroup,
-} from '../../../../helpers/api-unit.helper.js';
+} from '../../../../helpers/api-unit.helper';
describe('payments/index', () => {
- let user, group, data, plan;
+ let user; let group; let data; let
+ plan;
beforeEach(async () => {
user = new User();
@@ -102,7 +103,7 @@ describe('payments/index', () => {
});
it('does not set negative extraMonths if plan has past dateTerminated date', async () => {
- let dateTerminated = moment().subtract(2, 'months').toDate();
+ const dateTerminated = moment().subtract(2, 'months').toDate();
recipient.purchased.plan.dateTerminated = dateTerminated;
await api.createSubscription(data);
@@ -120,7 +121,7 @@ describe('payments/index', () => {
});
it('adds to date terminated for an existing plan with a future terminated date', async () => {
- let dateTerminated = moment().add(1, 'months').toDate();
+ const dateTerminated = moment().add(1, 'months').toDate();
recipient.purchased.plan = plan;
recipient.purchased.plan.dateTerminated = dateTerminated;
@@ -130,7 +131,7 @@ describe('payments/index', () => {
});
it('replaces date terminated for an account with a past terminated date', async () => {
- let dateTerminated = moment().subtract(1, 'months').toDate();
+ const dateTerminated = moment().subtract(1, 'months').toDate();
recipient.purchased.plan.dateTerminated = dateTerminated;
await api.createSubscription(data);
@@ -208,18 +209,21 @@ describe('payments/index', () => {
it('sends a private message about the gift', async () => {
await api.createSubscription(data);
- let msg = '\`Hello recipient, sender has sent you 3 months of subscription!\`';
+ const msg = '`Hello recipient, sender has sent you 3 months of subscription!`';
expect(user.sendMessage).to.be.calledOnce;
- expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
+ expect(user.sendMessage).to.be.calledWith(
+ recipient,
+ { receiverMsg: msg, senderMsg: msg, save: false },
+ );
});
it('sends an email about the gift', async () => {
await api.createSubscription(data);
expect(sender.sendTxn).to.be.calledWith(recipient, 'gifted-subscription', [
- {name: 'GIFTER', content: 'sender'},
- {name: 'X_MONTHS_SUBSCRIPTION', content: 3},
+ { name: 'GIFTER', content: 'sender' },
+ { name: 'X_MONTHS_SUBSCRIPTION', content: 3 },
]);
});
@@ -416,8 +420,8 @@ describe('payments/index', () => {
context('Mystery Items', () => {
it('awards mystery items when within the timeframe for a mystery item', async () => {
- let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
- let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
+ const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
+ const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
@@ -437,7 +441,7 @@ describe('payments/index', () => {
it('does not awards mystery items when not within the timeframe for a mystery item', async () => {
const noMysteryItemTimeframe = 1462183920000; // May 2nd 2016
- let fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
+ const fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
await api.createSubscription(data);
@@ -449,7 +453,7 @@ describe('payments/index', () => {
it('does not add a notification for mystery items if none was awarded', async () => {
const noMysteryItemTimeframe = 1462183920000; // May 2nd 2016
- let fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
+ const fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
await api.createSubscription(data);
@@ -461,9 +465,9 @@ describe('payments/index', () => {
});
it('does not award mystery item when user already owns the item', async () => {
- let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
- let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
- let mayMysteryItem = 'armor_mystery_201605';
+ const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
+ const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
+ const mayMysteryItem = 'armor_mystery_201605';
user.items.gear.owned[mayMysteryItem] = true;
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
@@ -477,9 +481,9 @@ describe('payments/index', () => {
});
it('does not award mystery item when user already has the item in the mystery box', async () => {
- let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
- let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
- let mayMysteryItem = 'armor_mystery_201605';
+ const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
+ const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
+ const mayMysteryItem = 'armor_mystery_201605';
user.purchased.plan.mysteryItems = [mayMysteryItem];
sandbox.spy(user.purchased.plan.mysteryItems, 'push');
@@ -504,8 +508,8 @@ describe('payments/index', () => {
it('adds a month termination date by default', async () => {
await api.cancelSubscription(data);
- let now = new Date();
- let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(29, 30); // 1 month +/- 1 days
});
@@ -515,8 +519,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(89, 90); // 3 months +/- 1 days
});
@@ -526,8 +530,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(38, 39); // should be about 1 month + 1/3 month
});
@@ -537,8 +541,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -549,8 +553,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
- let now = new Date();
- let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
+ const now = new Date();
+ const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -641,9 +645,10 @@ describe('payments/index', () => {
it('sends a message from purchaser to recipient', async () => {
await api.buyGems(data);
- let msg = '\`Hello recipient, sender has sent you 4 gems!\`';
+ const msg = '`Hello recipient, sender has sent you 4 gems!`';
- expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
+ expect(user.sendMessage).to.be
+ .calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
});
it('sends a message from purchaser to recipient wtih custom message', async () => {
@@ -652,7 +657,8 @@ describe('payments/index', () => {
await api.buyGems(data);
const msg = `\`Hello recipient, sender has sent you 4 gems!\` ${data.gift.message}`;
- expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
+ expect(user.sendMessage).to.be
+ .calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
});
it('sends a push notification if user did not gift to self', async () => {
@@ -671,8 +677,8 @@ describe('payments/index', () => {
});
await api.buyGems(data);
- let [recipientsMessageContent, sendersMessageContent] = ['en', 'en'].map((lang) => {
- let messageContent = t('giftedGemsFull', {
+ const [recipientsMessageContent, sendersMessageContent] = ['en', 'en'].map(lang => {
+ const messageContent = t('giftedGemsFull', {
username: recipient.profile.name,
sender: user.profile.name,
gemAmount: data.gift.gems.amount,
@@ -681,7 +687,10 @@ describe('payments/index', () => {
return `\`${messageContent}\``;
});
- expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: recipientsMessageContent, senderMsg: sendersMessageContent, save: false });
+ expect(user.sendMessage).to.be.calledWith(
+ recipient,
+ { receiverMsg: recipientsMessageContent, senderMsg: sendersMessageContent, save: false },
+ );
});
});
});
@@ -693,7 +702,7 @@ describe('payments/index', () => {
await api.addSubToGroupUser(user, group);
- let updatedUser = await User.findById(user._id).exec();
+ const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -709,17 +718,17 @@ describe('payments/index', () => {
it('awards the Royal Purple Jackalope pet', async () => {
await api.addSubToGroupUser(user, group);
- let updatedUser = await User.findById(user._id).exec();
+ const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.items.pets['Jackalope-RoyalPurple']).to.eql(5);
});
it('saves previously unused Mystery Items and Hourglasses for an expired subscription', async () => {
- let planExpirationDate = new Date();
+ const planExpirationDate = new Date();
planExpirationDate.setDate(planExpirationDate.getDate() - 2);
- let mysteryItem = 'item';
- let mysteryItems = [mysteryItem];
- let consecutive = {
+ const mysteryItem = 'item';
+ const mysteryItems = [mysteryItem];
+ const consecutive = {
trinkets: 3,
};
@@ -735,7 +744,7 @@ describe('payments/index', () => {
await user.save();
await api.addSubToGroupUser(user, group);
- let updatedUser = await User.findById(user._id).exec();
+ const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.purchased.plan.mysteryItems[0]).to.eql(mysteryItem);
expect(updatedUser.purchased.plan.consecutive.trinkets).to.equal(consecutive.trinkets);
diff --git a/test/api/unit/libs/payments/paypal/checkout-success.test.js b/test/api/unit/libs/payments/paypal/checkout-success.test.js
index 80547925b4..3c896f4128 100644
--- a/test/api/unit/libs/payments/paypal/checkout-success.test.js
+++ b/test/api/unit/libs/payments/paypal/checkout-success.test.js
@@ -5,8 +5,10 @@ import { model as User } from '../../../../../../website/server/models/user';
describe('checkout success', () => {
const subKey = 'basic_3mo';
- let user, gift, customerId, paymentId;
- let paypalPaymentExecuteStub, paymentBuyGemsStub, paymentsCreateSubscritionStub;
+ let user; let gift; let customerId; let
+ paymentId;
+ let paypalPaymentExecuteStub; let paymentBuyGemsStub; let
+ paymentsCreateSubscritionStub;
beforeEach(() => {
user = new User();
@@ -25,7 +27,9 @@ describe('checkout success', () => {
});
it('purchases gems', async () => {
- await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
+ await paypalPayments.checkoutSuccess({
+ user, gift, paymentId, customerId,
+ });
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });
@@ -38,7 +42,7 @@ describe('checkout success', () => {
});
it('gifts gems', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'gems',
@@ -48,7 +52,9 @@ describe('checkout success', () => {
},
};
- await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
+ await paypalPayments.checkoutSuccess({
+ user, gift, paymentId, customerId,
+ });
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });
@@ -62,7 +68,7 @@ describe('checkout success', () => {
});
it('gifts subscription', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'subscription',
@@ -72,7 +78,9 @@ describe('checkout success', () => {
},
};
- await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
+ await paypalPayments.checkoutSuccess({
+ user, gift, paymentId, customerId,
+ });
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });
diff --git a/test/api/unit/libs/payments/paypal/checkout.test.js b/test/api/unit/libs/payments/paypal/checkout.test.js
index 25e381bcc1..b6173f6d8e 100644
--- a/test/api/unit/libs/payments/paypal/checkout.test.js
+++ b/test/api/unit/libs/payments/paypal/checkout.test.js
@@ -6,7 +6,7 @@ import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
const BASE_URL = nconf.get('BASE_URL');
-const i18n = common.i18n;
+const { i18n } = common;
describe('checkout', () => {
const subKey = 'basic_3mo';
@@ -53,7 +53,7 @@ describe('checkout', () => {
});
it('creates a link for gem purchases', async () => {
- let link = await paypalPayments.checkout({user: new User()});
+ const link = await paypalPayments.checkout({ user: new User() });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('Habitica Gems', 5.00));
@@ -61,9 +61,9 @@ describe('checkout', () => {
});
it('should error if gem amount is too low', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
- let gift = {
+ const gift = {
type: 'gems',
gems: {
amount: 0,
@@ -71,7 +71,7 @@ describe('checkout', () => {
},
};
- await expect(paypalPayments.checkout({gift}))
+ await expect(paypalPayments.checkout({ gift }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
message: 'Amount must be at least 1.',
@@ -80,10 +80,10 @@ describe('checkout', () => {
});
it('should error if the user cannot get gems', async () => {
- let user = new User();
+ const user = new User();
sinon.stub(user, 'canGetGems').resolves(false);
- await expect(paypalPayments.checkout({user})).to.eventually.be.rejected.and.to.eql({
+ await expect(paypalPayments.checkout({ user })).to.eventually.be.rejected.and.to.eql({
httpCode: 401,
message: i18n.t('groupPolicyCannotGetGems'),
name: 'NotAuthorized',
@@ -91,9 +91,9 @@ describe('checkout', () => {
});
it('creates a link for gifting gems', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
await receivingUser.save();
- let gift = {
+ const gift = {
type: 'gems',
uuid: receivingUser._id,
gems: {
@@ -101,7 +101,7 @@ describe('checkout', () => {
},
};
- let link = await paypalPayments.checkout({gift});
+ const link = await paypalPayments.checkout({ gift });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('Habitica Gems (Gift)', '4.00'));
@@ -109,9 +109,9 @@ describe('checkout', () => {
});
it('creates a link for gifting a subscription', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
- let gift = {
+ const gift = {
type: 'subscription',
subscription: {
key: subKey,
@@ -119,7 +119,7 @@ describe('checkout', () => {
},
};
- let link = await paypalPayments.checkout({gift});
+ const link = await paypalPayments.checkout({ gift });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('mo. Habitica Subscription (Gift)', '15.00'));
diff --git a/test/api/unit/libs/payments/paypal/ipn.test.js b/test/api/unit/libs/payments/paypal/ipn.test.js
index 0fe6c8a455..31769ee593 100644
--- a/test/api/unit/libs/payments/paypal/ipn.test.js
+++ b/test/api/unit/libs/payments/paypal/ipn.test.js
@@ -3,13 +3,15 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
describe('ipn', () => {
const subKey = 'basic_3mo';
- let user, group, txn_type, userPaymentId, groupPaymentId;
- let ipnVerifyAsyncStub, paymentCancelSubscriptionSpy;
+ let user; let group; let txn_type; let userPaymentId; let
+ groupPaymentId;
+ let ipnVerifyAsyncStub; let
+ paymentCancelSubscriptionSpy;
beforeEach(async () => {
txn_type = 'recurring_payment_profile_cancel';
@@ -38,16 +40,16 @@ describe('ipn', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
- afterEach(function () {
+ afterEach(() => {
paypalPayments.ipnVerifyAsync.restore();
payments.cancelSubscription.restore();
});
it('should cancel a user subscription', async () => {
- await paypalPayments.ipn({txn_type, recurring_payment_id: userPaymentId});
+ await paypalPayments.ipn({ txn_type, recurring_payment_id: userPaymentId });
expect(ipnVerifyAsyncStub).to.be.calledOnce;
- expect(ipnVerifyAsyncStub).to.be.calledWith({txn_type, recurring_payment_id: userPaymentId});
+ expect(ipnVerifyAsyncStub).to.be.calledWith({ txn_type, recurring_payment_id: userPaymentId });
expect(paymentCancelSubscriptionSpy).to.be.calledOnce;
expect(paymentCancelSubscriptionSpy.args[0][0].user._id).to.eql(user._id);
@@ -55,10 +57,10 @@ describe('ipn', () => {
});
it('should cancel a group subscription', async () => {
- await paypalPayments.ipn({txn_type, recurring_payment_id: groupPaymentId});
+ await paypalPayments.ipn({ txn_type, recurring_payment_id: groupPaymentId });
expect(ipnVerifyAsyncStub).to.be.calledOnce;
- expect(ipnVerifyAsyncStub).to.be.calledWith({txn_type, recurring_payment_id: groupPaymentId});
+ expect(ipnVerifyAsyncStub).to.be.calledWith({ txn_type, recurring_payment_id: groupPaymentId });
expect(paymentCancelSubscriptionSpy).to.be.calledOnce;
expect(paymentCancelSubscriptionSpy).to.be.calledWith({ groupId: group._id, paymentMethod: 'Paypal' });
diff --git a/test/api/unit/libs/payments/paypal/subscribe-cancel.test.js b/test/api/unit/libs/payments/paypal/subscribe-cancel.test.js
index e0f195f0d2..f9d2f86979 100644
--- a/test/api/unit/libs/payments/paypal/subscribe-cancel.test.js
+++ b/test/api/unit/libs/payments/paypal/subscribe-cancel.test.js
@@ -3,17 +3,19 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
import { createNonLeaderGroupMember } from '../paymentHelpers';
-const i18n = common.i18n;
+const { i18n } = common;
describe('subscribeCancel', () => {
const subKey = 'basic_3mo';
- let user, group, groupId, customerId, groupCustomerId, nextBillingDate;
- let paymentCancelSubscriptionSpy, paypalBillingAgreementCancelStub, paypalBillingAgreementGetStub;
+ let user; let group; let groupId; let customerId; let groupCustomerId; let
+ nextBillingDate;
+ let paymentCancelSubscriptionSpy; let paypalBillingAgreementCancelStub; let
+ paypalBillingAgreementGetStub;
beforeEach(async () => {
customerId = 'customer-id';
@@ -49,7 +51,7 @@ describe('subscribeCancel', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
- afterEach(function () {
+ afterEach(() => {
paypalPayments.paypalBillingAgreementGet.restore();
paypalPayments.paypalBillingAgreementCancel.restore();
payments.cancelSubscription.restore();
@@ -58,7 +60,7 @@ describe('subscribeCancel', () => {
it('should throw an error if we are missing a subscription', async () => {
user.purchased.plan.customerId = undefined;
- await expect(paypalPayments.subscribeCancel({user}))
+ await expect(paypalPayments.subscribeCancel({ user }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -67,7 +69,7 @@ describe('subscribeCancel', () => {
});
it('should throw an error if group is not found', async () => {
- await expect(paypalPayments.subscribeCancel({user, groupId: 'fake-id'}))
+ await expect(paypalPayments.subscribeCancel({ user, groupId: 'fake-id' }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 404,
name: 'NotFound',
@@ -76,9 +78,9 @@ describe('subscribeCancel', () => {
});
it('should throw an error if user is not group leader', async () => {
- let nonLeader = await createNonLeaderGroupMember(group);
+ const nonLeader = await createNonLeaderGroupMember(group);
- await expect(paypalPayments.subscribeCancel({user: nonLeader, groupId: group._id}))
+ await expect(paypalPayments.subscribeCancel({ user: nonLeader, groupId: group._id }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -87,7 +89,7 @@ describe('subscribeCancel', () => {
});
it('should cancel a user subscription', async () => {
- await paypalPayments.subscribeCancel({user});
+ await paypalPayments.subscribeCancel({ user });
expect(paypalBillingAgreementGetStub).to.be.calledOnce;
expect(paypalBillingAgreementGetStub).to.be.calledWith(customerId);
@@ -105,7 +107,7 @@ describe('subscribeCancel', () => {
});
it('should cancel a group subscription', async () => {
- await paypalPayments.subscribeCancel({user, groupId: group._id});
+ await paypalPayments.subscribeCancel({ user, groupId: group._id });
expect(paypalBillingAgreementGetStub).to.be.calledOnce;
expect(paypalBillingAgreementGetStub).to.be.calledWith(groupCustomerId);
diff --git a/test/api/unit/libs/payments/paypal/subscribe-success.test.js b/test/api/unit/libs/payments/paypal/subscribe-success.test.js
index 6c2edbf73c..80a09ab7cb 100644
--- a/test/api/unit/libs/payments/paypal/subscribe-success.test.js
+++ b/test/api/unit/libs/payments/paypal/subscribe-success.test.js
@@ -3,14 +3,16 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
describe('subscribeSuccess', () => {
const subKey = 'basic_3mo';
- let user, group, block, groupId, token, headers, customerId;
- let paypalBillingAgreementExecuteStub, paymentsCreateSubscritionStub;
+ let user; let group; let block; let groupId; let token; let headers; let
+ customerId;
+ let paypalBillingAgreementExecuteStub; let
+ paymentsCreateSubscritionStub;
beforeEach(async () => {
user = new User();
@@ -40,7 +42,9 @@ describe('subscribeSuccess', () => {
});
it('creates a user subscription', async () => {
- await paypalPayments.subscribeSuccess({user, block, groupId, token, headers});
+ await paypalPayments.subscribeSuccess({
+ user, block, groupId, token, headers,
+ });
expect(paypalBillingAgreementExecuteStub).to.be.calledOnce;
expect(paypalBillingAgreementExecuteStub).to.be.calledWith(token, {});
@@ -59,7 +63,9 @@ describe('subscribeSuccess', () => {
it('create a group subscription', async () => {
groupId = group._id;
- await paypalPayments.subscribeSuccess({user, block, groupId, token, headers});
+ await paypalPayments.subscribeSuccess({
+ user, block, groupId, token, headers,
+ });
expect(paypalBillingAgreementExecuteStub).to.be.calledOnce;
expect(paypalBillingAgreementExecuteStub).to.be.calledWith(token, {});
diff --git a/test/api/unit/libs/payments/paypal/subscribe.test.js b/test/api/unit/libs/payments/paypal/subscribe.test.js
index d167d7087d..23ad11c60c 100644
--- a/test/api/unit/libs/payments/paypal/subscribe.test.js
+++ b/test/api/unit/libs/payments/paypal/subscribe.test.js
@@ -6,16 +6,17 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('subscribe', () => {
const subKey = 'basic_3mo';
- let coupon, sub, approvalHerf;
+ let coupon; let sub; let
+ approvalHerf;
let paypalBillingAgreementCreateStub;
beforeEach(() => {
approvalHerf = 'approvalHerf-test';
- sub = Object.assign({}, common.content.subscriptionBlocks[subKey]);
+ sub = { ...common.content.subscriptionBlocks[subKey] };
paypalBillingAgreementCreateStub = sinon.stub(paypalPayments, 'paypalBillingAgreementCreate')
.resolves({
@@ -30,7 +31,7 @@ describe('subscribe', () => {
it('should throw an error when coupon code is missing', async () => {
sub.discount = 40;
- await expect(paypalPayments.subscribe({sub, coupon}))
+ await expect(paypalPayments.subscribe({ sub, coupon }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
name: 'BadRequest',
@@ -43,13 +44,13 @@ describe('subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
sinon.stub(cc, 'validate').returns('invalid');
- await expect(paypalPayments.subscribe({sub, coupon}))
+ await expect(paypalPayments.subscribe({ sub, coupon }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -63,17 +64,17 @@ describe('subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
- let updatedCouponModel = await couponModel.save();
+ const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);
- let link = await paypalPayments.subscribe({sub, coupon});
+ const link = await paypalPayments.subscribe({ sub, coupon });
expect(link).to.eql(approvalHerf);
expect(paypalBillingAgreementCreateStub).to.be.calledOnce;
- let billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
+ const billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
expect(paypalBillingAgreementCreateStub).to.be.calledWith({
name: billingPlanTitle,
description: billingPlanTitle,
@@ -92,11 +93,11 @@ describe('subscribe', () => {
it('creates a link for a subscription', async () => {
delete sub.discount;
- let link = await paypalPayments.subscribe({sub, coupon});
+ const link = await paypalPayments.subscribe({ sub, coupon });
expect(link).to.eql(approvalHerf);
expect(paypalBillingAgreementCreateStub).to.be.calledOnce;
- let billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
+ const billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
expect(paypalBillingAgreementCreateStub).to.be.calledWith({
name: billingPlanTitle,
description: billingPlanTitle,
diff --git a/test/api/unit/libs/payments/stripe/cancel-subscription.test.js b/test/api/unit/libs/payments/stripe/cancel-subscription.test.js
index 64750dab8f..c392502f1d 100644
--- a/test/api/unit/libs/payments/stripe/cancel-subscription.test.js
+++ b/test/api/unit/libs/payments/stripe/cancel-subscription.test.js
@@ -2,18 +2,19 @@ import stripeModule from 'stripe';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('cancel subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
- let user, groupId, group;
+ let user; let groupId; let
+ group;
beforeEach(async () => {
user = new User();
@@ -62,7 +63,7 @@ describe('cancel subscription', () => {
});
it('throws an error if user is not the group leader', async () => {
- let nonLeader = new User();
+ const nonLeader = new User();
nonLeader.guilds.push(groupId);
await nonLeader.save();
@@ -78,7 +79,9 @@ describe('cancel subscription', () => {
});
describe('success', () => {
- let stripeDeleteCustomerStub, paymentsCancelSubStub, stripeRetrieveStub, subscriptionId, currentPeriodEndTimeStamp;
+ let stripeDeleteCustomerStub; let paymentsCancelSubStub;
+ let stripeRetrieveStub; let subscriptionId; let
+ currentPeriodEndTimeStamp;
beforeEach(() => {
subscriptionId = 'subId';
@@ -89,7 +92,10 @@ describe('cancel subscription', () => {
stripeRetrieveStub = sinon.stub(stripe.customers, 'retrieve')
.resolves({
subscriptions: {
- data: [{id: subscriptionId, current_period_end: currentPeriodEndTimeStamp}], // eslint-disable-line camelcase
+ data: [{
+ id: subscriptionId,
+ current_period_end: currentPeriodEndTimeStamp,
+ }], // eslint-disable-line camelcase
},
});
});
diff --git a/test/api/unit/libs/payments/stripe/checkout-subscription.test.js b/test/api/unit/libs/payments/stripe/checkout-subscription.test.js
index 9a47d7fffe..cffb9a9d35 100644
--- a/test/api/unit/libs/payments/stripe/checkout-subscription.test.js
+++ b/test/api/unit/libs/payments/stripe/checkout-subscription.test.js
@@ -3,19 +3,22 @@ import cc from 'coupon-code';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('checkout with subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
- let user, group, data, gift, sub, groupId, email, headers, coupon, customerIdResponse, subscriptionId, token;
+ let user; let group; let data; let gift; let sub;
+ let groupId; let email; let headers; let coupon;
+ let customerIdResponse; let subscriptionId; let
+ token;
let spy;
let stripeCreateCustomerSpy;
let stripePaymentsCreateSubSpy;
@@ -57,10 +60,10 @@ describe('checkout with subscription', () => {
spy.resolves;
stripeCreateCustomerSpy = sinon.stub(stripe.customers, 'create');
- let stripCustomerResponse = {
+ const stripCustomerResponse = {
id: customerIdResponse,
subscriptions: {
- data: [{id: subscriptionId}],
+ data: [{ id: subscriptionId }],
},
};
stripeCreateCustomerSpy.resolves(stripCustomerResponse);
@@ -72,7 +75,7 @@ describe('checkout with subscription', () => {
data.sub.quantity = 3;
});
- afterEach(function () {
+ afterEach(() => {
stripe.subscriptions.update.restore();
stripe.customers.create.restore();
payments.createSubscription.restore();
@@ -120,7 +123,7 @@ describe('checkout with subscription', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
@@ -149,9 +152,9 @@ describe('checkout with subscription', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
- let couponModel = new Coupon();
+ const couponModel = new Coupon();
couponModel.event = 'google_6mo';
- let updatedCouponModel = await couponModel.save();
+ const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);
diff --git a/test/api/unit/libs/payments/stripe/checkout.test.js b/test/api/unit/libs/payments/stripe/checkout.test.js
index 37a89e4e70..72585007ad 100644
--- a/test/api/unit/libs/payments/stripe/checkout.test.js
+++ b/test/api/unit/libs/payments/stripe/checkout.test.js
@@ -5,13 +5,15 @@ import stripePayments from '../../../../../../website/server/libs/payments/strip
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('checkout', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
- let stripeChargeStub, paymentBuyGemsStub, paymentCreateSubscritionStub;
- let user, gift, groupId, email, headers, coupon, customerIdResponse, token;
+ let stripeChargeStub; let paymentBuyGemsStub; let
+ paymentCreateSubscritionStub;
+ let user; let gift; let groupId; let email; let headers; let coupon; let customerIdResponse; let
+ token;
beforeEach(() => {
user = new User();
@@ -23,7 +25,7 @@ describe('checkout', () => {
token = 'test-token';
customerIdResponse = 'example-customerIdResponse';
- let stripCustomerResponse = {
+ const stripCustomerResponse = {
id: customerIdResponse,
};
stripeChargeStub = sinon.stub(stripe.charges, 'create').resolves(stripCustomerResponse);
@@ -54,7 +56,7 @@ describe('checkout', () => {
});
it('should error if gem amount is too low', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
gift = {
type: 'gems',
@@ -132,7 +134,7 @@ describe('checkout', () => {
});
it('should gift gems', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'gems',
@@ -169,7 +171,7 @@ describe('checkout', () => {
});
it('should gift a subscription', async () => {
- let receivingUser = new User();
+ const receivingUser = new User();
receivingUser.save();
gift = {
type: 'subscription',
diff --git a/test/api/unit/libs/payments/stripe/edit-subscription.test.js b/test/api/unit/libs/payments/stripe/edit-subscription.test.js
index b7a2ec6ecd..1db3a86b17 100644
--- a/test/api/unit/libs/payments/stripe/edit-subscription.test.js
+++ b/test/api/unit/libs/payments/stripe/edit-subscription.test.js
@@ -2,17 +2,18 @@ import stripeModule from 'stripe';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import common from '../../../../../../website/common';
-const i18n = common.i18n;
+const { i18n } = common;
describe('edit subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
- let user, groupId, group, token;
+ let user; let groupId; let group; let
+ token;
beforeEach(async () => {
user = new User();
@@ -76,7 +77,7 @@ describe('edit subscription', () => {
});
it('throws an error if user is not the group leader', async () => {
- let nonLeader = new User();
+ const nonLeader = new User();
nonLeader.guilds.push(groupId);
await nonLeader.save();
@@ -93,13 +94,14 @@ describe('edit subscription', () => {
});
describe('success', () => {
- let stripeListSubscriptionStub, stripeUpdateSubscriptionStub, subscriptionId;
+ let stripeListSubscriptionStub; let stripeUpdateSubscriptionStub; let
+ subscriptionId;
beforeEach(() => {
subscriptionId = 'subId';
stripeListSubscriptionStub = sinon.stub(stripe.subscriptions, 'list')
.resolves({
- data: [{id: subscriptionId}],
+ data: [{ id: subscriptionId }],
});
stripeUpdateSubscriptionStub = sinon.stub(stripe.subscriptions, 'update').resolves({});
@@ -118,11 +120,13 @@ describe('edit subscription', () => {
}, stripe);
expect(stripeListSubscriptionStub).to.be.calledOnce;
- expect(stripeListSubscriptionStub).to.be.calledWith({customer: user.purchased.plan.customerId});
+ expect(stripeListSubscriptionStub).to.be.calledWith({
+ customer: user.purchased.plan.customerId,
+ });
expect(stripeUpdateSubscriptionStub).to.be.calledOnce;
expect(stripeUpdateSubscriptionStub).to.be.calledWith(
subscriptionId,
- { card: token }
+ { card: token },
);
});
@@ -134,11 +138,13 @@ describe('edit subscription', () => {
}, stripe);
expect(stripeListSubscriptionStub).to.be.calledOnce;
- expect(stripeListSubscriptionStub).to.be.calledWith({customer: group.purchased.plan.customerId});
+ expect(stripeListSubscriptionStub).to.be.calledWith({
+ customer: group.purchased.plan.customerId,
+ });
expect(stripeUpdateSubscriptionStub).to.be.calledOnce;
expect(stripeUpdateSubscriptionStub).to.be.calledWith(
subscriptionId,
- { card: token }
+ { card: token },
);
});
});
diff --git a/test/api/unit/libs/payments/stripe/handle-webhook.test.js b/test/api/unit/libs/payments/stripe/handle-webhook.test.js
index dd7d60be85..9be8121773 100644
--- a/test/api/unit/libs/payments/stripe/handle-webhook.test.js
+++ b/test/api/unit/libs/payments/stripe/handle-webhook.test.js
@@ -1,25 +1,25 @@
import stripeModule from 'stripe';
+import { v4 as uuid } from 'uuid';
+import moment from 'moment';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
import logger from '../../../../../../website/server/libs/logger';
-import { v4 as uuid } from 'uuid';
-import moment from 'moment';
-const i18n = common.i18n;
+const { i18n } = common;
describe('Stripe - Webhooks', () => {
const stripe = stripeModule('test');
describe('all events', () => {
const eventType = 'account.updated';
- const event = {id: 123};
- const eventRetrieved = {type: eventType};
+ const event = { id: 123 };
+ const eventRetrieved = { type: eventType };
beforeEach(() => {
sinon.stub(stripe.events, 'retrieve').resolves(eventRetrieved);
@@ -33,7 +33,7 @@ describe('Stripe - Webhooks', () => {
it('logs an error if an unsupported webhook event is passed', async () => {
const error = new Error(`Missing handler for Stripe webhook ${eventType}`);
- await stripePayments.handleWebhooks({requestBody: event}, stripe);
+ await stripePayments.handleWebhooks({ requestBody: event }, stripe);
expect(logger.error).to.have.been.calledOnce;
const calledWith = logger.error.getCall(0).args;
@@ -42,7 +42,7 @@ describe('Stripe - Webhooks', () => {
});
it('retrieves and validates the event from Stripe', async () => {
- await stripePayments.handleWebhooks({requestBody: event}, stripe);
+ await stripePayments.handleWebhooks({ requestBody: event }, stripe);
expect(stripe.events.retrieve).to.have.been.calledOnce;
expect(stripe.events.retrieve).to.have.been.calledWith(event.id);
});
@@ -68,7 +68,7 @@ describe('Stripe - Webhooks', () => {
request: 123,
});
- await stripePayments.handleWebhooks({requestBody: {}}, stripe);
+ await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.events.retrieve).to.have.been.calledOnce;
expect(stripe.customers.del).to.not.have.been.called;
@@ -93,11 +93,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
- await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
- message: i18n.t('userNotFound'),
- httpCode: 404,
- name: 'NotFound',
- });
+ await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
+ .to.eventually.be.rejectedWith({
+ message: i18n.t('userNotFound'),
+ httpCode: 404,
+ name: 'NotFound',
+ });
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -108,7 +109,7 @@ describe('Stripe - Webhooks', () => {
it('deletes the customer on Stripe and calls payments.cancelSubscription', async () => {
const customerId = '456';
- let subscriber = new User();
+ const subscriber = new User();
subscriber.purchased.plan.customerId = customerId;
subscriber.purchased.plan.paymentMethod = 'Stripe';
await subscriber.save();
@@ -127,13 +128,13 @@ describe('Stripe - Webhooks', () => {
request: null,
});
- await stripePayments.handleWebhooks({requestBody: {}}, stripe);
+ await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.customers.del).to.have.been.calledOnce;
expect(stripe.customers.del).to.have.been.calledWith(customerId);
expect(payments.cancelSubscription).to.have.been.calledOnce;
- let cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
+ const cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
expect(cancelSubscriptionOpts.user._id).to.equal(subscriber._id);
expect(cancelSubscriptionOpts.paymentMethod).to.equal('Stripe');
expect(Math.round(moment(cancelSubscriptionOpts.nextBill).diff(new Date(), 'days', true))).to.equal(3);
@@ -160,11 +161,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
- await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
- message: i18n.t('groupNotFound'),
- httpCode: 404,
- name: 'NotFound',
- });
+ await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
+ .to.eventually.be.rejectedWith({
+ message: i18n.t('groupNotFound'),
+ httpCode: 404,
+ name: 'NotFound',
+ });
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -175,7 +177,7 @@ describe('Stripe - Webhooks', () => {
it('throws an error if the group leader is not found', async () => {
const customerId = 456;
- let subscriber = generateGroup({
+ const subscriber = generateGroup({
name: 'test group',
type: 'guild',
privacy: 'public',
@@ -199,11 +201,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
- await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
- message: i18n.t('userNotFound'),
- httpCode: 404,
- name: 'NotFound',
- });
+ await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
+ .to.eventually.be.rejectedWith({
+ message: i18n.t('userNotFound'),
+ httpCode: 404,
+ name: 'NotFound',
+ });
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -214,10 +217,10 @@ describe('Stripe - Webhooks', () => {
it('deletes the customer on Stripe and calls payments.cancelSubscription', async () => {
const customerId = '456';
- let leader = new User();
+ const leader = new User();
await leader.save();
- let subscriber = generateGroup({
+ const subscriber = generateGroup({
name: 'test group',
type: 'guild',
privacy: 'public',
@@ -241,13 +244,13 @@ describe('Stripe - Webhooks', () => {
request: null,
});
- await stripePayments.handleWebhooks({requestBody: {}}, stripe);
+ await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.customers.del).to.have.been.calledOnce;
expect(stripe.customers.del).to.have.been.calledWith(customerId);
expect(payments.cancelSubscription).to.have.been.calledOnce;
- let cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
+ const cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
expect(cancelSubscriptionOpts.user._id).to.equal(leader._id);
expect(cancelSubscriptionOpts.paymentMethod).to.equal('Stripe');
expect(Math.round(moment(cancelSubscriptionOpts.nextBill).diff(new Date(), 'days', true))).to.equal(3);
diff --git a/test/api/unit/libs/payments/stripe/upgrade-group-plan.test.js b/test/api/unit/libs/payments/stripe/upgrade-group-plan.test.js
index 38b6e6f979..a1ce194cae 100644
--- a/test/api/unit/libs/payments/stripe/upgrade-group-plan.test.js
+++ b/test/api/unit/libs/payments/stripe/upgrade-group-plan.test.js
@@ -2,7 +2,7 @@ import stripeModule from 'stripe';
import {
generateGroup,
-} from '../../../../../helpers/api-unit.helper.js';
+} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
@@ -10,9 +10,10 @@ import payments from '../../../../../../website/server/libs/payments/payments';
describe('Stripe - Upgrade Group Plan', () => {
const stripe = stripeModule('test');
- let spy, data, user, group;
+ let spy; let data; let user; let
+ group;
- beforeEach(async function () {
+ beforeEach(async () => {
user = new User();
user.profile.name = 'sender';
@@ -44,7 +45,7 @@ describe('Stripe - Upgrade Group Plan', () => {
stripePayments.setStripeApi(stripe);
});
- afterEach(function () {
+ afterEach(() => {
stripe.subscriptions.update.restore();
});
@@ -52,7 +53,7 @@ describe('Stripe - Upgrade Group Plan', () => {
data.paymentMethod = 'Stripe';
await payments.createSubscription(data);
- let updatedGroup = await Group.findById(group._id).exec();
+ const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.quantity).to.eql(3);
updatedGroup.memberCount += 1;
diff --git a/test/api/unit/libs/preening.test.js b/test/api/unit/libs/preening.test.js
index 9f5dacbf14..c2448c5df9 100644
--- a/test/api/unit/libs/preening.test.js
+++ b/test/api/unit/libs/preening.test.js
@@ -1,7 +1,7 @@
-import { preenHistory } from '../../../../website/server/libs/preening';
import moment from 'moment';
import sinon from 'sinon'; // eslint-disable-line no-shadow
-import { generateHistory } from '../../../helpers/api-unit.helper.js';
+import { preenHistory } from '../../../../website/server/libs/preening';
+import { generateHistory } from '../../../helpers/api-unit.helper';
describe('preenHistory', () => {
let clock;
@@ -13,47 +13,47 @@ describe('preenHistory', () => {
toFake: ['Date'],
});
});
- afterEach(() => {
- return clock.restore();
- });
+ afterEach(() => clock.restore());
it('does not modify history if all entries are more recent than cutoff (free users)', () => {
- let h = generateHistory(60);
+ const h = generateHistory(60);
expect(preenHistory(_.cloneDeep(h), false, 0)).to.eql(h);
});
it('does not modify history if all entries are more recent than cutoff (subscribers)', () => {
- let h = generateHistory(365);
+ const h = generateHistory(365);
expect(preenHistory(_.cloneDeep(h), true, 0)).to.eql(h);
});
it('does aggregate data in monthly entries before cutoff (free users)', () => {
- let h = generateHistory(81); // Jumps to July
- let preened = preenHistory(_.cloneDeep(h), false, 0);
+ const h = generateHistory(81); // Jumps to July
+ const preened = preenHistory(_.cloneDeep(h), false, 0);
expect(preened.length).to.eql(62); // Keeps 60 days + 2 entries per august and july
});
it('does aggregate data in monthly entries before cutoff (subscribers)', () => {
- let h = generateHistory(396); // Jumps to September 2012
- let preened = preenHistory(_.cloneDeep(h), true, 0);
+ const h = generateHistory(396); // Jumps to September 2012
+ const preened = preenHistory(_.cloneDeep(h), true, 0);
expect(preened.length).to.eql(367); // Keeps 365 days + 2 entries per october and september
});
it('does aggregate data in monthly and yearly entries before cutoff (free users)', () => {
- let h = generateHistory(731); // Jumps to October 21 2012
- let preened = preenHistory(_.cloneDeep(h), false, 0);
- expect(preened.length).to.eql(73); // Keeps 60 days + 11 montly entries and 2 yearly entry for 2011 and 2012
+ const h = generateHistory(731); // Jumps to October 21 2012
+ const preened = preenHistory(_.cloneDeep(h), false, 0);
+ // Keeps 60 days + 11 montly entries and 2 yearly entry for 2011 and 2012
+ expect(preened.length).to.eql(73);
});
it('does aggregate data in monthly and yearly entries before cutoff (subscribers)', () => {
- let h = generateHistory(1031); // Jumps to October 21 2012
- let preened = preenHistory(_.cloneDeep(h), true, 0);
- expect(preened.length).to.eql(380); // Keeps 365 days + 13 montly entries and 2 yearly entries for 2011 and 2010
+ const h = generateHistory(1031); // Jumps to October 21 2012
+ const preened = preenHistory(_.cloneDeep(h), true, 0);
+ // Keeps 365 days + 13 montly entries and 2 yearly entries for 2011 and 2010
+ expect(preened.length).to.eql(380);
});
it('correctly aggregates values', () => {
- let h = generateHistory(63); // Compress last 3 days
- let preened = preenHistory(_.cloneDeep(h), false, 0);
+ const h = generateHistory(63); // Compress last 3 days
+ const preened = preenHistory(_.cloneDeep(h), false, 0);
expect(preened[0].value).to.eql((61 + 62 + 63) / 3);
});
});
diff --git a/test/api/unit/libs/pushNotifications.js b/test/api/unit/libs/pushNotifications.js
index 0967ba349d..ba09d4cdce 100644
--- a/test/api/unit/libs/pushNotifications.js
+++ b/test/api/unit/libs/pushNotifications.js
@@ -1,19 +1,19 @@
-import { model as User } from '../../../../website/server/models/user';
import requireAgain from 'require-again';
import apn from 'apn/mock';
import nconf from 'nconf';
import gcmLib from 'node-gcm'; // works with FCM notifications too
+import { model as User } from '../../../../website/server/models/user';
describe('pushNotifications', () => {
let user;
let sendPushNotification;
- let pathToPushNotifications = '../../../../website/server/libs/pushNotifications';
+ const pathToPushNotifications = '../../../../website/server/libs/pushNotifications';
let fcmSendSpy;
let apnSendSpy;
- let identifier = 'identifier';
- let title = 'title';
- let message = 'message';
+ const identifier = 'identifier';
+ const title = 'title';
+ const message = 'message';
beforeEach(() => {
user = new User();
@@ -93,7 +93,7 @@ describe('pushNotifications', () => {
regId: '123',
});
- let details = {
+ const details = {
identifier,
title,
message,
diff --git a/test/api/unit/libs/setupNconf.test.js b/test/api/unit/libs/setupNconf.test.js
index 33101e40af..81269915cd 100644
--- a/test/api/unit/libs/setupNconf.test.js
+++ b/test/api/unit/libs/setupNconf.test.js
@@ -1,7 +1,7 @@
-import setupNconf from '../../../../website/server/libs/setupNconf';
import path from 'path';
import nconf from 'nconf';
+import setupNconf from '../../../../website/server/libs/setupNconf';
describe('setupNconf', () => {
beforeEach(() => {
@@ -21,7 +21,7 @@ describe('setupNconf', () => {
expect(nconf.env).to.be.calledOnce;
expect(nconf.file).to.be.calledOnce;
- let regexString = `\\${path.sep}config.json$`;
+ const regexString = `\\${path.sep}config.json$`;
expect(nconf.file).to.be.calledWithMatch('user', new RegExp(regexString));
});
diff --git a/test/api/unit/libs/slack.js b/test/api/unit/libs/slack.js
index 3780eb399a..c1615804c2 100644
--- a/test/api/unit/libs/slack.js
+++ b/test/api/unit/libs/slack.js
@@ -1,11 +1,11 @@
/* eslint-disable camelcase */
import { IncomingWebhook } from '@slack/client';
import requireAgain from 'require-again';
+import nconf from 'nconf';
+import moment from 'moment';
import * as slack from '../../../../website/server/libs/slack';
import logger from '../../../../website/server/libs/logger';
import { TAVERN_ID } from '../../../../website/server/models/group';
-import nconf from 'nconf';
-import moment from 'moment';
describe('slack', () => {
describe('sendFlagNotification', () => {
@@ -113,7 +113,7 @@ describe('slack', () => {
it('noops if no flagging url is provided', () => {
sandbox.stub(nconf, 'get').withArgs('SLACK_FLAGGING_URL').returns('');
sandbox.stub(logger, 'error');
- let reRequiredSlack = requireAgain('../../../../website/server/libs/slack');
+ const reRequiredSlack = requireAgain('../../../../website/server/libs/slack');
expect(logger.error).to.be.calledOnce;
diff --git a/test/api/unit/libs/taskManager.js b/test/api/unit/libs/taskManager.js
index 57c6f3957f..c6c54dc012 100644
--- a/test/api/unit/libs/taskManager.js
+++ b/test/api/unit/libs/taskManager.js
@@ -9,11 +9,12 @@ import {
generateUser,
generateGroup,
generateChallenge,
-} from '../../../helpers/api-unit.helper.js';
+} from '../../../helpers/api-unit.helper';
describe('taskManager', () => {
- let user, group, challenge;
- let testHabit = {
+ let user; let group; let
+ challenge;
+ const testHabit = {
text: 'test habit',
type: 'habit',
up: false,
@@ -47,8 +48,8 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- let newTasks = await createTasks(req, res, {user});
- let newTask = newTasks[0];
+ const newTasks = await createTasks(req, res, { user });
+ const newTask = newTasks[0];
expect(newTask.text).to.equal(testHabit.text);
expect(newTask.type).to.equal(testHabit.type);
@@ -61,15 +62,15 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- await createTasks(req, res, {user});
+ await createTasks(req, res, { user });
req.body = {};
req.query = {
type: 'habits',
};
- let tasks = await getTasks(req, res, {user});
- let task = tasks[0];
+ const tasks = await getTasks(req, res, { user });
+ const task = tasks[0];
expect(task.text).to.equal(testHabit.text);
expect(task.type).to.equal(testHabit.type);
@@ -82,8 +83,8 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- let newTasks = await createTasks(req, res, {user, group});
- let newTask = newTasks[0];
+ const newTasks = await createTasks(req, res, { user, group });
+ const newTask = newTasks[0];
expect(newTask.text).to.equal(testHabit.text);
expect(newTask.type).to.equal(testHabit.type);
@@ -97,15 +98,15 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- await createTasks(req, res, {user, group});
+ await createTasks(req, res, { user, group });
req.body = {};
req.query = {
type: 'habits',
};
- let tasks = await getTasks(req, res, {user, group});
- let task = tasks[0];
+ const tasks = await getTasks(req, res, { user, group });
+ const task = tasks[0];
expect(task.text).to.equal(testHabit.text);
expect(task.type).to.equal(testHabit.type);
@@ -119,8 +120,8 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- let newTasks = await createTasks(req, res, {user, challenge});
- let newTask = newTasks[0];
+ const newTasks = await createTasks(req, res, { user, challenge });
+ const newTask = newTasks[0];
expect(newTask.text).to.equal(testHabit.text);
expect(newTask.type).to.equal(testHabit.type);
@@ -134,15 +135,15 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- await createTasks(req, res, {user, challenge});
+ await createTasks(req, res, { user, challenge });
req.body = {};
req.query = {
type: 'habits',
};
- let tasks = await getTasks(req, res, {user, challenge});
- let task = tasks[0];
+ const tasks = await getTasks(req, res, { user, challenge });
+ const task = tasks[0];
expect(task.text).to.equal(testHabit.text);
expect(task.type).to.equal(testHabit.type);
@@ -156,9 +157,9 @@ describe('taskManager', () => {
req.body = testHabit;
res.t = i18n.t;
- let tasks = await createTasks(req, res, {user, challenge});
+ const tasks = await createTasks(req, res, { user, challenge });
- let syncableTask = syncableAttrs(tasks[0]);
+ const syncableTask = syncableAttrs(tasks[0]);
expect(syncableTask._id).to.not.exist;
expect(syncableTask.userId).to.not.exist;
@@ -172,7 +173,7 @@ describe('taskManager', () => {
});
it('moves tasks to a specified position', async () => {
- let order = ['task-id-1', 'task-id-2'];
+ const order = ['task-id-1', 'task-id-2'];
moveTask(order, 'task-id-2', 0);
@@ -180,7 +181,7 @@ describe('taskManager', () => {
});
it('moves tasks to a specified position out of length', async () => {
- let order = ['task-id-1'];
+ const order = ['task-id-1'];
moveTask(order, 'task-id-2', 2);
diff --git a/test/api/unit/libs/webhooks.test.js b/test/api/unit/libs/webhooks.test.js
index d1bc9c52ff..761eda713b 100644
--- a/test/api/unit/libs/webhooks.test.js
+++ b/test/api/unit/libs/webhooks.test.js
@@ -12,11 +12,13 @@ import {
} from '../../../../website/server/models/user';
import {
generateUser,
-} from '../../../helpers/api-unit.helper.js';
-import { defer } from '../../../helpers/api-unit.helper';
+ defer,
+} from '../../../helpers/api-unit.helper';
+
describe('webhooks', () => {
- let webhooks, user;
+ let webhooks; let
+ user;
beforeEach(() => {
sandbox.stub(got, 'post').returns(defer().promise);
@@ -72,7 +74,7 @@ describe('webhooks', () => {
describe('WebhookSender', () => {
it('creates a new WebhookSender object', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
@@ -82,13 +84,15 @@ describe('webhooks', () => {
it('provides default function for data transformation', () => {
sandbox.spy(WebhookSender, 'defaultTransformData');
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(WebhookSender.defaultTransformData).to.be.calledOnce;
@@ -100,14 +104,16 @@ describe('webhooks', () => {
});
it('adds default data (user and webhookType) to the body', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
sandbox.spy(sendWebhook, 'attachDefaultData');
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(sendWebhook.attachDefaultData).to.be.calledOnce;
@@ -118,25 +124,27 @@ describe('webhooks', () => {
expect(body).to.eql({
foo: 'bar',
- user: {_id: user._id},
+ user: { _id: user._id },
webhookType: 'custom',
});
});
it('can pass in a data transformation function', () => {
sandbox.spy(WebhookSender, 'defaultTransformData');
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
transformData (data) {
- let dataToSend = Object.assign({baz: 'biz'}, data);
+ const dataToSend = { baz: 'biz', ...data };
return dataToSend;
},
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(WebhookSender.defaultTransformData).to.not.be.called;
@@ -152,13 +160,15 @@ describe('webhooks', () => {
it('provides a default filter function', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(WebhookSender.defaultWebhookFilter).to.be.calledOnce;
@@ -166,16 +176,18 @@ describe('webhooks', () => {
it('can pass in a webhook filter function', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
webhookFilter (hook) {
return hook.url !== 'http://custom-url.com';
},
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(WebhookSender.defaultWebhookFilter).to.not.be.called;
@@ -184,18 +196,22 @@ describe('webhooks', () => {
it('can pass in a webhook filter function that filters on data', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
webhookFilter (hook, data) {
return hook.options.foo === data.foo;
},
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
user.webhooks = [
- { id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom', options: { foo: 'bar' }},
- { id: 'other-custom-webhook', url: 'http://other-custom-url.com', enabled: true, type: 'custom', options: { foo: 'foo' }},
+ {
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom', options: { foo: 'bar' },
+ },
+ {
+ id: 'other-custom-webhook', url: 'http://other-custom-url.com', enabled: true, type: 'custom', options: { foo: 'foo' },
+ },
];
sendWebhook.send(user, body);
@@ -204,41 +220,49 @@ describe('webhooks', () => {
});
it('ignores disabled webhooks', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'http://custom-url.com', enabled: false, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: false, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(got.post).to.not.be.called;
});
it('ignores webhooks with invalid urls', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
- user.webhooks = [{id: 'custom-webhook', url: 'httxp://custom-url!!!', enabled: true, type: 'custom'}];
+ user.webhooks = [{
+ id: 'custom-webhook', url: 'httxp://custom-url!!!', enabled: true, type: 'custom',
+ }];
sendWebhook.send(user, body);
expect(got.post).to.not.be.called;
});
it('ignores webhooks of other types', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
user.webhooks = [
- { id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'},
- { id: 'other-webhook', url: 'http://other-url.com', enabled: true, type: 'other'},
+ {
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ },
+ {
+ id: 'other-webhook', url: 'http://other-url.com', enabled: true, type: 'other',
+ },
];
sendWebhook.send(user, body);
@@ -250,14 +274,16 @@ describe('webhooks', () => {
});
it('sends every type of activity to global webhooks', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
user.webhooks = [
- { id: 'global-webhook', url: 'http://custom-url.com', enabled: true, type: 'globalActivity'},
+ {
+ id: 'global-webhook', url: 'http://custom-url.com', enabled: true, type: 'globalActivity',
+ },
];
sendWebhook.send(user, body);
@@ -269,15 +295,19 @@ describe('webhooks', () => {
});
it('sends multiple webhooks of the same type', () => {
- let sendWebhook = new WebhookSender({
+ const sendWebhook = new WebhookSender({
type: 'custom',
});
- let body = { foo: 'bar' };
+ const body = { foo: 'bar' };
user.webhooks = [
- { id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'},
- { id: 'other-custom-webhook', url: 'http://other-url.com', enabled: true, type: 'custom'},
+ {
+ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom',
+ },
+ {
+ id: 'other-custom-webhook', url: 'http://other-url.com', enabled: true, type: 'custom',
+ },
];
sendWebhook.send(user, body);
@@ -299,7 +329,7 @@ describe('webhooks', () => {
beforeEach(() => {
data = {
user: {
- _tmp: {foo: 'bar'},
+ _tmp: { foo: 'bar' },
stats: {
lvl: 5,
int: 10,
@@ -317,11 +347,12 @@ describe('webhooks', () => {
delta: 176,
};
- let mockStats = Object.assign({
+ const mockStats = {
maxHealth: 50,
maxMP: 103,
toNextLevel: 40,
- }, data.user.stats);
+ ...data.user.stats,
+ };
delete mockStats.toJSON;
sandbox.stub(User, 'addComputedStatsToJSONObj').returns(mockStats);
@@ -338,7 +369,7 @@ describe('webhooks', () => {
webhookType: 'taskActivity',
user: {
_id: user._id,
- _tmp: {foo: 'bar'},
+ _tmp: { foo: 'bar' },
stats: {
lvl: 5,
int: 10,
@@ -376,7 +407,7 @@ describe('webhooks', () => {
webhookType: 'taskActivity',
user: {
_id: user._id,
- _tmp: {foo: 'bar'},
+ _tmp: { foo: 'bar' },
stats: {
lvl: 5,
int: 10,
@@ -416,7 +447,7 @@ describe('webhooks', () => {
};
});
- ['created', 'updated', 'deleted'].forEach((type) => {
+ ['created', 'updated', 'deleted'].forEach(type => {
it(`sends ${type} tasks`, () => {
data.type = type;
@@ -498,7 +529,7 @@ describe('webhooks', () => {
};
});
- ['petHatched', 'mountRaised', 'leveledUp'].forEach((type) => {
+ ['petHatched', 'mountRaised', 'leveledUp'].forEach(type => {
it(`sends ${type} webhooks`, () => {
data.type = type;
@@ -545,7 +576,7 @@ describe('webhooks', () => {
};
});
- ['questStarted', 'questFinised'].forEach((type) => {
+ ['questStarted', 'questFinised'].forEach(type => {
it(`sends ${type} webhooks`, () => {
data.type = type;
@@ -584,7 +615,7 @@ describe('webhooks', () => {
describe('groupChatReceivedWebhook', () => {
it('sends chat data', () => {
- let data = {
+ const data = {
group: {
id: 'group-id',
name: 'some group',
@@ -619,7 +650,7 @@ describe('webhooks', () => {
});
it('does not send chat data for group if not selected', () => {
- let data = {
+ const data = {
group: {
id: 'not-group-id',
name: 'some group',
diff --git a/test/api/unit/middlewares/analytics.test.js b/test/api/unit/middlewares/analytics.test.js
index 8865c11d0b..32b88d00b8 100644
--- a/test/api/unit/middlewares/analytics.test.js
+++ b/test/api/unit/middlewares/analytics.test.js
@@ -1,16 +1,17 @@
/* eslint-disable global-require */
+import nconf from 'nconf';
+import requireAgain from 'require-again';
import {
generateRes,
generateReq,
generateNext,
} from '../../../helpers/api-unit.helper';
import * as analyticsService from '../../../../website/server/libs/analyticsService';
-import nconf from 'nconf';
-import requireAgain from 'require-again';
describe('analytics middleware', () => {
- let res, req, next;
- let pathToAnalyticsMiddleware = '../../../../website/server/middlewares/analytics';
+ let res; let req; let
+ next;
+ const pathToAnalyticsMiddleware = '../../../../website/server/middlewares/analytics';
beforeEach(() => {
res = generateRes();
@@ -19,7 +20,7 @@ describe('analytics middleware', () => {
});
it('attaches analytics object res.locals', () => {
- let attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
+ const attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
attachAnalytics(req, res, next);
@@ -28,7 +29,7 @@ describe('analytics middleware', () => {
it('attaches stubbed methods for non-prod environments', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(false);
- let attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
+ const attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
attachAnalytics(req, res, next);
@@ -39,7 +40,7 @@ describe('analytics middleware', () => {
it('attaches real methods for prod environments', () => {
sandbox.stub(nconf, 'get').withArgs('IS_PROD').returns(true);
- let attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
+ const attachAnalytics = requireAgain(pathToAnalyticsMiddleware).default;
attachAnalytics(req, res, next);
diff --git a/test/api/unit/middlewares/auth.test.js b/test/api/unit/middlewares/auth.test.js
index 830af9be04..f4a9324189 100644
--- a/test/api/unit/middlewares/auth.test.js
+++ b/test/api/unit/middlewares/auth.test.js
@@ -5,7 +5,8 @@ import {
import { authWithHeaders as authWithHeadersFactory } from '../../../../website/server/middlewares/auth';
describe('auth middleware', () => {
- let res, req, user;
+ let res; let req; let
+ user;
beforeEach(async () => {
res = generateRes();
@@ -14,7 +15,7 @@ describe('auth middleware', () => {
});
describe('auth with headers', () => {
- it('allows to specify a list of user field that we do not want to load', (done) => {
+ it('allows to specify a list of user field that we do not want to load', done => {
const authWithHeaders = authWithHeadersFactory({
userFieldsToExclude: ['items'],
});
@@ -22,18 +23,18 @@ describe('auth middleware', () => {
req.headers['x-api-user'] = user._id;
req.headers['x-api-key'] = user.apiToken;
- authWithHeaders(req, res, (err) => {
+ authWithHeaders(req, res, err => {
if (err) return done(err);
const userToJSON = res.locals.user.toJSON();
expect(userToJSON.items).to.not.exist;
expect(userToJSON.auth).to.exist;
- done();
+ return done();
});
});
- it('makes sure some fields are always included', (done) => {
+ it('makes sure some fields are always included', done => {
const authWithHeaders = authWithHeadersFactory({
userFieldsToExclude: [
'items', 'auth.timestamps',
@@ -44,7 +45,7 @@ describe('auth middleware', () => {
req.headers['x-api-user'] = user._id;
req.headers['x-api-key'] = user.apiToken;
- authWithHeaders(req, res, (err) => {
+ authWithHeaders(req, res, err => {
if (err) return done(err);
const userToJSON = res.locals.user.toJSON();
@@ -56,7 +57,7 @@ describe('auth middleware', () => {
expect(userToJSON._id).to.exist;
expect(userToJSON.flags).to.exist;
- done();
+ return done();
});
});
});
diff --git a/test/api/unit/middlewares/cors.test.js b/test/api/unit/middlewares/cors.test.js
index 1d5b111dd4..9b2c568bf1 100644
--- a/test/api/unit/middlewares/cors.test.js
+++ b/test/api/unit/middlewares/cors.test.js
@@ -7,7 +7,8 @@ import {
import cors from '../../../../website/server/middlewares/cors';
describe('cors middleware', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
req = generateReq();
diff --git a/test/api/unit/middlewares/cronMiddleware.js b/test/api/unit/middlewares/cronMiddleware.js
index ca48110393..bd93b06e65 100644
--- a/test/api/unit/middlewares/cronMiddleware.js
+++ b/test/api/unit/middlewares/cronMiddleware.js
@@ -1,3 +1,5 @@
+import moment from 'moment';
+import { v4 as generateUUID } from 'uuid';
import {
generateRes,
generateReq,
@@ -5,22 +7,21 @@ import {
generateDaily,
} from '../../../helpers/api-unit.helper';
import cronMiddleware from '../../../../website/server/middlewares/cron';
-import moment from 'moment';
import { model as User } from '../../../../website/server/models/user';
import { model as Group } from '../../../../website/server/models/group';
import * as Tasks from '../../../../website/server/models/task';
import * as analyticsService from '../../../../website/server/libs/analyticsService';
import * as cronLib from '../../../../website/server/libs/cron';
-import { v4 as generateUUID } from 'uuid';
const CRON_TIMEOUT_WAIT = new Date(60 * 60 * 1000).getTime();
const CRON_TIMEOUT_UNIT = new Date(60 * 1000).getTime();
describe('cron middleware', () => {
- let res, req;
+ let res; let
+ req;
let user;
- beforeEach((done) => {
+ beforeEach(done => {
res = generateRes();
req = generateReq();
user = new User({
@@ -48,33 +49,35 @@ describe('cron middleware', () => {
sandbox.restore();
});
- it('calls next when user is not attached', (done) => {
+ it('calls next when user is not attached', done => {
res.locals.user = null;
cronMiddleware(req, res, done);
});
- it('calls next when days have not been missed', (done) => {
+ it('calls next when days have not been missed', done => {
cronMiddleware(req, res, done);
});
it('should clear todos older than 30 days for free users', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
- let task = generateTodo(user);
- task.dateCompleted = moment(new Date()).subtract({days: 31});
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const task = generateTodo(user);
+ task.dateCompleted = moment(new Date()).subtract({ days: 31 });
task.completed = true;
await task.save();
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- Tasks.Task.findOne({_id: task}, function (secondErr, taskFound) {
+ Tasks.Task.findOne({ _id: task }, (secondErr, taskFound) => {
if (secondErr) return reject(err);
expect(secondErr).to.not.exist;
expect(taskFound).to.not.exist;
- resolve();
+ return resolve();
});
+
+ return null;
});
});
});
@@ -82,22 +85,23 @@ describe('cron middleware', () => {
it('should not clear todos older than 30 days for subscribed users', async () => {
user.purchased.plan.customerId = 'subscribedId';
user.purchased.plan.dateUpdated = moment('012013', 'MMYYYY');
- user.lastCron = moment(new Date()).subtract({days: 2});
- let task = generateTodo(user);
- task.dateCompleted = moment(new Date()).subtract({days: 31});
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const task = generateTodo(user);
+ task.dateCompleted = moment(new Date()).subtract({ days: 31 });
task.completed = true;
await task.save();
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- Tasks.Task.findOne({_id: task}, function (secondErr, taskFound) {
+ Tasks.Task.findOne({ _id: task }, (secondErr, taskFound) => {
if (secondErr) return reject(secondErr);
expect(secondErr).to.not.exist;
expect(taskFound).to.exist;
- resolve();
+ return resolve();
});
+ return null;
});
});
});
@@ -105,105 +109,106 @@ describe('cron middleware', () => {
it('should clear todos older than 90 days for subscribed users', async () => {
user.purchased.plan.customerId = 'subscribedId';
user.purchased.plan.dateUpdated = moment('012013', 'MMYYYY');
- user.lastCron = moment(new Date()).subtract({days: 2});
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
- let task = generateTodo(user);
- task.dateCompleted = moment(new Date()).subtract({days: 91});
+ const task = generateTodo(user);
+ task.dateCompleted = moment(new Date()).subtract({ days: 91 });
task.completed = true;
await task.save();
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- Tasks.Task.findOne({_id: task}, function (secondErr, taskFound) {
+ Tasks.Task.findOne({ _id: task }, (secondErr, taskFound) => {
if (secondErr) return reject(secondErr);
expect(secondErr).to.not.exist;
expect(taskFound).to.not.exist;
- resolve();
+ return resolve();
});
+ return null;
});
});
});
it('should call next if user was not modified after cron', async () => {
- let hpBefore = user.stats.hp;
- user.lastCron = moment(new Date()).subtract({days: 2});
+ const hpBefore = user.stats.hp;
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
expect(hpBefore).to.equal(user.stats.hp);
- resolve();
+ return resolve();
});
});
});
it('updates user.auth.timestamps.loggedin and lastCron', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
- let now = new Date();
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const now = new Date();
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
expect(moment(now).isSame(user.lastCron, 'day'));
expect(moment(now).isSame(user.auth.timestamps.loggedin, 'day'));
- resolve();
+ return resolve();
});
});
});
it('does damage for missing dailies', async () => {
- let hpBefore = user.stats.hp;
- user.lastCron = moment(new Date()).subtract({days: 2});
- let daily = generateDaily(user);
- daily.startDate = moment(new Date()).subtract({days: 2});
+ const hpBefore = user.stats.hp;
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const daily = generateDaily(user);
+ daily.startDate = moment(new Date()).subtract({ days: 2 });
await daily.save();
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- User.findOne({_id: user._id}, function (secondErr, updatedUser) {
+ return User.findOne({ _id: user._id }, (secondErr, updatedUser) => {
if (secondErr) return reject(secondErr);
expect(updatedUser.stats.hp).to.be.lessThan(hpBefore);
- resolve();
+ return resolve();
});
});
});
});
it('updates tasks', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
- let todo = generateTodo(user);
- let todoValueBefore = todo.value;
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const todo = generateTodo(user);
+ const todoValueBefore = todo.value;
await Promise.all([todo.save(), user.save()]);
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- Tasks.Task.findOne({_id: todo._id}, function (secondErr, todoFound) {
+ return Tasks.Task.findOne({ _id: todo._id }, (secondErr, todoFound) => {
if (secondErr) return reject(secondErr);
expect(todoFound.value).to.be.lessThan(todoValueBefore);
- resolve();
+ return resolve();
});
});
});
});
it('applies quest progress', async () => {
- let hpBefore = user.stats.hp;
- user.lastCron = moment(new Date()).subtract({days: 2});
- let daily = generateDaily(user);
- daily.startDate = moment(new Date()).subtract({days: 2});
+ const hpBefore = user.stats.hp;
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const daily = generateDaily(user);
+ daily.startDate = moment(new Date()).subtract({ days: 2 });
await daily.save();
- let questKey = 'dilatory';
+ const questKey = 'dilatory';
user.party.quest.key = questKey;
- let party = new Group({
+ const party = new Group({
type: 'party',
name: generateUUID(),
leader: user._id,
@@ -218,22 +223,22 @@ describe('cron middleware', () => {
party.startQuest(user);
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
- User.findOne({_id: user._id}, function (secondErr, updatedUser) {
+ return User.findOne({ _id: user._id }, (secondErr, updatedUser) => {
if (secondErr) return reject(secondErr);
expect(updatedUser.stats.hp).to.be.lessThan(hpBefore);
- resolve();
+ return resolve();
});
});
});
});
it('recovers from failed cron and does not error when user is already cronning', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
await user.save();
- let updatedUser = user.toObject();
+ const updatedUser = user.toObject();
updatedUser.nMatched = 0;
sandbox.spy(cronLib, 'recoverCron');
@@ -242,8 +247,8 @@ describe('cron middleware', () => {
.withArgs({
_id: user._id,
$or: [
- {_cronSignature: 'NOT_RUNNING'},
- {_cronSignature: {$lt: sinon.match.number}},
+ { _cronSignature: 'NOT_RUNNING' },
+ { _cronSignature: { $lt: sinon.match.number } },
],
})
.returns({
@@ -253,18 +258,18 @@ describe('cron middleware', () => {
});
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
expect(cronLib.recoverCron).to.be.calledOnce;
- resolve();
+ return resolve();
});
});
});
it('cronSignature less than an hour ago should error', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
- let now = new Date();
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const now = new Date();
await User.update({
_id: user._id,
}, {
@@ -273,20 +278,20 @@ describe('cron middleware', () => {
},
}).exec();
await user.save();
- let expectedErrMessage = `Impossible to recover from cron for user ${user._id}.`;
+ const expectedErrMessage = `Impossible to recover from cron for user ${user._id}.`;
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (!err) return reject(new Error('Cron should have failed.'));
expect(err.message).to.be.equal(expectedErrMessage);
- resolve();
+ return resolve();
});
});
});
it('cronSignature longer than an hour ago should allow cron', async () => {
- user.lastCron = moment(new Date()).subtract({days: 2});
- let now = new Date();
+ user.lastCron = moment(new Date()).subtract({ days: 2 });
+ const now = new Date();
await User.update({
_id: user._id,
}, {
@@ -297,11 +302,11 @@ describe('cron middleware', () => {
await user.save();
await new Promise((resolve, reject) => {
- cronMiddleware(req, res, (err) => {
+ cronMiddleware(req, res, err => {
if (err) return reject(err);
expect(moment(now).isSame(user.auth.timestamps.loggedin, 'day'));
expect(user._cronSignature).to.be.equal('NOT_RUNNING');
- resolve();
+ return resolve();
});
});
});
diff --git a/test/api/unit/middlewares/ensureAccessRight.test.js b/test/api/unit/middlewares/ensureAccessRight.test.js
index 1938546c9c..30eb84b333 100644
--- a/test/api/unit/middlewares/ensureAccessRight.test.js
+++ b/test/api/unit/middlewares/ensureAccessRight.test.js
@@ -10,7 +10,8 @@ import { NotAuthorized } from '../../../../website/server/libs/errors';
import apiError from '../../../../website/server/libs/apiError';
describe('ensure access middlewares', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
res = generateRes();
@@ -20,7 +21,7 @@ describe('ensure access middlewares', () => {
context('ensure admin', () => {
it('returns not authorized when user is not an admin', () => {
- res.locals = {user: {contributor: {admin: false}}};
+ res.locals = { user: { contributor: { admin: false } } };
ensureAdmin(req, res, next);
@@ -30,7 +31,7 @@ describe('ensure access middlewares', () => {
});
it('passes when user is an admin', () => {
- res.locals = {user: {contributor: {admin: true}}};
+ res.locals = { user: { contributor: { admin: true } } };
ensureAdmin(req, res, next);
@@ -41,7 +42,7 @@ describe('ensure access middlewares', () => {
context('ensure sudo', () => {
it('returns not authorized when user is not a sudo user', () => {
- res.locals = {user: {contributor: {sudo: false}}};
+ res.locals = { user: { contributor: { sudo: false } } };
ensureSudo(req, res, next);
@@ -51,7 +52,7 @@ describe('ensure access middlewares', () => {
});
it('passes when user is a sudo user', () => {
- res.locals = {user: {contributor: {sudo: true}}};
+ res.locals = { user: { contributor: { sudo: true } } };
ensureSudo(req, res, next);
diff --git a/test/api/unit/middlewares/ensureDevelpmentMode.js b/test/api/unit/middlewares/ensureDevelpmentMode.js
index 0e1140c961..39bbb2fe6f 100644
--- a/test/api/unit/middlewares/ensureDevelpmentMode.js
+++ b/test/api/unit/middlewares/ensureDevelpmentMode.js
@@ -1,4 +1,5 @@
/* eslint-disable global-require */
+import nconf from 'nconf';
import {
generateRes,
generateReq,
@@ -6,10 +7,10 @@ import {
} from '../../../helpers/api-unit.helper';
import ensureDevelpmentMode from '../../../../website/server/middlewares/ensureDevelpmentMode';
import { NotFound } from '../../../../website/server/libs/errors';
-import nconf from 'nconf';
describe('developmentMode middleware', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
res = generateRes();
diff --git a/test/api/unit/middlewares/errorHandler.test.js b/test/api/unit/middlewares/errorHandler.test.js
index 7611b2c418..ba7c5998a5 100644
--- a/test/api/unit/middlewares/errorHandler.test.js
+++ b/test/api/unit/middlewares/errorHandler.test.js
@@ -15,7 +15,8 @@ import { BadRequest } from '../../../../website/server/libs/errors';
import logger from '../../../../website/server/libs/logger';
describe('errorHandler', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
res = generateRes();
@@ -29,7 +30,7 @@ describe('errorHandler', () => {
});
it('sends internal server error if error is not a CustomError and is not identified', () => {
- let error = new Error();
+ const error = new Error();
errorHandler(error, req, res, next);
@@ -45,7 +46,7 @@ describe('errorHandler', () => {
});
it('identifies errors with statusCode property and format them correctly', () => {
- let error = new Error('Error message');
+ const error = new Error('Error message');
error.statusCode = 400;
errorHandler(error, req, res, next);
@@ -62,7 +63,7 @@ describe('errorHandler', () => {
});
it('doesn\'t leak info about 500 errors', () => {
- let error = new Error('Some secret error message');
+ const error = new Error('Some secret error message');
error.statusCode = 500;
errorHandler(error, req, res, next);
@@ -79,7 +80,7 @@ describe('errorHandler', () => {
});
it('sends CustomError', () => {
- let error = new BadRequest();
+ const error = new BadRequest();
errorHandler(error, req, res, next);
@@ -95,7 +96,7 @@ describe('errorHandler', () => {
});
it('handle http-errors errors', () => {
- let error = new Error('custom message');
+ const error = new Error('custom message');
error.statusCode = 422;
errorHandler(error, req, res, next);
@@ -112,7 +113,7 @@ describe('errorHandler', () => {
});
it('handle express-validator errors', () => {
- let error = [{param: 'param', msg: 'invalid param', value: 123}];
+ const error = [{ param: 'param', msg: 'invalid param', value: 123 }];
errorHandler(error, req, res, next);
@@ -131,7 +132,7 @@ describe('errorHandler', () => {
});
it('handle Mongoose Validation errors', () => {
- let error = new Error('User validation failed');
+ const error = new Error('User validation failed');
error.name = 'ValidationError';
error.errors = {
@@ -159,7 +160,7 @@ describe('errorHandler', () => {
});
it('logs error', () => {
- let error = new BadRequest();
+ const error = new BadRequest();
errorHandler(error, req, res, next);
diff --git a/test/api/unit/middlewares/language.test.js b/test/api/unit/middlewares/language.test.js
index 8c93bc2b5e..4965da9a49 100644
--- a/test/api/unit/middlewares/language.test.js
+++ b/test/api/unit/middlewares/language.test.js
@@ -10,11 +10,12 @@ import {
import common from '../../../../website/common';
import { model as User } from '../../../../website/server/models/user';
-const i18n = common.i18n;
+const { i18n } = common;
describe('language middleware', () => {
describe('res.t', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
res = generateRes();
@@ -46,9 +47,10 @@ describe('language middleware', () => {
});
describe('getUserLanguage', () => {
- let res, req, next;
+ let res; let req; let
+ next;
- let checkResT = (resToCheck) => {
+ const checkResT = resToCheck => {
expect(resToCheck.t).to.be.a('function');
expect(resToCheck.t('help')).to.equal(i18n.t('help', req.language));
};
@@ -119,7 +121,7 @@ describe('language middleware', () => {
checkResT(res);
});
- it('falls back to english if the user preferred language is not avalaible', (done) => {
+ it('falls back to english if the user preferred language is not avalaible', done => {
req.locals = {
user: {
preferences: {
@@ -155,7 +157,7 @@ describe('language middleware', () => {
});
context('request with session', () => {
- it('uses the user preferred language if avalaible', (done) => {
+ it('uses the user preferred language if avalaible', done => {
sandbox.stub(User, 'findOne').returns({
lean () {
return this;
@@ -182,7 +184,7 @@ describe('language middleware', () => {
});
context('browser fallback', () => {
- it('uses browser specificed language', (done) => {
+ it('uses browser specificed language', done => {
req.headers['accept-language'] = 'pt';
getUserLanguage(req, res, () => {
@@ -192,7 +194,7 @@ describe('language middleware', () => {
});
});
- it('uses first language in series if browser specifies multiple', (done) => {
+ it('uses first language in series if browser specifies multiple', done => {
req.headers['accept-language'] = 'he, pt, it';
getUserLanguage(req, res, () => {
@@ -202,7 +204,7 @@ describe('language middleware', () => {
});
});
- it('skips invalid lanaguages and uses first language in series if browser specifies multiple', (done) => {
+ it('skips invalid lanaguages and uses first language in series if browser specifies multiple', done => {
req.headers['accept-language'] = 'blah, he, pt, it';
getUserLanguage(req, res, () => {
@@ -212,7 +214,7 @@ describe('language middleware', () => {
});
});
- it('uses normal version of language if specialized locale is passed in', (done) => {
+ it('uses normal version of language if specialized locale is passed in', done => {
req.headers['accept-language'] = 'fr-CA';
getUserLanguage(req, res, () => {
@@ -222,7 +224,7 @@ describe('language middleware', () => {
});
});
- it('uses normal version of language if specialized locale is passed in', (done) => {
+ it('uses normal version of language if specialized locale is passed in', done => {
req.headers['accept-language'] = 'fr-CA';
getUserLanguage(req, res, () => {
@@ -232,7 +234,7 @@ describe('language middleware', () => {
});
});
- it('uses es if es is passed in', (done) => {
+ it('uses es if es is passed in', done => {
req.headers['accept-language'] = 'es';
getUserLanguage(req, res, () => {
@@ -242,7 +244,7 @@ describe('language middleware', () => {
});
});
- it('uses es_419 if applicable es-languages are passed in', (done) => {
+ it('uses es_419 if applicable es-languages are passed in', done => {
req.headers['accept-language'] = 'es-mx';
getUserLanguage(req, res, () => {
@@ -252,7 +254,7 @@ describe('language middleware', () => {
});
});
- it('uses es_419 if multiple es languages are passed in', (done) => {
+ it('uses es_419 if multiple es languages are passed in', done => {
req.headers['accept-language'] = 'es-GT, es-MX, es-CR';
getUserLanguage(req, res, () => {
@@ -262,7 +264,7 @@ describe('language middleware', () => {
});
});
- it('zh', (done) => {
+ it('zh', done => {
req.headers['accept-language'] = 'zh-TW';
getUserLanguage(req, res, () => {
@@ -272,7 +274,7 @@ describe('language middleware', () => {
});
});
- it('uses english if browser specified language is not compatible', (done) => {
+ it('uses english if browser specified language is not compatible', done => {
req.headers['accept-language'] = 'blah';
getUserLanguage(req, res, () => {
@@ -282,7 +284,7 @@ describe('language middleware', () => {
});
});
- it('uses english if browser does not specify', (done) => {
+ it('uses english if browser does not specify', done => {
req.headers['accept-language'] = '';
getUserLanguage(req, res, () => {
@@ -292,7 +294,7 @@ describe('language middleware', () => {
});
});
- it('uses english if browser does not supply an accept-language header', (done) => {
+ it('uses english if browser does not supply an accept-language header', done => {
delete req.headers['accept-language'];
getUserLanguage(req, res, () => {
diff --git a/test/api/unit/middlewares/maintenanceMode.test.js b/test/api/unit/middlewares/maintenanceMode.test.js
index 130573c046..59b5185381 100644
--- a/test/api/unit/middlewares/maintenanceMode.test.js
+++ b/test/api/unit/middlewares/maintenanceMode.test.js
@@ -1,14 +1,15 @@
+import nconf from 'nconf';
+import requireAgain from 'require-again';
import {
generateRes,
generateReq,
generateNext,
} from '../../../helpers/api-unit.helper';
-import nconf from 'nconf';
-import requireAgain from 'require-again';
describe('maintenance mode middleware', () => {
- let res, req, next;
- let pathToMaintenanceModeMiddleware = '../../../../website/server/middlewares/maintenanceMode';
+ let res; let req; let
+ next;
+ const pathToMaintenanceModeMiddleware = '../../../../website/server/middlewares/maintenanceMode';
beforeEach(() => {
res = generateRes();
@@ -18,7 +19,7 @@ describe('maintenance mode middleware', () => {
it('does not return 503 error when maintenance mode is off', () => {
req = generateReq();
sandbox.stub(nconf, 'get').withArgs('MAINTENANCE_MODE').returns('false');
- let attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
+ const attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
attachMaintenanceMode(req, res, next);
@@ -29,7 +30,7 @@ describe('maintenance mode middleware', () => {
it('returns 503 error when maintenance mode is on', () => {
req = generateReq();
sandbox.stub(nconf, 'get').withArgs('MAINTENANCE_MODE').returns('true');
- let attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
+ const attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
attachMaintenanceMode(req, res, next);
@@ -39,18 +40,18 @@ describe('maintenance mode middleware', () => {
});
it('renders maintenance page when request type is HTML', () => {
- req = generateReq({headers: {accept: 'text/html'}});
+ req = generateReq({ headers: { accept: 'text/html' } });
sandbox.stub(nconf, 'get').withArgs('MAINTENANCE_MODE').returns('true');
- let attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
+ const attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
attachMaintenanceMode(req, res, next);
expect(res.render).to.have.been.calledOnce;
});
it('sends error message when request type is JSON', () => {
- req = generateReq({headers: {accept: 'application/json'}});
+ req = generateReq({ headers: { accept: 'application/json' } });
sandbox.stub(nconf, 'get').withArgs('MAINTENANCE_MODE').returns('true');
- let attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
+ const attachMaintenanceMode = requireAgain(pathToMaintenanceModeMiddleware).default;
attachMaintenanceMode(req, res, next);
expect(res.send).to.have.been.calledOnce;
diff --git a/test/api/unit/middlewares/redirects.js b/test/api/unit/middlewares/redirects.js
index fdbff0d879..2399717437 100644
--- a/test/api/unit/middlewares/redirects.js
+++ b/test/api/unit/middlewares/redirects.js
@@ -1,14 +1,15 @@
+import nconf from 'nconf';
+import requireAgain from 'require-again';
import {
generateRes,
generateReq,
generateNext,
} from '../../../helpers/api-unit.helper';
-import nconf from 'nconf';
-import requireAgain from 'require-again';
describe('redirects middleware', () => {
- let res, req, next;
- let pathToRedirectsMiddleware = '../../../../website/server/middlewares/redirects';
+ let res; let req; let
+ next;
+ const pathToRedirectsMiddleware = '../../../../website/server/middlewares/redirects';
beforeEach(() => {
res = generateRes();
@@ -18,13 +19,13 @@ describe('redirects middleware', () => {
context('forceSSL', () => {
it('sends http requests to https', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
req.header = sandbox.stub().withArgs('x-forwarded-proto').returns('http');
req.originalUrl = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceSSL(req, res, next);
@@ -33,13 +34,13 @@ describe('redirects middleware', () => {
});
it('does not redirect https forwarded requests', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
req.header = sandbox.stub().withArgs('x-forwarded-proto').returns('https');
req.originalUrl = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceSSL(req, res, next);
@@ -47,13 +48,13 @@ describe('redirects middleware', () => {
});
it('does not redirect outside of production environments', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(false);
req.header = sandbox.stub().withArgs('x-forwarded-proto').returns('http');
req.originalUrl = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceSSL(req, res, next);
@@ -61,13 +62,13 @@ describe('redirects middleware', () => {
});
it('does not redirect if base URL is not https', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('http://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
req.header = sandbox.stub().withArgs('x-forwarded-proto').returns('http');
req.originalUrl = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceSSL(req, res, next);
@@ -75,7 +76,7 @@ describe('redirects middleware', () => {
});
it('does not redirect if passed skip ssl request param is passed with corrrect key', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
nconfStub.withArgs('SKIP_SSL_CHECK_KEY').returns('test-key');
@@ -91,7 +92,7 @@ describe('redirects middleware', () => {
});
it('does redirect if skip ssl request param is passed with incorrrect key', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
nconfStub.withArgs('SKIP_SSL_CHECK_KEY').returns('test-key');
@@ -108,7 +109,7 @@ describe('redirects middleware', () => {
});
it('does redirect if skip ssl check key is not set', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IS_PROD').returns(true);
nconfStub.withArgs('SKIP_SSL_CHECK_KEY').returns(null);
@@ -127,7 +128,7 @@ describe('redirects middleware', () => {
context('forceHabitica', () => {
it('sends requests with differing hostname to base URL host', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('false');
nconfStub.withArgs('IS_PROD').returns(true);
@@ -136,7 +137,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/static/front';
req.url = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
@@ -145,7 +146,7 @@ describe('redirects middleware', () => {
});
it('does not redirect outside of production environments', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('false');
nconfStub.withArgs('IS_PROD').returns(false);
@@ -154,7 +155,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/static/front';
req.url = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
@@ -162,7 +163,7 @@ describe('redirects middleware', () => {
});
it('does not redirect if env is set to ignore redirection', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('true');
nconfStub.withArgs('IS_PROD').returns(true);
@@ -171,7 +172,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/static/front';
req.url = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
@@ -179,7 +180,7 @@ describe('redirects middleware', () => {
});
it('does not redirect if request hostname matches base URL host', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('false');
nconfStub.withArgs('IS_PROD').returns(true);
@@ -188,7 +189,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/static/front';
req.url = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
@@ -196,7 +197,7 @@ describe('redirects middleware', () => {
});
it('does not redirect if request is an API URL', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('false');
nconfStub.withArgs('IS_PROD').returns(true);
@@ -205,7 +206,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/api/v3/challenges';
req.url = '/api/v3/challenges';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
@@ -213,7 +214,7 @@ describe('redirects middleware', () => {
});
it('does not redirect if request method is not GET', () => {
- let nconfStub = sandbox.stub(nconf, 'get');
+ const nconfStub = sandbox.stub(nconf, 'get');
nconfStub.withArgs('BASE_URL').returns('https://habitica.com');
nconfStub.withArgs('IGNORE_REDIRECT').returns('false');
nconfStub.withArgs('IS_PROD').returns(true);
@@ -222,7 +223,7 @@ describe('redirects middleware', () => {
req.originalUrl = '/static/front';
req.url = '/static/front';
- let attachRedirects = requireAgain(pathToRedirectsMiddleware);
+ const attachRedirects = requireAgain(pathToRedirectsMiddleware);
attachRedirects.forceHabitica(req, res, next);
diff --git a/test/api/unit/middlewares/response.js b/test/api/unit/middlewares/response.js
index 2ffc8c6675..b8157287be 100644
--- a/test/api/unit/middlewares/response.js
+++ b/test/api/unit/middlewares/response.js
@@ -7,7 +7,8 @@ import responseMiddleware from '../../../../website/server/middlewares/response'
import packageInfo from '../../../../package.json';
describe('response middleware', () => {
- let res, req, next;
+ let res; let req; let
+ next;
beforeEach(() => {
res = generateRes();
@@ -24,7 +25,7 @@ describe('response middleware', () => {
it('can be used to respond to requests', () => {
responseMiddleware(req, res, next);
- res.respond(200, {field: 1});
+ res.respond(200, { field: 1 });
expect(res.status).to.be.calledOnce;
expect(res.json).to.be.calledOnce;
@@ -32,7 +33,7 @@ describe('response middleware', () => {
expect(res.status).to.be.calledWith(200);
expect(res.json).to.be.calledWith({
success: true,
- data: {field: 1},
+ data: { field: 1 },
notifications: [],
userV: res.locals.user._v,
appVersion: packageInfo.version,
@@ -41,7 +42,7 @@ describe('response middleware', () => {
it('can be passed a third parameter to be used as optional message', () => {
responseMiddleware(req, res, next);
- res.respond(200, {field: 1}, 'hello');
+ res.respond(200, { field: 1 }, 'hello');
expect(res.status).to.be.calledOnce;
expect(res.json).to.be.calledOnce;
@@ -49,7 +50,7 @@ describe('response middleware', () => {
expect(res.status).to.be.calledWith(200);
expect(res.json).to.be.calledWith({
success: true,
- data: {field: 1},
+ data: { field: 1 },
message: 'hello',
notifications: [],
userV: res.locals.user._v,
@@ -59,7 +60,7 @@ describe('response middleware', () => {
it('treats status >= 400 as failures', () => {
responseMiddleware(req, res, next);
- res.respond(403, {field: 1});
+ res.respond(403, { field: 1 });
expect(res.status).to.be.calledOnce;
expect(res.json).to.be.calledOnce;
@@ -67,7 +68,7 @@ describe('response middleware', () => {
expect(res.status).to.be.calledWith(403);
expect(res.json).to.be.calledWith({
success: false,
- data: {field: 1},
+ data: { field: 1 },
notifications: [],
userV: res.locals.user._v,
appVersion: packageInfo.version,
@@ -76,13 +77,13 @@ describe('response middleware', () => {
it('returns userV if a user is authenticated', () => {
responseMiddleware(req, res, next);
- res.respond(200, {field: 1});
+ res.respond(200, { field: 1 });
expect(res.json).to.be.calledOnce;
expect(res.json).to.be.calledWith({
success: true,
- data: {field: 1},
+ data: { field: 1 },
notifications: [],
userV: 0,
appVersion: packageInfo.version,
@@ -90,24 +91,25 @@ describe('response middleware', () => {
});
it('returns notifications if a user is authenticated', () => {
- const user = res.locals.user;
+ const { user } = res.locals;
user.notifications = [
null, // invalid, not an object
- {seen: true}, // invalid, no type or id
- {id: 123}, // invalid, no type
- // {type: 'ABC'}, // invalid, no id, not included here because the id would be added automatically
- {type: 'ABC', id: '123'}, // valid
+ { seen: true }, // invalid, no type or id
+ { id: 123 }, // invalid, no type
+ // invalid, no id, not included here because the id would be added automatically
+ // {type: 'ABC'},
+ { type: 'ABC', id: '123' }, // valid
];
responseMiddleware(req, res, next);
- res.respond(200, {field: 1});
+ res.respond(200, { field: 1 });
expect(res.json).to.be.calledOnce;
expect(res.json).to.be.calledWith({
success: true,
- data: {field: 1},
+ data: { field: 1 },
notifications: [
{
type: 'ABC',
diff --git a/test/api/unit/models/challenge.test.js b/test/api/unit/models/challenge.test.js
index cb4b5562e5..f95908f298 100644
--- a/test/api/unit/models/challenge.test.js
+++ b/test/api/unit/models/challenge.test.js
@@ -1,13 +1,14 @@
+import { each, find } from 'lodash';
import { model as Challenge } from '../../../../website/server/models/challenge';
import { model as Group } from '../../../../website/server/models/group';
import { model as User } from '../../../../website/server/models/user';
import * as Tasks from '../../../../website/server/models/task';
-import common from '../../../../website/common/';
-import { each, find } from 'lodash';
+import common from '../../../../website/common';
describe('Challenge Model', () => {
- let guild, leader, challenge, task;
- let tasksToTest = {
+ let guild; let leader; let challenge; let
+ task;
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -74,11 +75,15 @@ describe('Challenge Model', () => {
it('adds tasks to challenge and challenge members', async () => {
await challenge.addTasks([task]);
- const updatedLeader = await User.findOne({_id: leader._id});
- const updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- const syncedTask = find(updatedLeadersTasks, function findNewTask (updatedLeadersTask) {
- return updatedLeadersTask.type === taskValue.type && updatedLeadersTask.text === taskValue.text;
- });
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => (
+ updatedLeadersTask.type === taskValue.type
+ && updatedLeadersTask.text === taskValue.text
+ ),
+ );
expect(syncedTask).to.exist;
expect(syncedTask.notes).to.eql(task.notes);
@@ -88,18 +93,22 @@ describe('Challenge Model', () => {
it('syncs a challenge to a user', async () => {
await challenge.addTasks([task]);
- let newMember = new User({
+ const newMember = new User({
guilds: [guild._id],
});
await newMember.save();
await challenge.syncToUser(newMember);
- let updatedNewMember = await User.findById(newMember._id);
- let updatedNewMemberTasks = await Tasks.Task.find({_id: { $in: updatedNewMember.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedNewMemberTasks, function findNewTask (updatedNewMemberTask) {
- return updatedNewMemberTask.type === taskValue.type && updatedNewMemberTask.text === taskValue.text;
- });
+ const updatedNewMember = await User.findById(newMember._id);
+ const updatedNewMemberTasks = await Tasks.Task.find({ _id: { $in: updatedNewMember.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(
+ updatedNewMemberTasks,
+ updatedNewMemberTask => (
+ updatedNewMemberTask.type === taskValue.type
+ && updatedNewMemberTask.text === taskValue.text
+ ),
+ );
expect(updatedNewMember.challenges).to.contain(challenge._id);
expect(updatedNewMember.tags[7].id).to.equal(challenge._id);
@@ -111,30 +120,32 @@ describe('Challenge Model', () => {
it('syncs a challenge to a user with the existing task', async () => {
await challenge.addTasks([task]);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, function findNewTask (updatedLeadersTask) {
- return updatedLeadersTask.challenge.taskId === task._id;
- });
+ let updatedLeader = await User.findOne({ _id: leader._id });
+ let updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ let syncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => updatedLeadersTask.challenge.taskId === task._id,
+ );
- let createdAtBefore = syncedTask.createdAt;
- let attributeBefore = syncedTask.attribute;
+ const createdAtBefore = syncedTask.createdAt;
+ const attributeBefore = syncedTask.attribute;
- let newTitle = 'newName';
+ const newTitle = 'newName';
task.text = newTitle;
task.attribute = 'int';
await task.save();
await challenge.syncToUser(leader);
- updatedLeader = await User.findOne({_id: leader._id});
- updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
+ updatedLeader = await User.findOne({ _id: leader._id });
+ updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
- syncedTask = find(updatedLeadersTasks, function findNewTask (updatedLeadersTask) {
- return updatedLeadersTask.challenge.taskId === task._id;
- });
+ syncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => updatedLeadersTask.challenge.taskId === task._id,
+ );
- let createdAtAfter = syncedTask.createdAt;
- let attributeAfter = syncedTask.attribute;
+ const createdAtAfter = syncedTask.createdAt;
+ const attributeAfter = syncedTask.attribute;
expect(createdAtBefore).to.eql(createdAtAfter);
expect(attributeBefore).to.eql(attributeAfter);
@@ -142,10 +153,10 @@ describe('Challenge Model', () => {
});
it('updates tasks to challenge and challenge members', async () => {
- let updatedTaskName = 'Updated Test Habit';
+ const updatedTaskName = 'Updated Test Habit';
await challenge.addTasks([task]);
- let req = {
+ const req = {
body: { text: updatedTaskName },
};
@@ -154,8 +165,8 @@ describe('Challenge Model', () => {
await challenge.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder[`${taskType}s`][0]);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder[`${taskType}s`][0]);
expect(updatedUserTask.text).to.equal(updatedTaskName);
});
@@ -164,8 +175,8 @@ describe('Challenge Model', () => {
await challenge.addTasks([task]);
await challenge.removeTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findOne({_id: updatedLeader.tasksOrder[`${taskType}s`][0]}).exec();
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findOne({ _id: updatedLeader.tasksOrder[`${taskType}s`][0] }).exec();
expect(updatedUserTask.challenge.broken).to.equal('TASK_DELETED');
});
@@ -174,11 +185,15 @@ describe('Challenge Model', () => {
await challenge.addTasks([task]);
await challenge.unlinkTasks(leader, 'remove-all');
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, function findNewTask (updatedLeadersTask) {
- return updatedLeadersTask.type === taskValue.type && updatedLeadersTask.text === taskValue.text;
- });
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => (
+ updatedLeadersTask.type === taskValue.type
+ && updatedLeadersTask.text === taskValue.text
+ ),
+ );
expect(syncedTask).to.not.exist;
});
@@ -187,11 +202,15 @@ describe('Challenge Model', () => {
await challenge.addTasks([task]);
await challenge.unlinkTasks(leader, 'keep-all');
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, function findNewTask (updatedLeadersTask) {
- return updatedLeadersTask.type === taskValue.type && updatedLeadersTask.text === taskValue.text;
- });
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => (
+ updatedLeadersTask.type === taskValue.type
+ && updatedLeadersTask.text === taskValue.text
+ ),
+ );
expect(syncedTask).to.exist;
expect(syncedTask.challenge._id).to.be.undefined;
@@ -212,8 +231,8 @@ describe('Challenge Model', () => {
await challenge.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.habits[0]);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.habits[0]);
expect(updatedUserTask.up).to.equal(true);
expect(updatedUserTask.down).to.equal(false);
@@ -229,8 +248,8 @@ describe('Challenge Model', () => {
task.date = new Date();
await challenge.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.todos[0]);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.todos[0]);
expect(updatedUserTask.date).to.exist;
});
@@ -247,8 +266,8 @@ describe('Challenge Model', () => {
});
await challenge.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.todos[0]);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.todos[0]);
expect(updatedUserTask.checklist.toObject()).to.deep.equal([]);
});
@@ -263,8 +282,8 @@ describe('Challenge Model', () => {
task.everyX = 2;
await challenge.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.dailys[0]);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedUserTask = await Tasks.Task.findById(updatedLeader.tasksOrder.dailys[0]);
expect(updatedUserTask.everyX).to.eql(2);
});
diff --git a/test/api/unit/models/group.test.js b/test/api/unit/models/group.test.js
index 318e569868..85557ba418 100644
--- a/test/api/unit/models/group.test.js
+++ b/test/api/unit/models/group.test.js
@@ -20,7 +20,9 @@ import { TAVERN_ID } from '../../../../website/common/script/constants';
import shared from '../../../../website/common';
describe('Group Model', () => {
- let party, questLeader, participatingMember, sleepingParticipatingMember, nonParticipatingMember, undecidedMember;
+ let party; let questLeader; let participatingMember;
+ let sleepingParticipatingMember; let nonParticipatingMember; let
+ undecidedMember;
beforeEach(async () => {
sandbox.stub(email, 'sendTxn');
@@ -32,7 +34,7 @@ describe('Group Model', () => {
privacy: 'private',
});
- let _progress = {
+ const _progress = {
up: 10,
down: 8,
collectedItems: 5,
@@ -132,13 +134,13 @@ describe('Group Model', () => {
});
it('returns early if user is not in a party', async () => {
- let userWithoutParty = new User();
+ const userWithoutParty = new User();
await userWithoutParty.save();
await Group.processQuestProgress(userWithoutParty, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -150,7 +152,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -159,7 +161,7 @@ describe('Group Model', () => {
it('returns early if user is not on quest', async () => {
await Group.processQuestProgress(nonParticipatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -168,7 +170,7 @@ describe('Group Model', () => {
it('returns early if user has made no progress', async () => {
await Group.processQuestProgress(participatingMember, null);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -180,7 +182,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -194,7 +196,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype._processBossQuest).to.be.calledOnce;
expect(party._processCollectionQuest).to.not.be.called;
@@ -208,7 +210,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(Group.prototype._processCollectionQuest).to.be.calledOnce;
@@ -222,7 +224,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(sleepingParticipatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -236,7 +238,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(sleepingParticipatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party._processBossQuest).to.not.be.called;
expect(party._processCollectionQuest).to.not.be.called;
@@ -260,7 +262,7 @@ describe('Group Model', () => {
it('applies user\'s progress to quest boss hp', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.hp).to.eql(495);
});
@@ -268,7 +270,7 @@ describe('Group Model', () => {
it('sends a chat message about progress', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledOnce;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -286,9 +288,9 @@ describe('Group Model', () => {
it('applies damage only to participating members of party', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -322,9 +324,9 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -350,7 +352,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledTwice;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -360,8 +362,8 @@ describe('Group Model', () => {
});
it('calls finishQuest when boss has <= 0 hp', async () => {
- let quest = questScrolls[party.quest.key];
- let finishQuest = sandbox.spy(Group.prototype, 'finishQuest');
+ const quest = questScrolls[party.quest.key];
+ const finishQuest = sandbox.spy(Group.prototype, 'finishQuest');
progress.up = 999;
@@ -383,13 +385,13 @@ describe('Group Model', () => {
it('applies down progress to boss rage', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.rage).to.eql(10);
});
it('activates rage when progress.down triggers rage bar', async () => {
- let quest = questScrolls[party.quest.key];
+ const quest = questScrolls[party.quest.key];
progress.down = -999;
party.quest.progress.hp = 300;
@@ -397,7 +399,7 @@ describe('Group Model', () => {
await party.save();
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledWith({
message: quest.boss.rage.effect('en'),
@@ -414,7 +416,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.hp).to.eql(500);
});
@@ -434,23 +436,23 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.rage).to.eql(8);
- let drainedUser = await User.findById(participatingMember._id);
+ const drainedUser = await User.findById(participatingMember._id);
expect(drainedUser.stats.mp).to.eql(10);
});
it('activates rage when progress.down triggers rage bar', async () => {
- let quest = questScrolls[party.quest.key];
+ const quest = questScrolls[party.quest.key];
progress.down = -999;
await party.save();
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledWith({
message: quest.boss.rage.effect('en'),
@@ -458,7 +460,7 @@ describe('Group Model', () => {
});
expect(party.quest.progress.rage).to.eql(0);
- let drainedUser = await User.findById(participatingMember._id);
+ const drainedUser = await User.findById(participatingMember._id);
expect(drainedUser.stats.mp).to.eql(0);
});
});
@@ -481,7 +483,7 @@ describe('Group Model', () => {
it('applies user\'s progress to found quest items', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.collect.soapBars).to.eq(5);
});
@@ -495,7 +497,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.progress.collect.fireCoral).to.eq(20);
});
@@ -503,7 +505,7 @@ describe('Group Model', () => {
it('sends a chat message about progress', async () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledOnce;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -522,7 +524,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledOnce;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -547,7 +549,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledOnce;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -572,7 +574,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledOnce;
expect(Group.prototype.sendChat).to.be.calledWithMatch({
@@ -590,7 +592,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(Group.prototype.sendChat).to.be.calledTwice;
expect(Group.prototype.sendChat).to.be.calledWith({
@@ -600,8 +602,8 @@ describe('Group Model', () => {
});
it('calls finishQuest when all items are found', async () => {
- let quest = questScrolls[party.quest.key];
- let finishQuest = sandbox.spy(Group.prototype, 'finishQuest');
+ const quest = questScrolls[party.quest.key];
+ const finishQuest = sandbox.spy(Group.prototype, 'finishQuest');
progress.collectedItems = 999;
@@ -616,7 +618,7 @@ describe('Group Model', () => {
await Group.processQuestProgress(participatingMember, progress);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -659,7 +661,7 @@ describe('Group Model', () => {
});
it('throws an error if only uuids are passed in, but they are not an array', async () => {
- await expect(Group.validateInvitations({ uuids: 'user-id'}, res)).to.eventually.be.rejected.and.eql({
+ await expect(Group.validateInvitations({ uuids: 'user-id' }, res)).to.eventually.be.rejected.and.eql({
httpCode: 400,
message: 'Bad request.',
name: 'BadRequest',
@@ -669,7 +671,7 @@ describe('Group Model', () => {
});
it('throws an error if only emails are passed in, but they are not an array', async () => {
- await expect(Group.validateInvitations({emails: 'user@example.com'}, res)).to.eventually.be.rejected.and.eql({
+ await expect(Group.validateInvitations({ emails: 'user@example.com' }, res)).to.eventually.be.rejected.and.eql({
httpCode: 400,
message: 'Bad request.',
name: 'BadRequest',
@@ -679,91 +681,95 @@ describe('Group Model', () => {
});
it('throws an error if emails are not passed in, and uuid array is empty', async () => {
- await expect(Group.validateInvitations({uuids: []}, res)).to.eventually.be.rejected.and.eql({
- httpCode: 400,
- message: 'Bad request.',
- name: 'BadRequest',
- });
+ await expect(Group.validateInvitations({ uuids: [] }, res))
+ .to.eventually.be.rejected.and.eql({
+ httpCode: 400,
+ message: 'Bad request.',
+ name: 'BadRequest',
+ });
expect(res.t).to.be.calledOnce;
expect(res.t).to.be.calledWith('inviteMustNotBeEmpty');
});
it('throws an error if uuids are not passed in, and email array is empty', async () => {
- await expect(Group.validateInvitations({emails: []}, res)).to.eventually.be.rejected.and.eql({
- httpCode: 400,
- message: 'Bad request.',
- name: 'BadRequest',
- });
+ await expect(Group.validateInvitations({ emails: [] }, res))
+ .to.eventually.be.rejected.and.eql({
+ httpCode: 400,
+ message: 'Bad request.',
+ name: 'BadRequest',
+ });
expect(res.t).to.be.calledOnce;
expect(res.t).to.be.calledWith('inviteMustNotBeEmpty');
});
it('throws an error if uuids and emails are passed in as empty arrays', async () => {
- await expect(Group.validateInvitations({emails: [], uuids: []}, res)).to.eventually.be.rejected.and.eql({
- httpCode: 400,
- message: 'Bad request.',
- name: 'BadRequest',
- });
+ await expect(Group.validateInvitations({ emails: [], uuids: [] }, res))
+ .to.eventually.be.rejected.and.eql({
+ httpCode: 400,
+ message: 'Bad request.',
+ name: 'BadRequest',
+ });
expect(res.t).to.be.calledOnce;
expect(res.t).to.be.calledWith('inviteMustNotBeEmpty');
});
it('throws an error if total invites exceed max invite constant', async () => {
- let uuids = [];
- let emails = [];
+ const uuids = [];
+ const emails = [];
- for (let i = 0; i < INVITES_LIMIT / 2; i++) {
+ for (let i = 0; i < INVITES_LIMIT / 2; i += 1) {
uuids.push(`user-id-${i}`);
emails.push(`user-${i}@example.com`);
}
uuids.push('one-more-uuid'); // to put it over the limit
- await expect(Group.validateInvitations({uuids, emails}, res)).to.eventually.be.rejected.and.eql({
- httpCode: 400,
- message: 'Bad request.',
- name: 'BadRequest',
- });
+ await expect(Group.validateInvitations({ uuids, emails }, res))
+ .to.eventually.be.rejected.and.eql({
+ httpCode: 400,
+ message: 'Bad request.',
+ name: 'BadRequest',
+ });
expect(res.t).to.be.calledOnce;
- expect(res.t).to.be.calledWith('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT });
+ expect(res.t).to.be.calledWith('canOnlyInviteMaxInvites', { maxInvites: INVITES_LIMIT });
});
it('does not throw error if number of invites matches max invite limit', async () => {
- let uuids = [];
- let emails = [];
+ const uuids = [];
+ const emails = [];
- for (let i = 0; i < INVITES_LIMIT / 2; i++) {
+ for (let i = 0; i < INVITES_LIMIT / 2; i += 1) {
uuids.push(`user-id-${i}`);
emails.push(`user-${i}@example.com`);
}
- await Group.validateInvitations({uuids, emails}, res);
+ await Group.validateInvitations({ uuids, emails }, res);
expect(res.t).to.not.be.called;
});
it('does not throw an error if only user ids are passed in', async () => {
- await Group.validateInvitations({uuids: ['user-id', 'user-id2']}, res);
+ await Group.validateInvitations({ uuids: ['user-id', 'user-id2'] }, res);
expect(res.t).to.not.be.called;
});
it('does not throw an error if only emails are passed in', async () => {
- await Group.validateInvitations({emails: ['user1@example.com', 'user2@example.com']}, res);
+ await Group.validateInvitations({ emails: ['user1@example.com', 'user2@example.com'] }, res);
expect(res.t).to.not.be.called;
});
it('does not throw an error if both uuids and emails are passed in', async () => {
- await Group.validateInvitations({uuids: ['user-id', 'user-id2'], emails: ['user1@example.com', 'user2@example.com']}, res);
+ await Group.validateInvitations({ uuids: ['user-id', 'user-id2'], emails: ['user1@example.com', 'user2@example.com'] }, res);
expect(res.t).to.not.be.called;
});
it('does not throw an error if uuids are passed in and emails are an empty array', async () => {
- await Group.validateInvitations({uuids: ['user-id', 'user-id2'], emails: []}, res);
+ await Group.validateInvitations({ uuids: ['user-id', 'user-id2'], emails: [] }, res);
expect(res.t).to.not.be.called;
});
it('does not throw an error if emails are passed in and uuids are an empty array', async () => {
- await Group.validateInvitations({uuids: [], emails: ['user1@example.com', 'user2@example.com']}, res);
+ await Group.validateInvitations({ uuids: [], emails: ['user1@example.com', 'user2@example.com'] }, res);
expect(res.t).to.not.be.called;
});
});
@@ -777,7 +783,7 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -792,7 +798,7 @@ describe('Group Model', () => {
bossDamage: 3.7,
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -806,7 +812,7 @@ describe('Group Model', () => {
userDamage: 15.3,
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -818,7 +824,7 @@ describe('Group Model', () => {
quest: 'lostMasterclasser3',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -830,7 +836,7 @@ describe('Group Model', () => {
quest: 'lostMasterclasser3',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -848,7 +854,7 @@ describe('Group Model', () => {
},
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -859,7 +865,7 @@ describe('Group Model', () => {
type: 'all_items_found',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -873,7 +879,7 @@ describe('Group Model', () => {
spell: 'earth',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -888,7 +894,7 @@ describe('Group Model', () => {
target: participatingMember.profile.name,
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -901,7 +907,7 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -914,7 +920,7 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -926,7 +932,7 @@ describe('Group Model', () => {
quest: 'stressbeast',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -938,7 +944,7 @@ describe('Group Model', () => {
quest: 'stressbeast',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -951,7 +957,7 @@ describe('Group Model', () => {
scene: 'market',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -963,7 +969,7 @@ describe('Group Model', () => {
quest: 'stressbeast',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
@@ -976,7 +982,7 @@ describe('Group Model', () => {
task: 'Feed the pet',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
translationCheck(toJSON.chat[0].text);
});
});
@@ -990,7 +996,7 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
expect(toJSON.chat.length).to.equal(1);
});
@@ -1002,8 +1008,8 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- const admin = new User({'contributor.admin': true});
- let toJSON = await Group.toJSONCleanChat(party, admin);
+ const admin = new User({ 'contributor.admin': true });
+ const toJSON = await Group.toJSONCleanChat(party, admin);
expect(toJSON.chat.length).to.equal(1);
});
@@ -1015,7 +1021,7 @@ describe('Group Model', () => {
quest: 'basilist',
},
}];
- let toJSON = await Group.toJSONCleanChat(party, questLeader);
+ const toJSON = await Group.toJSONCleanChat(party, questLeader);
expect(toJSON.chat.length).to.equal(0);
});
});
@@ -1041,8 +1047,9 @@ describe('Group Model', () => {
});
describe('#checkChatSpam', () => {
- let testUser, testTime, tavern;
- let testUserID = '1';
+ let testUser; let testTime; let
+ tavern;
+ const testUserID = '1';
beforeEach(async () => {
testTime = Date.now();
@@ -1059,32 +1066,33 @@ describe('Group Model', () => {
});
function generateTestMessage (overrides = {}) {
- return Object.assign({}, {
+ return {
text: 'test message',
uuid: testUserID,
timestamp: testTime,
- }, overrides);
+ ...overrides,
+ };
}
it('group that is not the tavern returns false, while tavern returns true', async () => {
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
party.chat.push(generateTestMessage());
}
expect(party.checkChatSpam(testUser)).to.eql(false);
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
tavern.chat.push(generateTestMessage());
}
expect(tavern.checkChatSpam(testUser)).to.eql(true);
});
it('high enough contributor returns false', async () => {
- let highContributor = testUser;
+ const highContributor = testUser;
highContributor.contributor = {
level: SPAM_MIN_EXEMPT_CONTRIB_LEVEL,
};
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
tavern.chat.push(generateTestMessage());
}
@@ -1097,17 +1105,17 @@ describe('Group Model', () => {
});
it('user has not reached limit but another one has returns false', async () => {
- let otherUserID = '2';
+ const otherUserID = '2';
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
- tavern.chat.push(generateTestMessage({uuid: otherUserID}));
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
+ tavern.chat.push(generateTestMessage({ uuid: otherUserID }));
}
expect(tavern.checkChatSpam(testUser)).to.eql(false);
});
it('user messages is less than the limit returns false', async () => {
- for (let i = 0; i < SPAM_MESSAGE_LIMIT - 1; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT - 1; i += 1) {
tavern.chat.push(generateTestMessage());
}
@@ -1115,17 +1123,17 @@ describe('Group Model', () => {
});
it('user has reached the message limit outside of window returns false', async () => {
- for (let i = 0; i < SPAM_MESSAGE_LIMIT - 1; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT - 1; i += 1) {
tavern.chat.push(generateTestMessage());
}
- let earlierTimestamp = testTime - SPAM_WINDOW_LENGTH - 1;
- tavern.chat.push(generateTestMessage({timestamp: earlierTimestamp}));
+ const earlierTimestamp = testTime - SPAM_WINDOW_LENGTH - 1;
+ tavern.chat.push(generateTestMessage({ timestamp: earlierTimestamp }));
expect(tavern.checkChatSpam(testUser)).to.eql(false);
});
it('user has posted too many messages in limit returns true', async () => {
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
tavern.chat.push(generateTestMessage());
}
@@ -1147,7 +1155,7 @@ describe('Group Model', () => {
await party.leave(participatingMember);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party.quest.members).to.eql({
[questLeader._id]: true,
[sleepingParticipatingMember._id]: true,
@@ -1163,7 +1171,7 @@ describe('Group Model', () => {
await party.leave(nonParticipatingMember);
await party.leave(undecidedMember);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party).to.not.exist;
});
@@ -1178,7 +1186,7 @@ describe('Group Model', () => {
message: shared.i18n.t('cannotDeleteActiveGroup'),
});
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party).to.exist;
expect(party.memberCount).to.eql(1);
});
@@ -1194,19 +1202,19 @@ describe('Group Model', () => {
message: shared.i18n.t('leaderCannotLeaveGroupWithActiveGroup'),
});
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party).to.exist;
expect(party.memberCount).to.eql(1);
});
it('deletes a private group when the last member leaves and a subscription is cancelled', async () => {
- let guild = new Group({
+ const guild = new Group({
name: 'test guild',
type: 'guild',
memberCount: 1,
});
- let leader = new User({
+ const leader = new User({
guilds: [guild._id],
});
@@ -1222,7 +1230,7 @@ describe('Group Model', () => {
await guild.leave(leader);
- party = await Group.findOne({_id: guild._id});
+ party = await Group.findOne({ _id: guild._id });
expect(party).to.not.exist;
});
@@ -1235,7 +1243,7 @@ describe('Group Model', () => {
await party.leave(nonParticipatingMember);
await party.leave(undecidedMember);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party).to.exist;
});
@@ -1244,7 +1252,7 @@ describe('Group Model', () => {
await party.leave(participatingMember);
- party = await Group.findOne({_id: party._id});
+ party = await Group.findOne({ _id: party._id });
expect(party).to.exist;
});
@@ -1255,7 +1263,7 @@ describe('Group Model', () => {
memberCount: 1,
});
- let leader = new User({
+ const leader = new User({
guilds: [guild._id],
});
@@ -1268,7 +1276,7 @@ describe('Group Model', () => {
await guild.leave(leader);
- guild = await Group.findOne({_id: guild._id});
+ guild = await Group.findOne({ _id: guild._id });
expect(guild).to.not.exist;
});
@@ -1279,11 +1287,11 @@ describe('Group Model', () => {
memberCount: 1,
});
- let leader = new User({
+ const leader = new User({
guilds: [guild._id],
});
- let member = new User({
+ const member = new User({
guilds: [guild._id],
});
@@ -1297,7 +1305,7 @@ describe('Group Model', () => {
await guild.leave(member);
- guild = await Group.findOne({_id: guild._id});
+ guild = await Group.findOne({ _id: guild._id });
expect(guild).to.exist;
});
});
@@ -1309,7 +1317,8 @@ describe('Group Model', () => {
it('formats message', () => {
const chatMessage = party.sendChat({
- message: 'a new message', user: {
+ message: 'a new message',
+ user: {
_id: 'user-id',
profile: { name: 'user name' },
contributor: {
@@ -1322,8 +1331,8 @@ describe('Group Model', () => {
return 'backer object';
},
},
- }}
- );
+ },
+ });
const chat = chatMessage;
@@ -1340,7 +1349,7 @@ describe('Group Model', () => {
});
it('formats message as system if no user is passed in', () => {
- const chat = party.sendChat({message: 'a system message'});
+ const chat = party.sendChat({ message: 'a system message' });
expect(chat.text).to.eql('a system message');
expect(validator.isUUID(chat.id)).to.eql(true);
@@ -1355,7 +1364,7 @@ describe('Group Model', () => {
});
it('updates users about new messages in party', () => {
- party.sendChat({message: 'message'});
+ party.sendChat({ message: 'message' });
expect(User.update).to.be.calledOnce;
expect(User.update).to.be.calledWithMatch({
@@ -1365,11 +1374,11 @@ describe('Group Model', () => {
});
it('updates users about new messages in group', () => {
- let group = new Group({
+ const group = new Group({
type: 'guild',
});
- group.sendChat({message: 'message'});
+ group.sendChat({ message: 'message' });
expect(User.update).to.be.calledOnce;
expect(User.update).to.be.calledWithMatch({
@@ -1379,7 +1388,7 @@ describe('Group Model', () => {
});
it('does not send update to user that sent the message', () => {
- party.sendChat({message: 'message', user: {_id: 'user-id', profile: { name: 'user' }}});
+ party.sendChat({ message: 'message', user: { _id: 'user-id', profile: { name: 'user' } } });
expect(User.update).to.be.calledOnce;
expect(User.update).to.be.calledWithMatch({
@@ -1391,7 +1400,7 @@ describe('Group Model', () => {
it('skips sending new message notification for guilds with > 5000 members', () => {
party.memberCount = 5001;
- party.sendChat({message: 'message'});
+ party.sendChat({ message: 'message' });
expect(User.update).to.not.be.called;
});
@@ -1399,7 +1408,7 @@ describe('Group Model', () => {
it('skips sending messages to the tavern', () => {
party._id = TAVERN_ID;
- party.sendChat({message: 'message'});
+ party.sendChat({ message: 'message' });
expect(User.update).to.not.be.called;
});
@@ -1408,7 +1417,7 @@ describe('Group Model', () => {
describe('#startQuest', () => {
context('Failure Conditions', () => {
it('throws an error if group is not a party', async () => {
- let guild = new Group({
+ const guild = new Group({
type: 'guild',
});
@@ -1448,7 +1457,7 @@ describe('Group Model', () => {
});
it('sets up boss quest', () => {
- let bossQuest = questScrolls.whale;
+ const bossQuest = questScrolls.whale;
party.quest.key = bossQuest.key;
party.startQuest(participatingMember);
@@ -1457,7 +1466,7 @@ describe('Group Model', () => {
});
it('sets up rage meter for rage boss quest', () => {
- let rageBossQuest = questScrolls.trex_undead;
+ const rageBossQuest = questScrolls.trex_undead;
party.quest.key = rageBossQuest.key;
party.startQuest(participatingMember);
@@ -1466,7 +1475,7 @@ describe('Group Model', () => {
});
it('sets up collection quest', () => {
- let collectionQuest = questScrolls.vice2;
+ const collectionQuest = questScrolls.vice2;
party.quest.key = collectionQuest.key;
party.startQuest(participatingMember);
@@ -1476,7 +1485,7 @@ describe('Group Model', () => {
});
it('sets up collection quest with multiple items', () => {
- let collectionQuest = questScrolls.evilsanta2;
+ const collectionQuest = questScrolls.evilsanta2;
party.quest.key = collectionQuest.key;
party.startQuest(participatingMember);
@@ -1489,7 +1498,7 @@ describe('Group Model', () => {
it('prunes non-participating members from quest members object', () => {
party.startQuest(participatingMember);
- let expectedQuestMembers = {};
+ const expectedQuestMembers = {};
expectedQuestMembers[questLeader._id] = true;
expectedQuestMembers[participatingMember._id] = true;
expectedQuestMembers[sleepingParticipatingMember._id] = true;
@@ -1536,7 +1545,7 @@ describe('Group Model', () => {
it('does not apply updates to nonparticipating members', async () => {
await party.startQuest(participatingMember);
- nonParticipatingMember = await User.findById(nonParticipatingMember ._id);
+ nonParticipatingMember = await User.findById(nonParticipatingMember._id);
undecidedMember = await User.findById(undecidedMember._id);
expect(nonParticipatingMember.party.quest.key).to.not.eql('whale');
@@ -1562,8 +1571,8 @@ describe('Group Model', () => {
expect(email.sendTxn).to.be.calledOnce;
- let memberIds = _.map(email.sendTxn.args[0][0], '_id');
- let typeOfEmail = email.sendTxn.args[0][1];
+ const memberIds = _.map(email.sendTxn.args[0][0], '_id');
+ const typeOfEmail = email.sendTxn.args[0][1];
expect(memberIds).to.have.a.lengthOf(3);
expect(memberIds).to.include(participatingMember._id);
@@ -1596,7 +1605,11 @@ describe('Group Model', () => {
},
}];
- await Promise.all([participatingMember.save(), sleepingParticipatingMember.save(), questLeader.save()]);
+ await Promise.all([
+ participatingMember.save(),
+ sleepingParticipatingMember.save(),
+ questLeader.save(),
+ ]);
await party.startQuest(nonParticipatingMember);
@@ -1604,10 +1617,10 @@ describe('Group Model', () => {
expect(questActivityWebhook.send).to.be.calledThrice; // for 3 participating members
- let args = questActivityWebhook.send.args[0];
- let webhooks = args[0].webhooks;
- let webhookOwner = args[0]._id;
- let options = args[1];
+ const args = questActivityWebhook.send.args[0];
+ const { webhooks } = args[0];
+ const webhookOwner = args[0]._id;
+ const options = args[1];
expect(webhooks).to.have.a.lengthOf(1);
if (webhookOwner === questLeader._id) {
@@ -1638,7 +1651,7 @@ describe('Group Model', () => {
expect(email.sendTxn).to.be.calledOnce;
- let memberIds = _.map(email.sendTxn.args[0][0], '_id');
+ const memberIds = _.map(email.sendTxn.args[0][0], '_id');
expect(memberIds).to.have.a.lengthOf(1);
expect(memberIds).to.not.include(participatingMember._id);
@@ -1662,7 +1675,7 @@ describe('Group Model', () => {
expect(email.sendTxn).to.be.calledOnce;
- let memberIds = _.map(email.sendTxn.args[0][0], '_id');
+ const memberIds = _.map(email.sendTxn.args[0][0], '_id');
expect(memberIds).to.have.a.lengthOf(2);
expect(memberIds).to.not.include(participatingMember._id);
@@ -1675,7 +1688,9 @@ describe('Group Model', () => {
await party.startQuest(nonParticipatingMember);
- let members = [questLeader._id, participatingMember._id, sleepingParticipatingMember._id];
+ const members = [
+ questLeader._id, participatingMember._id, sleepingParticipatingMember._id,
+ ];
expect(User.update).to.be.calledWith(
{ _id: { $in: members } },
@@ -1685,7 +1700,7 @@ describe('Group Model', () => {
'party.quest.progress.down': 0,
'party.quest.completed': null,
},
- }
+ },
);
});
@@ -1700,14 +1715,14 @@ describe('Group Model', () => {
$inc: {
'items.quests.whale': -1,
},
- }
+ },
);
});
it('modifies the participating initiating user directly', async () => {
await party.startQuest(participatingMember);
- let userQuest = participatingMember.party.quest;
+ const userQuest = participatingMember.party.quest;
expect(userQuest.key).to.eql('whale');
expect(userQuest.progress.up).to.eql(10);
@@ -1748,15 +1763,11 @@ describe('Group Model', () => {
});
describe('user update retry failures', () => {
- let successfulMock = {
- exec: () => {
- return Promise.resolve({raw: 'sucess'});
- },
+ const successfulMock = {
+ exec: () => Promise.resolve({ raw: 'sucess' }),
};
- let failedMock = {
- exec: () => {
- return Promise.reject(new Error('error'));
- },
+ const failedMock = {
+ exec: () => Promise.reject(new Error('error')),
};
it('doesn\'t retry successful operations', async () => {
@@ -1768,7 +1779,7 @@ describe('Group Model', () => {
});
it('stops retrying when a successful update has occurred', async () => {
- let updateStub = sandbox.stub(User, 'update');
+ const updateStub = sandbox.stub(User, 'update');
updateStub.onCall(0).returns(failedMock);
updateStub.returns(successfulMock);
@@ -1789,7 +1800,7 @@ describe('Group Model', () => {
it('gives out achievements', async () => {
await party.finishQuest(quest);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -1828,7 +1839,7 @@ describe('Group Model', () => {
await questLeader.save();
await party.finishQuest(quest);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -1867,7 +1878,7 @@ describe('Group Model', () => {
await questLeader.save();
await party.finishQuest(quest);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -1897,7 +1908,7 @@ describe('Group Model', () => {
await questLeader.save();
await party.finishQuest(quest);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -1915,7 +1926,7 @@ describe('Group Model', () => {
it('gives xp and gold', async () => {
await party.finishQuest(quest);
- let [
+ const [
updatedLeader,
updatedParticipatingMember,
updatedSleepingParticipatingMember,
@@ -1935,91 +1946,91 @@ describe('Group Model', () => {
context('drops', () => {
it('awards gear', async () => {
- let gearQuest = questScrolls.vice3;
+ const gearQuest = questScrolls.vice3;
await party.finishQuest(gearQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.gear.owned.weapon_special_2).to.eql(true);
});
it('awards eggs', async () => {
- let eggQuest = questScrolls.vice3;
+ const eggQuest = questScrolls.vice3;
await party.finishQuest(eggQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.eggs.Dragon).to.eql(2);
});
it('awards food', async () => {
- let foodQuest = questScrolls.moonstone3;
+ const foodQuest = questScrolls.moonstone3;
await party.finishQuest(foodQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.food.RottenMeat).to.eql(5);
});
it('awards hatching potions', async () => {
- let hatchingPotionQuest = questScrolls.vice3;
+ const hatchingPotionQuest = questScrolls.vice3;
await party.finishQuest(hatchingPotionQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.hatchingPotions.Shade).to.eql(2);
});
it('awards quest scrolls to owner', async () => {
- let questAwardQuest = questScrolls.vice2;
+ const questAwardQuest = questScrolls.vice2;
await party.finishQuest(questAwardQuest);
- let updatedLeader = await User.findById(questLeader._id);
+ const updatedLeader = await User.findById(questLeader._id);
expect(updatedLeader.items.quests.vice3).to.eql(1);
});
it('awards non quest leader rewards to quest leader', async () => {
- let gearQuest = questScrolls.vice3;
+ const gearQuest = questScrolls.vice3;
await party.finishQuest(gearQuest);
- let updatedLeader = await User.findById(questLeader._id);
+ const updatedLeader = await User.findById(questLeader._id);
expect(updatedLeader.items.gear.owned.weapon_special_2).to.eql(true);
});
it('doesn\'t award quest owner rewards to all participants', async () => {
- let questAwardQuest = questScrolls.vice2;
+ const questAwardQuest = questScrolls.vice2;
await party.finishQuest(questAwardQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.quests.vice3).to.not.exist;
});
it('awards pets', async () => {
- let petQuest = questScrolls.evilsanta2;
+ const petQuest = questScrolls.evilsanta2;
await party.finishQuest(petQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.pets['BearCub-Polar']).to.eql(5);
});
it('awards mounts', async () => {
- let mountQuest = questScrolls.evilsanta;
+ const mountQuest = questScrolls.evilsanta;
await party.finishQuest(mountQuest);
- let updatedParticipatingMember = await User.findById(participatingMember._id);
+ const updatedParticipatingMember = await User.findById(participatingMember._id);
expect(updatedParticipatingMember.items.mounts['BearCub-Polar']).to.eql(true);
});
@@ -2079,7 +2090,11 @@ describe('Group Model', () => {
},
}];
- await Promise.all([participatingMember.save(), sleepingParticipatingMember.save(), questLeader.save()]);
+ await Promise.all([
+ participatingMember.save(),
+ sleepingParticipatingMember.save(),
+ questLeader.save(),
+ ]);
await party.finishQuest(quest);
@@ -2087,9 +2102,9 @@ describe('Group Model', () => {
expect(questActivityWebhook.send).to.be.calledOnce;
- let args = questActivityWebhook.send.args[0];
- let webhooks = args[0].webhooks;
- let options = args[1];
+ const args = questActivityWebhook.send.args[0];
+ const { webhooks } = args[0];
+ const options = args[1];
expect(webhooks).to.have.a.lengthOf(1);
expect(webhooks[0].id).to.eql(participatingMember.webhooks[0].id);
@@ -2118,7 +2133,7 @@ describe('Group Model', () => {
it('sets quest completed to the world quest key', async () => {
await party.finishQuest(tavernQuest);
- let updatedLeader = await User.findById(questLeader._id);
+ const updatedLeader = await User.findById(questLeader._id);
expect(updatedLeader.party.quest.completed).to.eql(tavernQuest.key);
});
@@ -2133,7 +2148,7 @@ describe('Group Model', () => {
it('looks for users in specified guild with webhooks', () => {
sandbox.spy(User, 'find');
- let guild = new Group({
+ const guild = new Group({
type: 'guild',
});
@@ -2167,13 +2182,13 @@ describe('Group Model', () => {
});
it('sends webhooks for users with webhooks', async () => {
- let guild = new Group({
+ const guild = new Group({
name: 'some guild',
type: 'guild',
});
- let chat = {message: 'text'};
- let memberWithWebhook = new User({
+ const chat = { message: 'text' };
+ const memberWithWebhook = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
@@ -2183,10 +2198,10 @@ describe('Group Model', () => {
},
}],
});
- let memberWithoutWebhook = new User({
+ const memberWithoutWebhook = new User({
guilds: [guild._id],
});
- let nonMemberWithWebhooks = new User({
+ const nonMemberWithWebhooks = new User({
webhooks: [{
type: 'groupChatReceived',
url: 'http://a-different-url.com',
@@ -2212,9 +2227,9 @@ describe('Group Model', () => {
expect(groupChatReceivedWebhook.send).to.be.calledOnce;
- let args = groupChatReceivedWebhook.send.args[0];
- let webhooks = args[0].webhooks;
- let options = args[1];
+ const args = groupChatReceivedWebhook.send.args[0];
+ const { webhooks } = args[0];
+ const options = args[1];
expect(webhooks).to.have.a.lengthOf(1);
expect(webhooks[0].id).to.eql(memberWithWebhook.webhooks[0].id);
@@ -2223,12 +2238,12 @@ describe('Group Model', () => {
});
it('sends webhooks for users with webhooks triggered by system messages', async () => {
- let guild = new Group({
+ const guild = new Group({
name: 'some guild',
type: 'guild',
});
- let memberWithWebhook = new User({
+ const memberWithWebhook = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
@@ -2238,10 +2253,10 @@ describe('Group Model', () => {
},
}],
});
- let memberWithoutWebhook = new User({
+ const memberWithoutWebhook = new User({
guilds: [guild._id],
});
- let nonMemberWithWebhooks = new User({
+ const nonMemberWithWebhooks = new User({
webhooks: [{
type: 'groupChatReceived',
url: 'http://a-different-url.com',
@@ -2261,16 +2276,16 @@ describe('Group Model', () => {
await guild.save();
- const groupMessage = guild.sendChat({message: 'Test message.'});
+ const groupMessage = guild.sendChat({ message: 'Test message.' });
await groupMessage.save();
await sleep();
expect(groupChatReceivedWebhook.send).to.be.calledOnce;
- let args = groupChatReceivedWebhook.send.args[0];
- let webhooks = args[0].webhooks;
- let options = args[1];
+ const args = groupChatReceivedWebhook.send.args[0];
+ const { webhooks } = args[0];
+ const options = args[1];
expect(webhooks).to.have.a.lengthOf(1);
expect(webhooks[0].id).to.eql(memberWithWebhook.webhooks[0].id);
@@ -2279,13 +2294,13 @@ describe('Group Model', () => {
});
it('sends webhooks for each user with webhooks in group', async () => {
- let guild = new Group({
+ const guild = new Group({
name: 'some guild',
type: 'guild',
});
- let chat = {message: 'text'};
- let memberWithWebhook = new User({
+ const chat = { message: 'text' };
+ const memberWithWebhook = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
@@ -2295,7 +2310,7 @@ describe('Group Model', () => {
},
}],
});
- let memberWithWebhook2 = new User({
+ const memberWithWebhook2 = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
@@ -2305,7 +2320,7 @@ describe('Group Model', () => {
},
}],
});
- let memberWithWebhook3 = new User({
+ const memberWithWebhook3 = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
@@ -2332,10 +2347,16 @@ describe('Group Model', () => {
expect(groupChatReceivedWebhook.send).to.be.calledThrice;
- let args = groupChatReceivedWebhook.send.args;
- expect(args.find(arg => arg[0].webhooks[0].id === memberWithWebhook.webhooks[0].id)).to.be.exist;
- expect(args.find(arg => arg[0].webhooks[0].id === memberWithWebhook2.webhooks[0].id)).to.be.exist;
- expect(args.find(arg => arg[0].webhooks[0].id === memberWithWebhook3.webhooks[0].id)).to.be.exist;
+ const { args } = groupChatReceivedWebhook.send;
+ expect(args.find(
+ arg => arg[0].webhooks[0].id === memberWithWebhook.webhooks[0].id,
+ )).to.be.exist;
+ expect(args.find(
+ arg => arg[0].webhooks[0].id === memberWithWebhook2.webhooks[0].id,
+ )).to.be.exist;
+ expect(args.find(
+ arg => arg[0].webhooks[0].id === memberWithWebhook3.webhooks[0].id,
+ )).to.be.exist;
});
});
diff --git a/test/api/unit/models/group_tasks.test.js b/test/api/unit/models/group_tasks.test.js
index 21cfd9ef2b..848b4b0792 100644
--- a/test/api/unit/models/group_tasks.test.js
+++ b/test/api/unit/models/group_tasks.test.js
@@ -1,12 +1,13 @@
+import { each, find, findIndex } from 'lodash';
import { model as Challenge } from '../../../../website/server/models/challenge';
import { model as Group } from '../../../../website/server/models/group';
import { model as User } from '../../../../website/server/models/user';
import * as Tasks from '../../../../website/server/models/task';
-import { each, find, findIndex } from 'lodash';
describe('Group Task Methods', () => {
- let guild, leader, challenge, task;
- let tasksToTest = {
+ let guild; let leader; let challenge; let
+ task;
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -79,9 +80,9 @@ describe('Group Task Methods', () => {
it('syncs an assigned task to a user', async () => {
await guild.syncTask(task, leader);
- let updatedLeader = await User.findOne({_id: leader._id});
- let tagIndex = findIndex(updatedLeader.tags, {id: guild._id});
- let newTag = updatedLeader.tags[tagIndex];
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const tagIndex = findIndex(updatedLeader.tags, { id: guild._id });
+ const newTag = updatedLeader.tags[tagIndex];
expect(newTag.id).to.equal(guild._id);
expect(newTag.name).to.equal(guild.name);
@@ -91,9 +92,9 @@ describe('Group Task Methods', () => {
it('create tags for a user when task is synced', async () => {
await guild.syncTask(task, leader);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
expect(task.group.assignedUsers).to.contain(leader._id);
expect(syncedTask).to.exist;
@@ -101,13 +102,13 @@ describe('Group Task Methods', () => {
it('syncs updated info for assigned task to a user', async () => {
await guild.syncTask(task, leader);
- let updatedTaskName = 'Update Task name';
+ const updatedTaskName = 'Update Task name';
task.text = updatedTaskName;
await guild.syncTask(task, leader);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
expect(task.group.assignedUsers).to.contain(leader._id);
expect(syncedTask).to.exist;
@@ -117,9 +118,9 @@ describe('Group Task Methods', () => {
it('syncs checklist items to an assigned user', async () => {
await guild.syncTask(task, leader);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
if (task.type !== 'daily' && task.type !== 'todo') return;
@@ -141,19 +142,19 @@ describe('Group Task Methods', () => {
});
it('syncs updated info for assigned task to all users', async () => {
- let updatedTaskName = 'Update Task name';
+ const updatedTaskName = 'Update Task name';
task.text = updatedTaskName;
task.group.approval.required = true;
await guild.updateTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
- let updatedMember = await User.findOne({_id: newMember._id});
- let updatedMemberTasks = await Tasks.Task.find({_id: { $in: updatedMember.tasksOrder[`${taskType}s`]}});
- let syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
+ const updatedMember = await User.findOne({ _id: newMember._id });
+ const updatedMemberTasks = await Tasks.Task.find({ _id: { $in: updatedMember.tasksOrder[`${taskType}s`] } });
+ const syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
expect(task.group.assignedUsers).to.contain(leader._id);
expect(syncedTask).to.exist;
@@ -169,22 +170,22 @@ describe('Group Task Methods', () => {
it('syncs a new checklist item to all assigned users', async () => {
if (task.type !== 'daily' && task.type !== 'todo') return;
- let newCheckListItem = {
+ const newCheckListItem = {
text: 'Checklist Item 1',
completed: false,
};
task.checklist.push(newCheckListItem);
- await guild.updateTask(task, {newCheckListItem});
+ await guild.updateTask(task, { newCheckListItem });
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
- let updatedMember = await User.findOne({_id: newMember._id});
- let updatedMemberTasks = await Tasks.Task.find({_id: { $in: updatedMember.tasksOrder[`${taskType}s`]}});
- let syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
+ const updatedMember = await User.findOne({ _id: newMember._id });
+ const updatedMemberTasks = await Tasks.Task.find({ _id: { $in: updatedMember.tasksOrder[`${taskType}s`] } });
+ const syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
expect(syncedTask.checklist.length).to.equal(task.checklist.length);
expect(syncedTask.checklist[1].text).to.equal(task.checklist[1].text);
@@ -195,20 +196,20 @@ describe('Group Task Methods', () => {
it('syncs updated info for checklist in assigned task to all users when flag is passed', async () => {
if (task.type !== 'daily' && task.type !== 'todo') return;
- let updateCheckListText = 'Updated checklist item';
+ const updateCheckListText = 'Updated checklist item';
if (task.checklist) {
task.checklist[0].text = updateCheckListText;
}
- await guild.updateTask(task, {updateCheckListItems: [task.checklist[0]]});
+ await guild.updateTask(task, { updateCheckListItems: [task.checklist[0]] });
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
- let updatedMember = await User.findOne({_id: newMember._id});
- let updatedMemberTasks = await Tasks.Task.find({_id: { $in: updatedMember.tasksOrder[`${taskType}s`]}});
- let syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
+ const updatedMember = await User.findOne({ _id: newMember._id });
+ const updatedMemberTasks = await Tasks.Task.find({ _id: { $in: updatedMember.tasksOrder[`${taskType}s`] } });
+ const syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
expect(syncedTask.checklist.length).to.equal(task.checklist.length);
expect(syncedTask.checklist[0].text).to.equal(updateCheckListText);
@@ -219,15 +220,15 @@ describe('Group Task Methods', () => {
it('removes a checklist item in assigned task to all users when flag is passed with checklist id', async () => {
if (task.type !== 'daily' && task.type !== 'todo') return;
- await guild.updateTask(task, {removedCheckListItemId: task.checklist[0].id});
+ await guild.updateTask(task, { removedCheckListItemId: task.checklist[0].id });
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
- let updatedMember = await User.findOne({_id: newMember._id});
- let updatedMemberTasks = await Tasks.Task.find({_id: { $in: updatedMember.tasksOrder[`${taskType}s`]}});
- let syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
+ const updatedMember = await User.findOne({ _id: newMember._id });
+ const updatedMemberTasks = await Tasks.Task.find({ _id: { $in: updatedMember.tasksOrder[`${taskType}s`] } });
+ const syncedMemberTask = find(updatedMemberTasks, findLinkedTask);
expect(syncedTask.checklist.length).to.equal(0);
expect(syncedMemberTask.checklist.length).to.equal(0);
@@ -238,9 +239,9 @@ describe('Group Task Methods', () => {
await guild.syncTask(task, leader);
await guild.removeTask(task);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
expect(syncedTask.group.broken).to.equal('TASK_DELETED');
});
@@ -249,9 +250,9 @@ describe('Group Task Methods', () => {
await guild.syncTask(task, leader);
await guild.unlinkTask(task, leader, 'remove-all');
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ const updatedLeader = await User.findOne({ _id: leader._id });
+ const updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
expect(task.group.assignedUsers).to.not.contain(leader._id);
expect(syncedTask).to.not.exist;
@@ -260,17 +261,18 @@ describe('Group Task Methods', () => {
it('unlinks and keeps group tasks for a user when keep-all is specified', async () => {
await guild.syncTask(task, leader);
- let updatedLeader = await User.findOne({_id: leader._id});
- let updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let syncedTask = find(updatedLeadersTasks, findLinkedTask);
+ let updatedLeader = await User.findOne({ _id: leader._id });
+ let updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const syncedTask = find(updatedLeadersTasks, findLinkedTask);
await guild.unlinkTask(task, leader, 'keep-all');
- updatedLeader = await User.findOne({_id: leader._id});
- updatedLeadersTasks = await Tasks.Task.find({_id: { $in: updatedLeader.tasksOrder[`${taskType}s`]}});
- let updatedSyncedTask = find(updatedLeadersTasks, function findUpdatedLinkedTask (updatedLeadersTask) {
- return updatedLeadersTask._id === syncedTask._id;
- });
+ updatedLeader = await User.findOne({ _id: leader._id });
+ updatedLeadersTasks = await Tasks.Task.find({ _id: { $in: updatedLeader.tasksOrder[`${taskType}s`] } });
+ const updatedSyncedTask = find(
+ updatedLeadersTasks,
+ updatedLeadersTask => updatedLeadersTask._id === syncedTask._id,
+ );
expect(task.group.assignedUsers).to.not.contain(leader._id);
expect(updatedSyncedTask).to.exist;
diff --git a/test/api/unit/models/task.test.js b/test/api/unit/models/task.test.js
index d925073945..006efd0a07 100644
--- a/test/api/unit/models/task.test.js
+++ b/test/api/unit/models/task.test.js
@@ -1,14 +1,15 @@
+import { each } from 'lodash';
import { model as Challenge } from '../../../../website/server/models/challenge';
import { model as Group } from '../../../../website/server/models/group';
import { model as User } from '../../../../website/server/models/user';
import * as Tasks from '../../../../website/server/models/task';
import { InternalServerError } from '../../../../website/server/libs/errors';
-import { each } from 'lodash';
-import { generateHistory } from '../../../helpers/api-unit.helper.js';
+import { generateHistory } from '../../../helpers/api-unit.helper';
describe('Task Model', () => {
- let guild, leader, challenge, task;
- let tasksToTest = {
+ let guild; let leader; let challenge; let
+ task;
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -62,11 +63,11 @@ describe('Task Model', () => {
});
it('preens challenge tasks history when scored', async () => {
- let historyLengthBeforePreen = task.history.length;
+ const historyLengthBeforePreen = task.history.length;
await task.scoreChallengeTask(1.2);
- let updatedTask = await Tasks.Task.findOne({_id: task._id});
+ const updatedTask = await Tasks.Task.findOne({ _id: task._id });
expect(historyLengthBeforePreen).to.be.greaterThan(updatedTask.history.length);
});
@@ -75,7 +76,8 @@ describe('Task Model', () => {
describe('Static Methods', () => {
describe('findByIdOrAlias', () => {
- let taskWithAlias, user;
+ let taskWithAlias; let
+ user;
beforeEach(async () => {
user = new User();
@@ -112,13 +114,13 @@ describe('Task Model', () => {
});
it('returns task by id', async () => {
- let foundTodo = await Tasks.Task.findByIdOrAlias(taskWithAlias._id, user._id);
+ const foundTodo = await Tasks.Task.findByIdOrAlias(taskWithAlias._id, user._id);
expect(foundTodo.text).to.eql(taskWithAlias.text);
});
it('returns task by alias', async () => {
- let foundTodo = await Tasks.Task.findByIdOrAlias(taskWithAlias.alias, user._id);
+ const foundTodo = await Tasks.Task.findByIdOrAlias(taskWithAlias.alias, user._id);
expect(foundTodo.text).to.eql(taskWithAlias.text);
});
@@ -134,7 +136,7 @@ describe('Task Model', () => {
});
it('returns null if task cannot be found', async () => {
- let foundTask = await Tasks.Task.findByIdOrAlias('not-found', user._id);
+ const foundTask = await Tasks.Task.findByIdOrAlias('not-found', user._id);
expect(foundTask).to.eql(null);
});
diff --git a/test/api/unit/models/user.test.js b/test/api/unit/models/user.test.js
index 24652fa7b6..298aa31c18 100644
--- a/test/api/unit/models/user.test.js
+++ b/test/api/unit/models/user.test.js
@@ -5,7 +5,7 @@ import common from '../../../../website/common';
describe('User Model', () => {
it('keeps user._tmp when calling .toJSON', () => {
- let user = new User({
+ const user = new User({
auth: {
local: {
username: 'username',
@@ -17,26 +17,26 @@ describe('User Model', () => {
},
});
- user._tmp = {ok: true};
- user._nonTmp = {ok: true};
+ user._tmp = { ok: true };
+ user._nonTmp = { ok: true };
- expect(user._tmp).to.eql({ok: true});
- expect(user._nonTmp).to.eql({ok: true});
+ expect(user._tmp).to.eql({ ok: true });
+ expect(user._nonTmp).to.eql({ ok: true });
- let toObject = user.toObject();
- let toJSON = user.toJSON();
+ const toObject = user.toObject();
+ const toJSON = user.toJSON();
expect(toObject).to.not.have.keys('_tmp');
expect(toObject).to.not.have.keys('_nonTmp');
expect(toJSON).to.have.any.key('_tmp');
- expect(toJSON._tmp).to.eql({ok: true});
+ expect(toJSON._tmp).to.eql({ ok: true });
expect(toJSON).to.not.have.keys('_nonTmp');
});
it('can add computed stats to a JSONified user object', () => {
- let user = new User();
- let userToJSON = user.toJSON();
+ const user = new User();
+ const userToJSON = user.toJSON();
expect(userToJSON.stats.maxMP).to.not.exist;
expect(userToJSON.stats.maxHealth).to.not.exist;
@@ -50,9 +50,9 @@ describe('User Model', () => {
});
it('can transform user object without mongoose helpers', async () => {
- let user = new User();
+ const user = new User();
await user.save();
- let userToJSON = await User.findById(user._id).lean().exec();
+ const userToJSON = await User.findById(user._id).lean().exec();
expect(userToJSON.stats.maxMP).to.not.exist;
expect(userToJSON.stats.maxHealth).to.not.exist;
@@ -68,9 +68,9 @@ describe('User Model', () => {
});
it('can transform user object without mongoose helpers (including computed stats)', async () => {
- let user = new User();
+ const user = new User();
await user.save();
- let userToJSON = await User.findById(user._id).lean().exec();
+ const userToJSON = await User.findById(user._id).lean().exec();
expect(userToJSON.stats.maxMP).to.not.exist;
expect(userToJSON.stats.maxHealth).to.not.exist;
@@ -86,11 +86,11 @@ describe('User Model', () => {
context('notifications', () => {
it('can add notifications without data', () => {
- let user = new User();
+ const user = new User();
user.addNotification('CRON');
- let userToJSON = user.toJSON();
+ const userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
expect(userToJSON.notifications[0]).to.have.all.keys(['data', 'id', 'type', 'seen']);
expect(userToJSON.notifications[0].type).to.equal('CRON');
@@ -99,14 +99,15 @@ describe('User Model', () => {
});
it('removes invalid notifications when calling toJSON', () => {
- let user = new User();
+ const user = new User();
user.notifications = [
null, // invalid, not an object
- {seen: true}, // invalid, no type or id
- {id: 123}, // invalid, no type
- // {type: 'ABC'}, // invalid, no id, not included here because the id would be added automatically
- {type: 'ABC', id: '123'}, // valid
+ { seen: true }, // invalid, no type or id
+ { id: 123 }, // invalid, no type
+ // invalid, no id, not included here because the id would be added automatically
+ // {type: 'ABC'},
+ { type: 'ABC', id: '123' }, // valid
];
const userToJSON = user.toJSON();
@@ -118,15 +119,15 @@ describe('User Model', () => {
});
it('can add notifications with data and already marked as seen', () => {
- let user = new User();
+ const user = new User();
- user.addNotification('CRON', {field: 1}, true);
+ user.addNotification('CRON', { field: 1 }, true);
- let userToJSON = user.toJSON();
+ const userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
expect(userToJSON.notifications[0]).to.have.all.keys(['data', 'id', 'type', 'seen']);
expect(userToJSON.notifications[0].type).to.equal('CRON');
- expect(userToJSON.notifications[0].data).to.eql({field: 1});
+ expect(userToJSON.notifications[0].data).to.eql({ field: 1 });
expect(userToJSON.notifications[0].seen).to.eql(true);
});
@@ -135,11 +136,11 @@ describe('User Model', () => {
let user = new User();
await user.save();
- await User.pushNotification({_id: user._id}, 'CRON');
+ await User.pushNotification({ _id: user._id }, 'CRON');
- user = await User.findOne({_id: user._id}).exec();
+ user = await User.findOne({ _id: user._id }).exec();
- let userToJSON = user.toJSON();
+ const userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
expect(userToJSON.notifications[0]).to.have.all.keys(['data', 'id', 'type', 'seen']);
expect(userToJSON.notifications[0].type).to.equal('CRON');
@@ -147,21 +148,21 @@ describe('User Model', () => {
});
it('validates notifications via static method', async () => {
- let user = new User();
+ const user = new User();
await user.save();
- expect(User.pushNotification({_id: user._id}, 'BAD_TYPE')).to.eventually.be.rejected;
- expect(User.pushNotification({_id: user._id}, 'CRON', null, 'INVALID_SEEN')).to.eventually.be.rejected;
+ expect(User.pushNotification({ _id: user._id }, 'BAD_TYPE')).to.eventually.be.rejected;
+ expect(User.pushNotification({ _id: user._id }, 'CRON', null, 'INVALID_SEEN')).to.eventually.be.rejected;
});
it('adds notifications without data for all given users via static method', async () => {
let user = new User();
- let otherUser = new User();
+ const otherUser = new User();
await Promise.all([user.save(), otherUser.save()]);
- await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON');
+ await User.pushNotification({ _id: { $in: [user._id, otherUser._id] } }, 'CRON');
- user = await User.findOne({_id: user._id}).exec();
+ user = await User.findOne({ _id: user._id }).exec();
let userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
@@ -170,7 +171,7 @@ describe('User Model', () => {
expect(userToJSON.notifications[0].data).to.eql({});
expect(userToJSON.notifications[0].seen).to.eql(false);
- user = await User.findOne({_id: otherUser._id}).exec();
+ user = await User.findOne({ _id: otherUser._id }).exec();
userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
@@ -182,27 +183,27 @@ describe('User Model', () => {
it('adds notifications with data and seen status for all given users via static method', async () => {
let user = new User();
- let otherUser = new User();
+ const otherUser = new User();
await Promise.all([user.save(), otherUser.save()]);
- await User.pushNotification({_id: {$in: [user._id, otherUser._id]}}, 'CRON', {field: 1}, true);
+ await User.pushNotification({ _id: { $in: [user._id, otherUser._id] } }, 'CRON', { field: 1 }, true);
- user = await User.findOne({_id: user._id}).exec();
+ user = await User.findOne({ _id: user._id }).exec();
let userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
expect(userToJSON.notifications[0]).to.have.all.keys(['data', 'id', 'type', 'seen']);
expect(userToJSON.notifications[0].type).to.equal('CRON');
- expect(userToJSON.notifications[0].data).to.eql({field: 1});
+ expect(userToJSON.notifications[0].data).to.eql({ field: 1 });
expect(userToJSON.notifications[0].seen).to.eql(true);
- user = await User.findOne({_id: otherUser._id}).exec();
+ user = await User.findOne({ _id: otherUser._id }).exec();
userToJSON = user.toJSON();
expect(user.notifications.length).to.equal(1);
expect(userToJSON.notifications[0]).to.have.all.keys(['data', 'id', 'type', 'seen']);
expect(userToJSON.notifications[0].type).to.equal('CRON');
- expect(userToJSON.notifications[0].data).to.eql({field: 1});
+ expect(userToJSON.notifications[0].data).to.eql({ field: 1 });
expect(userToJSON.notifications[0].seen).to.eql(true);
});
});
@@ -245,7 +246,7 @@ describe('User Model', () => {
let group;
beforeEach(() => {
user = new User();
- let leader = new User();
+ const leader = new User();
group = new Group({
name: 'test',
type: 'guild',
@@ -379,7 +380,8 @@ describe('User Model', () => {
// Create conditions for the Beast Master achievement to be awarded
user.achievements.beastMasterCount = 3;
- expect(user.achievements.beastMaster).to.not.equal(true); // verify that it was not awarded initially
+ // verify that it was not awarded initially
+ expect(user.achievements.beastMaster).to.not.equal(true);
user = await user.save();
// verify that it's been awarded
@@ -397,7 +399,8 @@ describe('User Model', () => {
user = await User.findById(user._id).select('-items').exec();
expect(user.isSelected('items')).to.equal(false);
- // create the conditions for the beast master achievement but this time it should not be awarded
+ // create the conditions for the beast master achievement
+ // but this time it should not be awarded
user.achievements.beastMasterCount = 3;
user = await user.save();
expect(user.achievements.beastMaster).to.equal(false);
@@ -536,11 +539,9 @@ describe('User Model', () => {
const today = moment('2017-12-06T00:00:00.000-06:00'); // 11 pm on 4 Texas
const req = {};
- req.header = () => {
- return timezoneOffset + 60;
- };
+ req.header = () => timezoneOffset + 60;
- const {daysMissed} = user.daysUserHasMissed(today, req);
+ const { daysMissed } = user.daysUserHasMissed(today, req);
expect(daysMissed).to.eql(0);
});
@@ -554,11 +555,9 @@ describe('User Model', () => {
const today = moment('2017-12-06T02:00:00.000-08:00');
const req = {};
- req.header = () => {
- return timezoneOffset + 60;
- };
+ req.header = () => timezoneOffset + 60;
- const {daysMissed} = user.daysUserHasMissed(today, req);
+ const { daysMissed } = user.daysUserHasMissed(today, req);
expect(daysMissed).to.eql(0);
});
diff --git a/test/api/unit/models/userNotification.test.js b/test/api/unit/models/userNotification.test.js
index 81140a9c26..c52a44bd21 100644
--- a/test/api/unit/models/userNotification.test.js
+++ b/test/api/unit/models/userNotification.test.js
@@ -5,10 +5,10 @@ describe('UserNotification Model', () => {
it('converts an array of notifications to a safe version', () => {
const notifications = [
null, // invalid, not an object
- {seen: true}, // invalid, no type or id
- {id: 123}, // invalid, no type
- {type: 'ABC'}, // invalid, no id
- new UserNotification({type: 'ABC', id: 123}), // valid
+ { seen: true }, // invalid, no type or id
+ { id: 123 }, // invalid, no type
+ { type: 'ABC' }, // invalid, no id
+ new UserNotification({ type: 'ABC', id: 123 }), // valid
];
const notificationsToJSON = UserNotification.convertNotificationsToSafeJson(notifications);
diff --git a/test/api/unit/models/webhook.test.js b/test/api/unit/models/webhook.test.js
index 06d69a256d..4a49b6213f 100644
--- a/test/api/unit/models/webhook.test.js
+++ b/test/api/unit/models/webhook.test.js
@@ -1,6 +1,6 @@
+import { v4 as generateUUID } from 'uuid';
import { model as Webhook } from '../../../../website/server/models/webhook';
import { BadRequest } from '../../../../website/server/libs/errors';
-import { v4 as generateUUID } from 'uuid';
import apiError from '../../../../website/server/libs/apiError';
describe('Webhook Model', () => {
@@ -33,7 +33,7 @@ describe('Webhook Model', () => {
it('it provides default values for options', () => {
delete config.options;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -49,7 +49,7 @@ describe('Webhook Model', () => {
it('provides missing task options', () => {
delete config.options.created;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -65,7 +65,7 @@ describe('Webhook Model', () => {
it('discards additional options', () => {
config.options.foo = 'another option';
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -79,12 +79,12 @@ describe('Webhook Model', () => {
});
});
- ['created', 'updated', 'deleted', 'scored', 'checklistScored'].forEach((option) => {
- it(`validates that ${option} is a boolean`, (done) => {
+ ['created', 'updated', 'deleted', 'scored', 'checklistScored'].forEach(option => {
+ it(`validates that ${option} is a boolean`, done => {
config.options[option] = 'not a boolean';
try {
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
@@ -115,7 +115,7 @@ describe('Webhook Model', () => {
it('it provides default values for options', () => {
delete config.options;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -129,7 +129,7 @@ describe('Webhook Model', () => {
it('provides missing user options', () => {
delete config.options.petHatched;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -143,7 +143,7 @@ describe('Webhook Model', () => {
it('discards additional options', () => {
config.options.foo = 'another option';
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -155,12 +155,12 @@ describe('Webhook Model', () => {
});
});
- ['petHatched', 'petHatched', 'leveledUp'].forEach((option) => {
- it(`validates that ${option} is a boolean`, (done) => {
+ ['petHatched', 'petHatched', 'leveledUp'].forEach(option => {
+ it(`validates that ${option} is a boolean`, done => {
config.options[option] = 'not a boolean';
try {
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
@@ -190,7 +190,7 @@ describe('Webhook Model', () => {
it('it provides default values for options', () => {
delete config.options;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -203,7 +203,7 @@ describe('Webhook Model', () => {
it('provides missing user options', () => {
delete config.options.questStarted;
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -216,7 +216,7 @@ describe('Webhook Model', () => {
it('discards additional options', () => {
config.options.foo = 'another option';
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -227,12 +227,12 @@ describe('Webhook Model', () => {
});
});
- ['questStarted', 'questFinished'].forEach((option) => {
- it(`validates that ${option} is a boolean`, (done) => {
+ ['questStarted', 'questFinished'].forEach(option => {
+ it(`validates that ${option} is a boolean`, done => {
config.options[option] = 'not a boolean';
try {
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
@@ -259,7 +259,7 @@ describe('Webhook Model', () => {
});
it('creates options', () => {
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -269,7 +269,7 @@ describe('Webhook Model', () => {
it('discards additional objects', () => {
config.options.foo = 'another thing';
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
@@ -279,11 +279,11 @@ describe('Webhook Model', () => {
});
});
- it('requires groupId option to be a uuid', (done) => {
+ it('requires groupId option to be a uuid', done => {
config.options.groupId = 'not a uuid';
try {
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
@@ -310,7 +310,7 @@ describe('Webhook Model', () => {
it('discards additional objects', () => {
config.options.foo = 'another thing';
- let wh = new Webhook(config);
+ const wh = new Webhook(config);
wh.formatOptions(res);
diff --git a/test/api/v3/integration/challenges/DELETE-challenges_challengeId.test.js b/test/api/v3/integration/challenges/DELETE-challenges_challengeId.test.js
index 15d8751e5a..5e1f9ce9e0 100644
--- a/test/api/v3/integration/challenges/DELETE-challenges_challengeId.test.js
+++ b/test/api/v3/integration/challenges/DELETE-challenges_challengeId.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateChallenge,
@@ -6,11 +7,10 @@ import {
checkExistence,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /challenges/:challengeId', () => {
it('returns error when challengeId is not a valid UUID', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.del('/challenges/test')).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -19,7 +19,7 @@ describe('DELETE /challenges/:challengeId', () => {
});
it('returns error when challengeId is not for a valid challenge', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.del(`/challenges/${generateUUID()}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -32,10 +32,10 @@ describe('DELETE /challenges/:challengeId', () => {
let groupLeader;
let group;
let challenge;
- let taskText = 'A challenge task text';
+ const taskText = 'A challenge task text';
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup();
+ const populatedGroup = await createAndPopulateGroup();
groupLeader = populatedGroup.groupLeader;
group = populatedGroup.group;
@@ -44,14 +44,14 @@ describe('DELETE /challenges/:challengeId', () => {
await groupLeader.post(`/challenges/${challenge._id}/join`);
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: taskText},
+ { type: 'habit', text: taskText },
]);
await challenge.sync();
});
it('returns an error when user doesn\'t have permissions to delete the challenge', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.del(`/challenges/${challenge._id}`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -69,7 +69,7 @@ describe('DELETE /challenges/:challengeId', () => {
});
it('refunds gems to group leader', async () => {
- let oldBalance = (await groupLeader.sync()).balance;
+ const oldBalance = (await groupLeader.sync()).balance;
await groupLeader.del(`/challenges/${challenge._id}`);
@@ -83,10 +83,8 @@ describe('DELETE /challenges/:challengeId', () => {
await sleep(0.5);
- let tasks = await groupLeader.get('/tasks/user');
- let testTask = _.find(tasks, (task) => {
- return task.text === taskText;
- });
+ const tasks = await groupLeader.get('/tasks/user');
+ const testTask = _.find(tasks, task => task.text === taskText);
expect(testTask.challenge.broken).to.eql('CHALLENGE_DELETED');
expect(testTask.challenge.winner).to.be.null;
diff --git a/test/api/v3/integration/challenges/GET-challenges_challengeId.test.js b/test/api/v3/integration/challenges/GET-challenges_challengeId.test.js
index 2f3e219592..7f70513da8 100644
--- a/test/api/v3/integration/challenges/GET-challenges_challengeId.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_challengeId.test.js
@@ -1,14 +1,14 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
createAndPopulateGroup,
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /challenges/:challengeId', () => {
it('fails if challenge doesn\'t exists', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.get(`/challenges/${generateUUID()}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -25,8 +25,8 @@ describe('GET /challenges/:challengeId', () => {
beforeEach(async () => {
user = await generateUser();
- let populatedGroup = await createAndPopulateGroup({
- groupDetails: {type: 'guild', privacy: 'public'},
+ const populatedGroup = await createAndPopulateGroup({
+ groupDetails: { type: 'guild', privacy: 'public' },
});
groupLeader = populatedGroup.groupLeader;
@@ -38,7 +38,7 @@ describe('GET /challenges/:challengeId', () => {
it('should return challenge data', async () => {
await challenge.sync();
- let chal = await user.get(`/challenges/${challenge._id}`);
+ const chal = await user.get(`/challenges/${challenge._id}`);
expect(chal.memberCount).to.equal(challenge.memberCount);
expect(chal.name).to.equal(challenge.name);
expect(chal._id).to.equal(challenge._id);
@@ -46,7 +46,7 @@ describe('GET /challenges/:challengeId', () => {
expect(chal.leader).to.eql({
_id: groupLeader._id,
id: groupLeader._id,
- profile: {name: groupLeader.profile.name},
+ profile: { name: groupLeader.profile.name },
auth: {
local: {
username: groupLeader.auth.local.username,
@@ -81,8 +81,8 @@ describe('GET /challenges/:challengeId', () => {
beforeEach(async () => {
nonMember = await generateUser();
- let populatedGroup = await createAndPopulateGroup({
- groupDetails: {type: 'guild', privacy: 'private'},
+ const populatedGroup = await createAndPopulateGroup({
+ groupDetails: { type: 'guild', privacy: 'private' },
members: 2,
});
@@ -90,8 +90,8 @@ describe('GET /challenges/:challengeId', () => {
group = populatedGroup.group;
members = populatedGroup.members;
- challengeLeader = members[0];
- otherMember = members[1];
+ challengeLeader = members[0]; // eslint-disable-line prefer-destructuring
+ otherMember = members[1]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(challengeLeader, group);
});
@@ -105,14 +105,14 @@ describe('GET /challenges/:challengeId', () => {
});
it('returns challenge data for any user in the guild', async () => {
- let chal = await otherMember.get(`/challenges/${challenge._id}`);
+ const chal = await otherMember.get(`/challenges/${challenge._id}`);
expect(chal.name).to.equal(challenge.name);
expect(chal._id).to.equal(challenge._id);
expect(chal.leader).to.eql({
_id: challengeLeader._id,
id: challengeLeader._id,
- profile: {name: challengeLeader.profile.name},
+ profile: { name: challengeLeader.profile.name },
auth: {
local: {
username: challengeLeader.auth.local.username,
@@ -139,14 +139,14 @@ describe('GET /challenges/:challengeId', () => {
await challengeLeader.sync();
expect(challengeLeader.guilds).to.be.empty; // check that leaving worked
- let chal = await challengeLeader.get(`/challenges/${challenge._id}`);
+ const chal = await challengeLeader.get(`/challenges/${challenge._id}`);
expect(chal.name).to.equal(challenge.name);
expect(chal._id).to.equal(challenge._id);
expect(chal.leader).to.eql({
_id: challengeLeader._id,
id: challengeLeader._id,
- profile: {name: challengeLeader.profile.name},
+ profile: { name: challengeLeader.profile.name },
auth: {
local: {
username: challengeLeader.auth.local.username,
@@ -171,8 +171,8 @@ describe('GET /challenges/:challengeId', () => {
beforeEach(async () => {
nonMember = await generateUser();
- let populatedGroup = await createAndPopulateGroup({
- groupDetails: {type: 'party', privacy: 'private'},
+ const populatedGroup = await createAndPopulateGroup({
+ groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -180,8 +180,8 @@ describe('GET /challenges/:challengeId', () => {
group = populatedGroup.group;
members = populatedGroup.members;
- challengeLeader = members[0];
- otherMember = members[1];
+ challengeLeader = members[0]; // eslint-disable-line prefer-destructuring
+ otherMember = members[1]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(challengeLeader, group);
});
@@ -195,14 +195,14 @@ describe('GET /challenges/:challengeId', () => {
});
it('returns challenge data for any user in the party', async () => {
- let chal = await otherMember.get(`/challenges/${challenge._id}`);
+ const chal = await otherMember.get(`/challenges/${challenge._id}`);
expect(chal.name).to.equal(challenge.name);
expect(chal._id).to.equal(challenge._id);
expect(chal.leader).to.eql({
_id: challengeLeader._id,
id: challengeLeader._id,
- profile: {name: challengeLeader.profile.name},
+ profile: { name: challengeLeader.profile.name },
auth: {
local: {
username: challengeLeader.auth.local.username,
@@ -229,14 +229,14 @@ describe('GET /challenges/:challengeId', () => {
await challengeLeader.sync();
expect(challengeLeader.party._id).to.be.undefined; // check that leaving worked
- let chal = await challengeLeader.get(`/challenges/${challenge._id}`);
+ const chal = await challengeLeader.get(`/challenges/${challenge._id}`);
expect(chal.name).to.equal(challenge.name);
expect(chal._id).to.equal(challenge._id);
expect(chal.leader).to.eql({
_id: challengeLeader._id,
id: challengeLeader._id,
- profile: {name: challengeLeader.profile.name},
+ profile: { name: challengeLeader.profile.name },
auth: {
local: {
username: challengeLeader.auth.local.username,
diff --git a/test/api/v3/integration/challenges/GET-challenges_challengeId_export_csv.test.js b/test/api/v3/integration/challenges/GET-challenges_challengeId_export_csv.test.js
index 03702d5063..9fca02088e 100644
--- a/test/api/v3/integration/challenges/GET-challenges_challengeId_export_csv.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_challengeId_export_csv.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
createAndPopulateGroup,
@@ -5,7 +6,6 @@ import {
translate as t,
sleep,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /challenges/:challengeId/export/csv', () => {
let groupLeader;
@@ -15,7 +15,7 @@ describe('GET /challenges/:challengeId/export/csv', () => {
let user;
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 3,
});
@@ -30,8 +30,8 @@ describe('GET /challenges/:challengeId/export/csv', () => {
await members[2].post(`/challenges/${challenge._id}/join`);
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: 'Task 1'},
- {type: 'todo', text: 'Task 2'},
+ { type: 'habit', text: 'Task 1' },
+ { type: 'todo', text: 'Task 2' },
]);
await sleep(0.5); // Make sure tasks are synced to the users
await members[0].sync();
@@ -74,7 +74,7 @@ describe('GET /challenges/:challengeId/export/csv', () => {
});
it('should successfully return when it contains erroneous residue user data', async () => {
- await members[0].update({challenges: []});
+ await members[0].update({ challenges: [] });
const res = await members[1].get(`/challenges/${challenge._id}/export/csv`);
const sortedMembers = _.sortBy([members[1], members[2], groupLeader], '_id');
const splitRes = res.split('\n');
diff --git a/test/api/v3/integration/challenges/GET-challenges_challengeId_members.test.js b/test/api/v3/integration/challenges/GET-challenges_challengeId_members.test.js
index 97ed8236fc..776f0db1b0 100644
--- a/test/api/v3/integration/challenges/GET-challenges_challengeId_members.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_challengeId_members.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
@@ -5,7 +6,6 @@ import {
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /challenges/:challengeId/members', () => {
let user;
@@ -31,9 +31,9 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('fails if user isn\'t in the private group and isn\'t challenge leader', async () => {
- let group = await generateGroup(user, {type: 'party', privacy: 'private'});
- let challenge = await generateChallenge(user, group);
- let anotherUser = await generateUser();
+ const group = await generateGroup(user, { type: 'party', privacy: 'private' });
+ const challenge = await generateChallenge(user, group);
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/challenges/${challenge._id}/members`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -43,23 +43,23 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('works if user isn\'t in the private group but is challenge leader', async () => {
- let populatedGroup = await createAndPopulateGroup({
- groupDetails: {type: 'party', privacy: 'private'},
+ const populatedGroup = await createAndPopulateGroup({
+ groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- let groupLeader = populatedGroup.groupLeader;
- let challengeLeader = populatedGroup.members[0];
- let challenge = await generateChallenge(challengeLeader, populatedGroup.group);
+ const { groupLeader } = populatedGroup;
+ const challengeLeader = populatedGroup.members[0];
+ const challenge = await generateChallenge(challengeLeader, populatedGroup.group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
await challengeLeader.post('/groups/party/leave');
await challengeLeader.sync();
expect(challengeLeader.party._id).to.be.undefined; // check that leaving worked
- let res = await challengeLeader.get(`/challenges/${challenge._id}/members`);
+ const res = await challengeLeader.get(`/challenges/${challenge._id}/members`);
expect(res[0]).to.eql({
_id: groupLeader._id,
id: groupLeader._id,
- profile: {name: groupLeader.profile.name},
+ profile: { name: groupLeader.profile.name },
auth: {
local: {
username: groupLeader.auth.local.username,
@@ -72,15 +72,15 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('works with challenges belonging to public guild', async () => {
- let leader = await generateUser({balance: 4});
- let group = await generateGroup(leader, {type: 'guild', privacy: 'public', name: generateUUID()});
- let challenge = await generateChallenge(leader, group);
+ const leader = await generateUser({ balance: 4 });
+ const group = await generateGroup(leader, { type: 'guild', privacy: 'public', name: generateUUID() });
+ const challenge = await generateChallenge(leader, group);
await leader.post(`/challenges/${challenge._id}/join`);
- let res = await user.get(`/challenges/${challenge._id}/members`);
+ const res = await user.get(`/challenges/${challenge._id}/members`);
expect(res[0]).to.eql({
_id: leader._id,
id: leader._id,
- profile: {name: leader.profile.name},
+ profile: { name: leader.profile.name },
auth: {
local: {
username: leader.auth.local.username,
@@ -95,15 +95,15 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('populates only some fields', async () => {
- let anotherUser = await generateUser({balance: 3});
- let group = await generateGroup(anotherUser, {type: 'guild', privacy: 'public', name: generateUUID()});
- let challenge = await generateChallenge(anotherUser, group);
+ const anotherUser = await generateUser({ balance: 3 });
+ const group = await generateGroup(anotherUser, { type: 'guild', privacy: 'public', name: generateUUID() });
+ const challenge = await generateChallenge(anotherUser, group);
await anotherUser.post(`/challenges/${challenge._id}/join`);
- let res = await user.get(`/challenges/${challenge._id}/members`);
+ const res = await user.get(`/challenges/${challenge._id}/members`);
expect(res[0]).to.eql({
_id: anotherUser._id,
id: anotherUser._id,
- profile: {name: anotherUser.profile.name},
+ profile: { name: anotherUser.profile.name },
auth: {
local: {
username: anotherUser.auth.local.username,
@@ -118,17 +118,17 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('returns only first 30 members if req.query.includeAllMembers is not true', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let usersToGenerate = [];
- for (let i = 0; i < 31; i++) {
- usersToGenerate.push(generateUser({challenges: [challenge._id]}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
+ usersToGenerate.push(generateUser({ challenges: [challenge._id] }));
}
await Promise.all(usersToGenerate);
- let res = await user.get(`/challenges/${challenge._id}/members?includeAllMembers=not-true`);
+ const res = await user.get(`/challenges/${challenge._id}/members?includeAllMembers=not-true`);
expect(res.length).to.equal(30);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -137,17 +137,17 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('returns only first 30 members if req.query.includeAllMembers is not defined', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let usersToGenerate = [];
- for (let i = 0; i < 31; i++) {
- usersToGenerate.push(generateUser({challenges: [challenge._id]}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
+ usersToGenerate.push(generateUser({ challenges: [challenge._id] }));
}
await Promise.all(usersToGenerate);
- let res = await user.get(`/challenges/${challenge._id}/members`);
+ const res = await user.get(`/challenges/${challenge._id}/members`);
expect(res.length).to.equal(30);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -156,17 +156,17 @@ describe('GET /challenges/:challengeId/members', () => {
});
it('returns all members if req.query.includeAllMembers is true', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let usersToGenerate = [];
- for (let i = 0; i < 31; i++) {
- usersToGenerate.push(generateUser({challenges: [challenge._id]}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
+ usersToGenerate.push(generateUser({ challenges: [challenge._id] }));
}
await Promise.all(usersToGenerate);
- let res = await user.get(`/challenges/${challenge._id}/members?includeAllMembers=true`);
+ const res = await user.get(`/challenges/${challenge._id}/members?includeAllMembers=true`);
expect(res.length).to.equal(32);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -174,47 +174,48 @@ describe('GET /challenges/:challengeId/members', () => {
});
});
- it('supports using req.query.lastId to get more members', async function () {
+ it('supports using req.query.lastId to get more members', async function test () {
this.timeout(30000); // @TODO: times out after 8 seconds
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let usersToGenerate = [];
- for (let i = 0; i < 57; i++) {
- usersToGenerate.push(generateUser({challenges: [challenge._id]}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 57; i += 1) {
+ usersToGenerate.push(generateUser({ challenges: [challenge._id] }));
}
- let generatedUsers = await Promise.all(usersToGenerate); // Group has 59 members (1 is the leader)
- let expectedIds = [user._id].concat(generatedUsers.map(generatedUser => generatedUser._id));
+ // Group has 59 members (1 is the leader)
+ const generatedUsers = await Promise.all(usersToGenerate);
+ const expectedIds = [user._id].concat(generatedUsers.map(generatedUser => generatedUser._id));
- let res = await user.get(`/challenges/${challenge._id}/members`);
+ const res = await user.get(`/challenges/${challenge._id}/members`);
expect(res.length).to.equal(30);
- let res2 = await user.get(`/challenges/${challenge._id}/members?lastId=${res[res.length - 1]._id}`);
+ const res2 = await user.get(`/challenges/${challenge._id}/members?lastId=${res[res.length - 1]._id}`);
expect(res2.length).to.equal(28);
- let resIds = res.concat(res2).map(member => member._id);
+ const resIds = res.concat(res2).map(member => member._id);
expect(resIds).to.eql(expectedIds.sort());
});
it('supports using req.query.search to get search members', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let usersToGenerate = [];
- for (let i = 0; i < 3; i++) {
+ const usersToGenerate = [];
+ for (let i = 0; i < 3; i += 1) {
usersToGenerate.push(generateUser({
challenges: [challenge._id],
'profile.name': `${i}profilename`,
}));
}
- let generatedUsers = await Promise.all(usersToGenerate);
- let profileNames = generatedUsers.map(generatedUser => generatedUser.profile.name);
+ const generatedUsers = await Promise.all(usersToGenerate);
+ const profileNames = generatedUsers.map(generatedUser => generatedUser.profile.name);
- let firstProfileName = profileNames[0];
- let nameToSearch = firstProfileName.substring(0, 4);
+ const firstProfileName = profileNames[0];
+ const nameToSearch = firstProfileName.substring(0, 4);
- let response = await user.get(`/challenges/${challenge._id}/members?search=${nameToSearch}`);
+ const response = await user.get(`/challenges/${challenge._id}/members?search=${nameToSearch}`);
expect(response[0].profile.name).to.eql(firstProfileName);
});
});
diff --git a/test/api/v3/integration/challenges/GET-challenges_challengeId_members_memberId.test.js b/test/api/v3/integration/challenges/GET-challenges_challengeId_members_memberId.test.js
index eef16de7e1..98455f66d3 100644
--- a/test/api/v3/integration/challenges/GET-challenges_challengeId_members_memberId.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_challengeId_members_memberId.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateChallenge,
generateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /challenges/:challengeId/members/:memberId', () => {
let user;
@@ -30,16 +30,16 @@ describe('GET /challenges/:challengeId/members/:memberId', () => {
});
it('fails if member doesn\'t exists', async () => {
- let userId = generateUUID();
+ const userId = generateUUID();
await expect(user.get(`/challenges/${generateUUID()}/members/${userId}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId}),
+ message: t('userWithIDNotFound', { userId }),
});
});
it('fails if challenge doesn\'t exists', async () => {
- let member = await generateUser();
+ const member = await generateUser();
await expect(user.get(`/challenges/${generateUUID()}/members/${member._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -48,11 +48,11 @@ describe('GET /challenges/:challengeId/members/:memberId', () => {
});
it('fails if user doesn\'t have access to the challenge', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let anotherUser = await generateUser();
- let member = await generateUser();
+ const anotherUser = await generateUser();
+ const member = await generateUser();
await expect(anotherUser.get(`/challenges/${challenge._id}/members/${member._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -61,10 +61,10 @@ describe('GET /challenges/:challengeId/members/:memberId', () => {
});
it('fails if member is not part of the challenge', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let member = await generateUser();
+ const member = await generateUser();
await expect(user.get(`/challenges/${challenge._id}/members/${member._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -73,37 +73,37 @@ describe('GET /challenges/:challengeId/members/:memberId', () => {
});
it('works with challenges belonging to a public guild', async () => {
- let groupLeader = await generateUser({balance: 4});
- let group = await generateGroup(groupLeader, {type: 'guild', privacy: 'public', name: generateUUID()});
- let challenge = await generateChallenge(groupLeader, group);
+ const groupLeader = await generateUser({ balance: 4 });
+ const group = await generateGroup(groupLeader, { type: 'guild', privacy: 'public', name: generateUUID() });
+ const challenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
- let taskText = 'Test Text';
- await groupLeader.post(`/tasks/challenge/${challenge._id}`, [{type: 'habit', text: taskText}]);
+ const taskText = 'Test Text';
+ await groupLeader.post(`/tasks/challenge/${challenge._id}`, [{ type: 'habit', text: taskText }]);
- let memberProgress = await user.get(`/challenges/${challenge._id}/members/${groupLeader._id}`);
+ const memberProgress = await user.get(`/challenges/${challenge._id}/members/${groupLeader._id}`);
expect(memberProgress).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile', 'tasks']);
expect(memberProgress.profile).to.have.all.keys(['name']);
expect(memberProgress.tasks.length).to.equal(1);
});
it('returns the member tasks for the challenges', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- await user.post(`/tasks/challenge/${challenge._id}`, [{type: 'habit', text: 'Test Text'}]);
+ await user.post(`/tasks/challenge/${challenge._id}`, [{ type: 'habit', text: 'Test Text' }]);
- let memberProgress = await user.get(`/challenges/${challenge._id}/members/${user._id}`);
- let chalTasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const memberProgress = await user.get(`/challenges/${challenge._id}/members/${user._id}`);
+ const chalTasks = await user.get(`/tasks/challenge/${challenge._id}`);
expect(memberProgress.tasks.length).to.equal(chalTasks.length);
expect(memberProgress.tasks[0].challenge.id).to.equal(challenge._id);
expect(memberProgress.tasks[0].challenge.taskId).to.equal(chalTasks[0]._id);
});
it('returns the tasks without the tags and checklist', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let challenge = await generateChallenge(user, group);
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
- let taskText = 'Test Text';
+ const taskText = 'Test Text';
await user.post(`/tasks/challenge/${challenge._id}`, [{
type: 'todo',
text: taskText,
@@ -115,7 +115,7 @@ describe('GET /challenges/:challengeId/members/:memberId', () => {
],
}]);
- let memberProgress = await user.get(`/challenges/${challenge._id}/members/${user._id}`);
+ const memberProgress = await user.get(`/challenges/${challenge._id}/members/${user._id}`);
expect(memberProgress.tasks[0]).not.to.have.key('tags');
expect(memberProgress.tasks[0].checklist).to.eql([]);
});
diff --git a/test/api/v3/integration/challenges/GET-challenges_group_groupid.test.js b/test/api/v3/integration/challenges/GET-challenges_group_groupid.test.js
index 9fc903c925..19ee8798c9 100644
--- a/test/api/v3/integration/challenges/GET-challenges_group_groupid.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_group_groupid.test.js
@@ -8,10 +8,11 @@ import { TAVERN_ID } from '../../../../../website/common/script/constants';
describe('GET challenges/groups/:groupId', () => {
context('Public Guild', () => {
- let publicGuild, user, nonMember, challenge, challenge2;
+ let publicGuild; let user; let nonMember; let challenge; let
+ challenge2;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestGuild',
type: 'guild',
@@ -31,14 +32,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return group challenges for non member with populated leader', async () => {
- let challenges = await nonMember.get(`/challenges/groups/${publicGuild._id}`);
+ const challenges = await nonMember.get(`/challenges/groups/${publicGuild._id}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -48,12 +49,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -66,14 +67,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return group challenges for member with populated leader', async () => {
- let challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
+ const challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -83,12 +84,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -106,7 +107,7 @@ describe('GET challenges/groups/:groupId', () => {
let foundChallengeIndex = _.findIndex(challenges, { _id: challenge2._id });
expect(foundChallengeIndex).to.eql(0);
- let newChallenge = await generateChallenge(user, publicGuild);
+ const newChallenge = await generateChallenge(user, publicGuild);
await user.post(`/challenges/${newChallenge._id}/join`);
challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
@@ -117,10 +118,11 @@ describe('GET challenges/groups/:groupId', () => {
});
context('Private Guild', () => {
- let privateGuild, user, nonMember, challenge, challenge2;
+ let privateGuild; let user; let nonMember; let challenge; let
+ challenge2;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestPrivateGuild',
type: 'guild',
@@ -149,14 +151,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return group challenges for member with populated leader', async () => {
- let challenges = await user.get(`/challenges/groups/${privateGuild._id}`);
+ const challenges = await user.get(`/challenges/groups/${privateGuild._id}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: privateGuild.leader._id,
id: privateGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -166,12 +168,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: privateGuild.leader._id,
id: privateGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -185,10 +187,11 @@ describe('GET challenges/groups/:groupId', () => {
});
context('official challenge is present', () => {
- let publicGuild, user, officialChallenge, challenge, challenge2;
+ let publicGuild; let user; let officialChallenge; let challenge; let
+ challenge2;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestGuild',
type: 'guild',
@@ -218,9 +221,9 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return official challenges first', async () => {
- let challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
+ const challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
- let foundChallengeIndex = _.findIndex(challenges, { _id: officialChallenge._id });
+ const foundChallengeIndex = _.findIndex(challenges, { _id: officialChallenge._id });
expect(foundChallengeIndex).to.eql(0);
});
@@ -233,7 +236,7 @@ describe('GET challenges/groups/:groupId', () => {
foundChallengeIndex = _.findIndex(challenges, { _id: challenge2._id });
expect(foundChallengeIndex).to.eql(1);
- let newChallenge = await generateChallenge(user, publicGuild);
+ const newChallenge = await generateChallenge(user, publicGuild);
await user.post(`/challenges/${newChallenge._id}/join`);
challenges = await user.get(`/challenges/groups/${publicGuild._id}`);
@@ -244,10 +247,11 @@ describe('GET challenges/groups/:groupId', () => {
});
context('Party', () => {
- let party, user, nonMember, challenge, challenge2;
+ let party; let user; let nonMember; let challenge; let
+ challenge2;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestParty',
type: 'party',
@@ -275,14 +279,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return group challenges for member with populated leader', async () => {
- let challenges = await user.get(`/challenges/groups/${party._id}`);
+ const challenges = await user.get(`/challenges/groups/${party._id}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: party.leader._id,
id: party.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -292,12 +296,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: party.leader._id,
id: party.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -310,14 +314,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return group challenges for member using ID "party"', async () => {
- let challenges = await user.get('/challenges/groups/party');
+ const challenges = await user.get('/challenges/groups/party');
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: party.leader._id,
id: party.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -327,12 +331,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: party.leader._id,
id: party.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -346,28 +350,29 @@ describe('GET challenges/groups/:groupId', () => {
});
context('Tavern', () => {
- let tavern, user, challenge, challenge2;
+ let tavern; let user; let challenge; let
+ challenge2;
before(async () => {
user = await generateUser();
- await user.update({balance: 0.5});
+ await user.update({ balance: 0.5 });
tavern = await user.get(`/groups/${TAVERN_ID}`);
- challenge = await generateChallenge(user, tavern, {prize: 1});
+ challenge = await generateChallenge(user, tavern, { prize: 1 });
await user.post(`/challenges/${challenge._id}/join`);
- challenge2 = await generateChallenge(user, tavern, {prize: 1});
+ challenge2 = await generateChallenge(user, tavern, { prize: 1 });
await user.post(`/challenges/${challenge2._id}/join`);
});
it('should return tavern challenges with populated leader', async () => {
- let challenges = await user.get(`/challenges/groups/${TAVERN_ID}`);
+ const challenges = await user.get(`/challenges/groups/${TAVERN_ID}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -377,12 +382,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -395,14 +400,14 @@ describe('GET challenges/groups/:groupId', () => {
});
it('should return tavern challenges using ID "habitrpg', async () => {
- let challenges = await user.get('/challenges/groups/habitrpg');
+ const challenges = await user.get('/challenges/groups/habitrpg');
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -412,12 +417,12 @@ describe('GET challenges/groups/:groupId', () => {
verifiedUsername: true,
},
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
diff --git a/test/api/v3/integration/challenges/GET-challenges_user.test.js b/test/api/v3/integration/challenges/GET-challenges_user.test.js
index c42510f640..abb7b32804 100644
--- a/test/api/v3/integration/challenges/GET-challenges_user.test.js
+++ b/test/api/v3/integration/challenges/GET-challenges_user.test.js
@@ -6,10 +6,11 @@ import {
describe('GET challenges/user', () => {
context('no official challenges', () => {
- let user, member, nonMember, challenge, challenge2, publicGuild;
+ let user; let member; let nonMember; let challenge; let challenge2; let
+ publicGuild;
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'TestGuild',
type: 'guild',
@@ -20,7 +21,7 @@ describe('GET challenges/user', () => {
user = groupLeader;
publicGuild = group;
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
nonMember = await generateUser();
challenge = await generateChallenge(user, group);
@@ -32,14 +33,14 @@ describe('GET challenges/user', () => {
it('should return challenges user has joined', async () => {
await nonMember.post(`/challenges/${challenge._id}/join`);
- let challenges = await nonMember.get('/challenges/user');
+ const challenges = await nonMember.get('/challenges/user');
- let foundChallenge = _.find(challenges, { _id: challenge._id });
+ const foundChallenge = _.find(challenges, { _id: challenge._id });
expect(foundChallenge).to.exist;
expect(foundChallenge.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -62,14 +63,14 @@ describe('GET challenges/user', () => {
});
it('should return challenges user has created', async () => {
- let challenges = await user.get('/challenges/user');
+ const challenges = await user.get('/challenges/user');
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -89,12 +90,12 @@ describe('GET challenges/user', () => {
summary: publicGuild.name,
leader: publicGuild.leader._id,
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -117,14 +118,14 @@ describe('GET challenges/user', () => {
});
it('should return challenges in user\'s group', async () => {
- let challenges = await member.get('/challenges/user');
+ const challenges = await member.get('/challenges/user');
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.exist;
expect(foundChallenge1.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -144,12 +145,12 @@ describe('GET challenges/user', () => {
summary: publicGuild.name,
leader: publicGuild.leader._id,
});
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.exist;
expect(foundChallenge2.leader).to.eql({
_id: publicGuild.leader._id,
id: publicGuild.leader._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -172,12 +173,12 @@ describe('GET challenges/user', () => {
});
it('should not return challenges in user groups if we send member true param', async () => {
- let challenges = await member.get(`/challenges/user?member=${true}`);
+ const challenges = await member.get(`/challenges/user?member=${true}`);
- let foundChallenge1 = _.find(challenges, { _id: challenge._id });
+ const foundChallenge1 = _.find(challenges, { _id: challenge._id });
expect(foundChallenge1).to.not.exist;
- let foundChallenge2 = _.find(challenges, { _id: challenge2._id });
+ const foundChallenge2 = _.find(challenges, { _id: challenge2._id });
expect(foundChallenge2).to.not.exist;
});
@@ -187,7 +188,7 @@ describe('GET challenges/user', () => {
let foundChallengeIndex = _.findIndex(challenges, { _id: challenge2._id });
expect(foundChallengeIndex).to.eql(0);
- let newChallenge = await generateChallenge(user, publicGuild);
+ const newChallenge = await generateChallenge(user, publicGuild);
await user.post(`/challenges/${newChallenge._id}/join`);
challenges = await user.get('/challenges/user');
@@ -197,7 +198,7 @@ describe('GET challenges/user', () => {
});
it('should not return challenges user doesn\'t have access to', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestPrivateGuild',
summary: 'summary for TestPrivateGuild',
@@ -206,17 +207,17 @@ describe('GET challenges/user', () => {
},
});
- let privateChallenge = await generateChallenge(groupLeader, group);
+ const privateChallenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${privateChallenge._id}/join`);
- let challenges = await nonMember.get('/challenges/user');
+ const challenges = await nonMember.get('/challenges/user');
- let foundChallenge = _.find(challenges, { _id: privateChallenge._id });
+ const foundChallenge = _.find(challenges, { _id: privateChallenge._id });
expect(foundChallenge).to.not.exist;
});
it('should not return challenges user doesn\'t have access to, even with query parameters', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestPrivateGuild',
summary: 'summary for TestPrivateGuild',
@@ -225,24 +226,27 @@ describe('GET challenges/user', () => {
},
});
- let privateChallenge = await generateChallenge(groupLeader, group, {categories: [{
- name: 'academics',
- slug: 'academics',
- }]});
+ const privateChallenge = await generateChallenge(groupLeader, group, {
+ categories: [{
+ name: 'academics',
+ slug: 'academics',
+ }],
+ });
await groupLeader.post(`/challenges/${privateChallenge._id}/join`);
- let challenges = await nonMember.get('/challenges/user?categories=academics&owned=not_owned');
+ const challenges = await nonMember.get('/challenges/user?categories=academics&owned=not_owned');
- let foundChallenge = _.find(challenges, { _id: privateChallenge._id });
+ const foundChallenge = _.find(challenges, { _id: privateChallenge._id });
expect(foundChallenge).to.not.exist;
});
});
context('official challenge is present', () => {
- let user, officialChallenge, challenge, challenge2, publicGuild;
+ let user; let officialChallenge; let challenge; let challenge2; let
+ publicGuild;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'TestGuild',
summary: 'summary for TestGuild',
@@ -273,9 +277,9 @@ describe('GET challenges/user', () => {
});
it('should return official challenges first', async () => {
- let challenges = await user.get('/challenges/user');
+ const challenges = await user.get('/challenges/user');
- let foundChallengeIndex = _.findIndex(challenges, { _id: officialChallenge._id });
+ const foundChallengeIndex = _.findIndex(challenges, { _id: officialChallenge._id });
expect(foundChallengeIndex).to.eql(0);
});
@@ -288,7 +292,7 @@ describe('GET challenges/user', () => {
foundChallengeIndex = _.findIndex(challenges, { _id: challenge2._id });
expect(foundChallengeIndex).to.eql(1);
- let newChallenge = await generateChallenge(user, publicGuild);
+ const newChallenge = await generateChallenge(user, publicGuild);
await user.post(`/challenges/${newChallenge._id}/join`);
challenges = await user.get('/challenges/user');
@@ -299,14 +303,15 @@ describe('GET challenges/user', () => {
});
context('filters and paging', () => {
- let user, guild, member;
+ let user; let guild; let
+ member;
const categories = [{
slug: 'newCat',
name: 'New Category',
}];
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'TestGuild',
type: 'guild',
@@ -317,9 +322,9 @@ describe('GET challenges/user', () => {
user = groupLeader;
guild = group;
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
- await user.update({balance: 20});
+ await user.update({ balance: 20 });
for (let i = 0; i < 11; i += 1) {
let challenge = await generateChallenge(user, group); // eslint-disable-line
@@ -328,7 +333,7 @@ describe('GET challenges/user', () => {
});
it('returns public guilds filtered by category', async () => {
- const categoryChallenge = await generateChallenge(user, guild, {categories});
+ const categoryChallenge = await generateChallenge(user, guild, { categories });
await user.post(`/challenges/${categoryChallenge._id}/join`);
const challenges = await user.get(`/challenges/user?categories=${categories[0].slug}`);
diff --git a/test/api/v3/integration/challenges/POST-challenges.test.js b/test/api/v3/integration/challenges/POST-challenges.test.js
index b53c3750b1..23475c1f23 100644
--- a/test/api/v3/integration/challenges/POST-challenges.test.js
+++ b/test/api/v3/integration/challenges/POST-challenges.test.js
@@ -1,13 +1,13 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
createAndPopulateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /challenges', () => {
it('returns error when group is empty', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post('/challenges')).to.eventually.be.rejected.and.eql({
code: 400,
@@ -17,7 +17,7 @@ describe('POST /challenges', () => {
});
it('returns error when groupId is not for a valid group', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post('/challenges', {
group: generateUUID(),
@@ -29,7 +29,7 @@ describe('POST /challenges', () => {
});
it('returns error when creating a challenge in the tavern with no prize', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post('/challenges', {
group: 'habitrpg',
@@ -42,8 +42,8 @@ describe('POST /challenges', () => {
});
it('returns error when creating a challenge in a public guild and you are not a member of it', async () => {
- let user = await generateUser();
- let { group } = await createAndPopulateGroup({
+ const user = await generateUser();
+ const { group } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -66,7 +66,7 @@ describe('POST /challenges', () => {
let groupMember;
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 1,
leaderDetails: {
balance: 3,
@@ -81,7 +81,7 @@ describe('POST /challenges', () => {
groupLeader = await populatedGroup.groupLeader.sync();
group = populatedGroup.group;
- groupMember = populatedGroup.members[0];
+ groupMember = populatedGroup.members[0]; // eslint-disable-line prefer-destructuring
});
it('returns an error when non-leader member creates a challenge in leaderOnly group', async () => {
@@ -95,14 +95,14 @@ describe('POST /challenges', () => {
});
it('allows non-leader member to create a challenge', async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 1,
});
group = populatedGroup.group;
- groupMember = populatedGroup.members[0];
+ groupMember = populatedGroup.members[0]; // eslint-disable-line prefer-destructuring
- let chal = await groupMember.post('/challenges', {
+ const chal = await groupMember.post('/challenges', {
group: group._id,
name: 'Test Challenge',
shortName: 'TC Label',
@@ -110,13 +110,13 @@ describe('POST /challenges', () => {
expect(chal.leader).to.eql({
_id: groupMember._id,
- profile: {name: groupMember.profile.name},
+ profile: { name: groupMember.profile.name },
});
});
it('doesn\'t take gems from user or group when challenge has no prize', async () => {
- let oldUserBalance = groupLeader.balance;
- let oldGroupBalance = group.balance;
+ const oldUserBalance = groupLeader.balance;
+ const oldGroupBalance = group.balance;
await groupLeader.post('/challenges', {
group: group._id,
@@ -143,9 +143,9 @@ describe('POST /challenges', () => {
});
it('takes prize out of group if it has sufficient funds', async () => {
- let oldUserBalance = groupLeader.balance;
- let oldGroupBalance = group.balance;
- let prize = 4;
+ const oldUserBalance = groupLeader.balance;
+ const oldGroupBalance = group.balance;
+ const prize = 4;
await groupLeader.post('/challenges', {
group: group._id,
@@ -159,8 +159,8 @@ describe('POST /challenges', () => {
});
it('takes prize out of both group and user if group doesn\'t have enough', async () => {
- let oldUserBalance = groupLeader.balance;
- let prize = 8;
+ const oldUserBalance = groupLeader.balance;
+ const prize = 8;
await groupLeader.post('/challenges', {
group: group._id,
@@ -170,14 +170,14 @@ describe('POST /challenges', () => {
});
await expect(group.sync()).to.eventually.have.property('balance', 0);
- await expect(groupLeader.sync()).to.eventually.have.property('balance', oldUserBalance - (prize / 4 - 1));
+ await expect(groupLeader.sync()).to.eventually.have.property('balance', oldUserBalance - (prize / 4 - 1));
});
it('takes prize out of user if group has no balance', async () => {
- let oldUserBalance = groupLeader.balance;
- let prize = 8;
+ const oldUserBalance = groupLeader.balance;
+ const prize = 8;
- await group.update({ balance: 0});
+ await group.update({ balance: 0 });
await groupLeader.post('/challenges', {
group: group._id,
name: 'Test Challenge',
@@ -190,7 +190,7 @@ describe('POST /challenges', () => {
});
it('increases challenge count of group', async () => {
- let oldChallengeCount = group.challengeCount;
+ const oldChallengeCount = group.challengeCount;
await groupLeader.post('/challenges', {
group: group._id,
@@ -208,7 +208,7 @@ describe('POST /challenges', () => {
},
});
- let challenge = await groupLeader.post('/challenges', {
+ const challenge = await groupLeader.post('/challenges', {
group: group._id,
name: 'Test Challenge',
shortName: 'TC Label',
@@ -219,7 +219,7 @@ describe('POST /challenges', () => {
});
it('doesn\'t set challenge as official if official flag is set by non-admin', async () => {
- let challenge = await groupLeader.post('/challenges', {
+ const challenge = await groupLeader.post('/challenges', {
group: group._id,
name: 'Test Challenge',
shortName: 'TC Label',
@@ -230,9 +230,9 @@ describe('POST /challenges', () => {
});
it('returns an error when challenge validation fails; doesn\'s save user or group', async () => {
- let oldChallengeCount = group.challengeCount;
- let oldUserBalance = groupLeader.balance;
- let oldGroupBalance = group.balance;
+ const oldChallengeCount = group.challengeCount;
+ const oldUserBalance = groupLeader.balance;
+ const oldGroupBalance = group.balance;
await expect(groupLeader.post('/challenges', {
group: group._id,
@@ -252,12 +252,12 @@ describe('POST /challenges', () => {
});
it('sets all properites of the challenge as passed', async () => {
- let name = 'Test Challenge';
- let shortName = 'TC Label';
- let description = 'Test Description';
- let prize = 4;
+ const name = 'Test Challenge';
+ const shortName = 'TC Label';
+ const description = 'Test Description';
+ const prize = 4;
- let challenge = await groupLeader.post('/challenges', {
+ const challenge = await groupLeader.post('/challenges', {
group: group._id,
name,
shortName,
@@ -267,7 +267,7 @@ describe('POST /challenges', () => {
expect(challenge.leader).to.eql({
_id: groupLeader._id,
- profile: {name: groupLeader.profile.name},
+ profile: { name: groupLeader.profile.name },
});
expect(challenge.name).to.eql(name);
expect(challenge.shortName).to.eql(shortName);
diff --git a/test/api/v3/integration/challenges/POST-challenges_challengeId_join.test.js b/test/api/v3/integration/challenges/POST-challenges_challengeId_join.test.js
index 8385d63e36..fad086cd4f 100644
--- a/test/api/v3/integration/challenges/POST-challenges_challengeId_join.test.js
+++ b/test/api/v3/integration/challenges/POST-challenges_challengeId_join.test.js
@@ -1,14 +1,14 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateChallenge,
createAndPopulateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /challenges/:challengeId/join', () => {
it('returns error when challengeId is not a valid UUID', async () => {
- let user = await generateUser({ balance: 1});
+ const user = await generateUser({ balance: 1 });
await expect(user.post('/challenges/test/join')).to.eventually.be.rejected.and.eql({
code: 400,
@@ -18,7 +18,7 @@ describe('POST /challenges/:challengeId/join', () => {
});
it('returns error when challengeId is not for a valid challenge', async () => {
- let user = await generateUser({ balance: 1});
+ const user = await generateUser({ balance: 1 });
await expect(user.post(`/challenges/${generateUUID()}/join`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -34,20 +34,20 @@ describe('POST /challenges/:challengeId/join', () => {
let authorizedUser;
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 1,
});
groupLeader = populatedGroup.groupLeader;
group = populatedGroup.group;
- authorizedUser = populatedGroup.members[0];
+ authorizedUser = populatedGroup.members[0]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
});
it('returns an error when user isn\'t in the private group and isn\'t challenge leader', async () => {
- let unauthorizedUser = await generateUser();
+ const unauthorizedUser = await generateUser();
await expect(unauthorizedUser.post(`/challenges/${challenge._id}/join`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -62,12 +62,12 @@ describe('POST /challenges/:challengeId/join', () => {
await groupLeader.sync();
expect(groupLeader.guilds).to.be.empty; // check that leaving worked
- let res = await groupLeader.post(`/challenges/${challenge._id}/join`);
+ const res = await groupLeader.post(`/challenges/${challenge._id}/join`);
expect(res.name).to.equal(challenge.name);
});
it('returns challenge data', async () => {
- let res = await authorizedUser.post(`/challenges/${challenge._id}/join`);
+ const res = await authorizedUser.post(`/challenges/${challenge._id}/join`);
expect(res.group).to.eql({
_id: group._id,
@@ -78,7 +78,7 @@ describe('POST /challenges/:challengeId/join', () => {
expect(res.leader).to.eql({
_id: groupLeader._id,
id: groupLeader._id,
- profile: {name: groupLeader.profile.name},
+ profile: { name: groupLeader.profile.name },
auth: {
local: {
username: groupLeader.auth.local.username,
@@ -111,7 +111,7 @@ describe('POST /challenges/:challengeId/join', () => {
it('increases memberCount of challenge', async () => {
await challenge.sync();
- let oldMemberCount = challenge.memberCount;
+ const oldMemberCount = challenge.memberCount;
await authorizedUser.post(`/challenges/${challenge._id}/join`);
@@ -123,15 +123,13 @@ describe('POST /challenges/:challengeId/join', () => {
it('syncs challenge tasks to joining user', async () => {
const taskText = 'A challenge task text';
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'daily', text: taskText},
+ { type: 'daily', text: taskText },
]);
await authorizedUser.post(`/challenges/${challenge._id}/join`);
const tasks = await authorizedUser.get('/tasks/user');
- const syncedTask = tasks.find((task) => {
- return task.text === taskText;
- });
+ const syncedTask = tasks.find(task => task.text === taskText);
expect(syncedTask.text).to.eql(taskText);
expect(syncedTask.isDue).to.exist;
@@ -139,7 +137,7 @@ describe('POST /challenges/:challengeId/join', () => {
});
it('adds challenge tag to user tags', async () => {
- let userTagsLength = (await authorizedUser.get('/tags')).length;
+ const userTagsLength = (await authorizedUser.get('/tags')).length;
await authorizedUser.post(`/challenges/${challenge._id}/join`);
diff --git a/test/api/v3/integration/challenges/POST-challenges_challengeId_leave.test.js b/test/api/v3/integration/challenges/POST-challenges_challengeId_leave.test.js
index 080f7a92ef..c6304151a1 100644
--- a/test/api/v3/integration/challenges/POST-challenges_challengeId_leave.test.js
+++ b/test/api/v3/integration/challenges/POST-challenges_challengeId_leave.test.js
@@ -1,14 +1,14 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateChallenge,
createAndPopulateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /challenges/:challengeId/leave', () => {
it('returns error when challengeId is not a valid UUID', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post('/challenges/test/leave')).to.eventually.be.rejected.and.eql({
code: 400,
@@ -18,7 +18,7 @@ describe('POST /challenges/:challengeId/leave', () => {
});
it('returns error when challengeId is not for a valid challenge', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post(`/challenges/${generateUUID()}/leave`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -37,15 +37,15 @@ describe('POST /challenges/:challengeId/leave', () => {
let taskText;
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 3,
});
groupLeader = populatedGroup.groupLeader;
group = populatedGroup.group;
- leavingUser = populatedGroup.members[0];
- notInChallengeUser = populatedGroup.members[1];
- notInGroupLeavingUser = populatedGroup.members[2];
+ leavingUser = populatedGroup.members[0]; // eslint-disable-line prefer-destructuring
+ notInChallengeUser = populatedGroup.members[1]; // eslint-disable-line prefer-destructuring
+ notInGroupLeavingUser = populatedGroup.members[2]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
@@ -53,7 +53,7 @@ describe('POST /challenges/:challengeId/leave', () => {
taskText = 'A challenge task text';
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: taskText},
+ { type: 'habit', text: taskText },
]);
await leavingUser.post(`/challenges/${challenge._id}/join`);
@@ -87,7 +87,7 @@ describe('POST /challenges/:challengeId/leave', () => {
});
it('decreases memberCount of challenge', async () => {
- let oldMemberCount = challenge.memberCount;
+ const oldMemberCount = challenge.memberCount;
await leavingUser.post(`/challenges/${challenge._id}/leave`);
@@ -100,10 +100,8 @@ describe('POST /challenges/:challengeId/leave', () => {
await leavingUser.post(`/challenges/${challenge._id}/leave`, {
keep: 'remove-all',
});
- let tasks = await leavingUser.get('/tasks/user');
- let tasksTexts = tasks.map((task) => {
- return task.text;
- });
+ const tasks = await leavingUser.get('/tasks/user');
+ const tasksTexts = tasks.map(task => task.text);
expect(tasksTexts).to.not.include(taskText);
});
@@ -113,10 +111,8 @@ describe('POST /challenges/:challengeId/leave', () => {
keep: 'test',
});
- let tasks = await leavingUser.get('/tasks/user');
- let testTask = _.find(tasks, (task) => {
- return task.text === taskText;
- });
+ const tasks = await leavingUser.get('/tasks/user');
+ const testTask = _.find(tasks, task => task.text === taskText);
expect(testTask).to.not.be.undefined;
});
diff --git a/test/api/v3/integration/challenges/POST-challenges_challengeId_winner_winnerId.test.js b/test/api/v3/integration/challenges/POST-challenges_challengeId_winner_winnerId.test.js
index 41c655b88c..3f3b75e7fe 100644
--- a/test/api/v3/integration/challenges/POST-challenges_challengeId_winner_winnerId.test.js
+++ b/test/api/v3/integration/challenges/POST-challenges_challengeId_winner_winnerId.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateChallenge,
@@ -6,11 +7,10 @@ import {
checkExistence,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /challenges/:challengeId/winner/:winnerId', () => {
it('returns error when challengeId is not a valid UUID', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post(`/challenges/test/selectWinner/${user._id}`)).to.eventually.be.rejected.and.eql({
code: 400,
@@ -20,7 +20,7 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
});
it('returns error when winnerId is not a valid UUID', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post(`/challenges/${generateUUID()}/selectWinner/test`)).to.eventually.be.rejected.and.eql({
code: 400,
@@ -30,7 +30,7 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
});
it('returns error when challengeId is not for a valid challenge', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post(`/challenges/${generateUUID()}/selectWinner/${user._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -44,16 +44,16 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
let group;
let challenge;
let winningUser;
- let taskText = 'A challenge task text';
+ const taskText = 'A challenge task text';
beforeEach(async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 1,
});
groupLeader = populatedGroup.groupLeader;
group = populatedGroup.group;
- winningUser = populatedGroup.members[0];
+ winningUser = populatedGroup.members[0]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(groupLeader, group, {
prize: 1,
@@ -61,7 +61,7 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
await groupLeader.post(`/challenges/${challenge._id}/join`);
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: taskText},
+ { type: 'habit', text: taskText },
]);
await winningUser.post(`/challenges/${challenge._id}/join`);
@@ -78,12 +78,12 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
});
it('returns an error when winning user isn\'t part of the challenge', async () => {
- let notInChallengeUser = await generateUser();
+ const notInChallengeUser = await generateUser();
await expect(groupLeader.post(`/challenges/${challenge._id}/selectWinner/${notInChallengeUser._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('winnerNotFound', {userId: notInChallengeUser._id}),
+ message: t('winnerNotFound', { userId: notInChallengeUser._id }),
});
});
@@ -101,12 +101,13 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
await sleep(0.5);
await expect(winningUser.sync()).to.eventually.have.nested.property('achievements.challenges').to.include(challenge.name);
- expect(winningUser.notifications.length).to.equal(2); // 2 because winningUser just joined the challenge, which now awards an achievement
+ // 2 because winningUser just joined the challenge, which now awards an achievement
+ expect(winningUser.notifications.length).to.equal(2);
expect(winningUser.notifications[1].type).to.equal('WON_CHALLENGE');
});
it('gives winner gems as reward', async () => {
- let oldBalance = winningUser.balance;
+ const oldBalance = winningUser.balance;
await groupLeader.post(`/challenges/${challenge._id}/selectWinner/${winningUser._id}`);
@@ -116,8 +117,8 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
});
it('doesn\'t gives winner gems if group policy prevents it', async () => {
- let oldBalance = winningUser.balance;
- let oldLeaderBalance = (await groupLeader.sync()).balance;
+ const oldBalance = winningUser.balance;
+ const oldLeaderBalance = (await groupLeader.sync()).balance;
await winningUser.update({
'purchased.plan.customerId': 'group-plan',
@@ -136,7 +137,7 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
});
it('doesn\'t refund gems to group leader', async () => {
- let oldBalance = (await groupLeader.sync()).balance;
+ const oldBalance = (await groupLeader.sync()).balance;
await groupLeader.post(`/challenges/${challenge._id}/selectWinner/${winningUser._id}`);
@@ -151,14 +152,10 @@ describe('POST /challenges/:challengeId/winner/:winnerId', () => {
await sleep(0.5);
const tasks = await winningUser.get('/tasks/user');
- const testTask = _.find(tasks, (task) => {
- return task.text === taskText;
- });
+ const testTask = _.find(tasks, task => task.text === taskText);
const updatedUser = await winningUser.sync();
- const challengeTag = updatedUser.tags.find(tags => {
- return tags.id === challenge._id;
- });
+ const challengeTag = updatedUser.tags.find(tags => tags.id === challenge._id);
expect(testTask.challenge.broken).to.eql('CHALLENGE_CLOSED');
expect(testTask.challenge.winner).to.eql(winningUser.profile.name);
diff --git a/test/api/v3/integration/challenges/POST_challenges_id_clone.test.js b/test/api/v3/integration/challenges/POST_challenges_id_clone.test.js
index 3f2abd8a0b..6f9844b415 100644
--- a/test/api/v3/integration/challenges/POST_challenges_id_clone.test.js
+++ b/test/api/v3/integration/challenges/POST_challenges_id_clone.test.js
@@ -5,7 +5,7 @@ import {
describe('POST /challenges/:challengeId/clone', () => {
it('clones a challenge', async () => {
- const user = await generateUser({balance: 10});
+ const user = await generateUser({ balance: 10 });
const group = await generateGroup(user);
const name = 'Test Challenge';
@@ -38,6 +38,7 @@ describe('POST /challenges/:challengeId/clone', () => {
expect(cloneChallengeResponse.clonedTasks[0].text).to.eql(challengeTask.text);
expect(cloneChallengeResponse.clonedTasks[0]._id).to.not.eql(challengeTask._id);
- expect(cloneChallengeResponse.clonedTasks[0].challenge.id).to.eql(cloneChallengeResponse.clonedChallenge._id);
+ expect(cloneChallengeResponse.clonedTasks[0].challenge.id)
+ .to.eql(cloneChallengeResponse.clonedChallenge._id);
});
});
diff --git a/test/api/v3/integration/challenges/PUT-challenges_challengeId.test.js b/test/api/v3/integration/challenges/PUT-challenges_challengeId.test.js
index d5f5d88c15..6b43a220a2 100644
--- a/test/api/v3/integration/challenges/PUT-challenges_challengeId.test.js
+++ b/test/api/v3/integration/challenges/PUT-challenges_challengeId.test.js
@@ -6,10 +6,11 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('PUT /challenges/:challengeId', () => {
- let privateGuild, user, nonMember, challenge, member;
+ let privateGuild; let user; let nonMember; let challenge; let
+ member;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'TestPrivateGuild',
type: 'guild',
@@ -22,7 +23,7 @@ describe('PUT /challenges/:challengeId', () => {
user = groupLeader;
nonMember = await generateUser();
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
challenge = await generateChallenge(user, group);
await user.post(`/challenges/${challenge._id}/join`);
@@ -48,7 +49,7 @@ describe('PUT /challenges/:challengeId', () => {
});
it('only updates allowed fields', async () => {
- let res = await user.put(`/challenges/${challenge._id}`, {
+ const res = await user.put(`/challenges/${challenge._id}`, {
// ignored
prize: 33,
group: 'blabla',
@@ -78,7 +79,7 @@ describe('PUT /challenges/:challengeId', () => {
expect(res.leader).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
diff --git a/test/api/v3/integration/chat/DELETE-chat_id.test.js b/test/api/v3/integration/chat/DELETE-chat_id.test.js
index 929ec790b6..58203ea94d 100644
--- a/test/api/v3/integration/chat/DELETE-chat_id.test.js
+++ b/test/api/v3/integration/chat/DELETE-chat_id.test.js
@@ -1,15 +1,16 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /groups/:groupId/chat/:chatId', () => {
- let groupWithChat, message, user, userThatDidNotCreateChat, admin;
+ let groupWithChat; let message; let user; let userThatDidNotCreateChat; let
+ admin;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -21,12 +22,12 @@ describe('DELETE /groups/:groupId/chat/:chatId', () => {
message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: 'Some message' });
message = message.message;
userThatDidNotCreateChat = await generateUser();
- admin = await generateUser({'contributor.admin': true});
+ admin = await generateUser({ 'contributor.admin': true });
});
context('Chat errors', () => {
it('returns an error is message does not exist', async () => {
- let fakeChatId = generateUUID();
+ const fakeChatId = generateUUID();
await expect(user.del(`/groups/${groupWithChat._id}/chat/${fakeChatId}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -55,9 +56,9 @@ describe('DELETE /groups/:groupId/chat/:chatId', () => {
await user.del(`/groups/${groupWithChat._id}/chat/${nextMessage.id}`);
const returnedMessages = await user.get(`/groups/${groupWithChat._id}/chat/`);
- const messageFromUser = returnedMessages.find(returnedMessage => {
- return returnedMessage.id === nextMessage.id;
- });
+ const messageFromUser = returnedMessages.find(
+ returnedMessage => returnedMessage.id === nextMessage.id,
+ );
expect(returnedMessages).is.an('array');
expect(messageFromUser).to.not.exist;
@@ -67,9 +68,9 @@ describe('DELETE /groups/:groupId/chat/:chatId', () => {
await admin.del(`/groups/${groupWithChat._id}/chat/${nextMessage.id}`);
const returnedMessages = await user.get(`/groups/${groupWithChat._id}/chat/`);
- const messageFromUser = returnedMessages.find(returnedMessage => {
- return returnedMessage.id === nextMessage.id;
- });
+ const messageFromUser = returnedMessages.find(
+ returnedMessage => returnedMessage.id === nextMessage.id,
+ );
expect(returnedMessages).is.an('array');
expect(messageFromUser).to.not.exist;
diff --git a/test/api/v3/integration/chat/GET-chat.test.js b/test/api/v3/integration/chat/GET-chat.test.js
index e3a9d17548..910b094c40 100644
--- a/test/api/v3/integration/chat/GET-chat.test.js
+++ b/test/api/v3/integration/chat/GET-chat.test.js
@@ -15,7 +15,7 @@ describe('GET /groups/:groupId/chat', () => {
let group;
before(async () => {
- let leader = await generateUser({balance: 2});
+ const leader = await generateUser({ balance: 2 });
group = await generateGroup(leader, {
name: 'test group',
@@ -23,8 +23,8 @@ describe('GET /groups/:groupId/chat', () => {
privacy: 'public',
}, {
chat: [
- {text: 'Hello', flags: {}, id: 1},
- {text: 'Welcome to the Guild', flags: {}, id: 2},
+ { text: 'Hello', flags: {}, id: 1 },
+ { text: 'Welcome to the Guild', flags: {}, id: 2 },
],
});
});
@@ -41,7 +41,7 @@ describe('GET /groups/:groupId/chat', () => {
let group;
before(async () => {
- let leader = await generateUser({balance: 2});
+ const leader = await generateUser({ balance: 2 });
group = await generateGroup(leader, {
name: 'test group',
diff --git a/test/api/v3/integration/chat/POST-chat.flag.test.js b/test/api/v3/integration/chat/POST-chat.flag.test.js
index 723715c80b..d3484452f3 100644
--- a/test/api/v3/integration/chat/POST-chat.flag.test.js
+++ b/test/api/v3/integration/chat/POST-chat.flag.test.js
@@ -1,24 +1,25 @@
-import {
- generateUser,
- translate as t,
-} from '../../../../helpers/api-integration/v3';
import { find } from 'lodash';
import moment from 'moment';
import nconf from 'nconf';
import { IncomingWebhook } from '@slack/client';
+import {
+ generateUser,
+ translate as t,
+} from '../../../../helpers/api-integration/v3';
const BASE_URL = nconf.get('BASE_URL');
describe('POST /chat/:chatId/flag', () => {
- let user, admin, anotherUser, newUser, group;
+ let user; let admin; let anotherUser; let newUser; let
+ group;
const TEST_MESSAGE = 'Test Message';
const USER_AGE_FOR_FLAGGING = 3;
beforeEach(async () => {
- user = await generateUser({balance: 1, 'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate()});
- admin = await generateUser({balance: 1, 'contributor.admin': true});
- anotherUser = await generateUser({'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate()});
- newUser = await generateUser({'auth.timestamps.created': moment().subtract(1, 'days').toDate()});
+ user = await generateUser({ balance: 1, 'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate() });
+ admin = await generateUser({ balance: 1, 'contributor.admin': true });
+ anotherUser = await generateUser({ 'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate() });
+ newUser = await generateUser({ 'auth.timestamps.created': moment().subtract(1, 'days').toDate() });
sandbox.stub(IncomingWebhook.prototype, 'send');
group = await user.post('/groups', {
@@ -42,20 +43,20 @@ describe('POST /chat/:chatId/flag', () => {
});
it('Allows players to flag their own message', async () => {
- let message = await user.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const message = await user.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
await expect(user.post(`/groups/${group._id}/chat/${message.message.id}/flag`)).to.eventually.be.ok;
});
it('Flags a chat and sends normal message to moderator Slack when user is not new', async () => {
- let { message } = await anotherUser.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await anotherUser.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
- let flagResult = await user.post(`/groups/${group._id}/chat/${message.id}/flag`);
+ const flagResult = await user.post(`/groups/${group._id}/chat/${message.id}/flag`);
expect(flagResult.flags[user._id]).to.equal(true);
expect(flagResult.flagCount).to.equal(1);
- let groupWithFlags = await admin.get(`/groups/${group._id}`);
+ const groupWithFlags = await admin.get(`/groups/${group._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck.flags[user._id]).to.equal(true);
// Slack message to mods
@@ -81,16 +82,16 @@ describe('POST /chat/:chatId/flag', () => {
});
it('Does not increment message flag count and sends different message to moderator Slack when user is new', async () => {
- let automatedComment = `The post's flag count has not been increased because the flagger's account is less than ${USER_AGE_FOR_FLAGGING} days old.`;
- let { message } = await newUser.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const automatedComment = `The post's flag count has not been increased because the flagger's account is less than ${USER_AGE_FOR_FLAGGING} days old.`;
+ const { message } = await newUser.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
- let flagResult = await newUser.post(`/groups/${group._id}/chat/${message.id}/flag`);
+ const flagResult = await newUser.post(`/groups/${group._id}/chat/${message.id}/flag`);
expect(flagResult.flags[newUser._id]).to.equal(true);
expect(flagResult.flagCount).to.equal(0);
- let groupWithFlags = await admin.get(`/groups/${group._id}`);
+ const groupWithFlags = await admin.get(`/groups/${group._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck.flags[newUser._id]).to.equal(true);
// Slack message to mods
@@ -116,38 +117,38 @@ describe('POST /chat/:chatId/flag', () => {
});
it('Flags a chat when the author\'s account was deleted', async () => {
- let deletedUser = await generateUser();
- let { message } = await deletedUser.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const deletedUser = await generateUser();
+ const { message } = await deletedUser.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
await deletedUser.del('/user', {
password: 'password',
});
- let flagResult = await user.post(`/groups/${group._id}/chat/${message.id}/flag`);
+ const flagResult = await user.post(`/groups/${group._id}/chat/${message.id}/flag`);
expect(flagResult.flags[user._id]).to.equal(true);
expect(flagResult.flagCount).to.equal(1);
- let groupWithFlags = await admin.get(`/groups/${group._id}`);
+ const groupWithFlags = await admin.get(`/groups/${group._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck.flags[user._id]).to.equal(true);
});
it('Flags a chat with a higher flag acount when an admin flags the message', async () => {
- let { message } = await user.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await user.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
- let flagResult = await admin.post(`/groups/${group._id}/chat/${message.id}/flag`);
+ const flagResult = await admin.post(`/groups/${group._id}/chat/${message.id}/flag`);
expect(flagResult.flags[admin._id]).to.equal(true);
expect(flagResult.flagCount).to.equal(5);
- let groupWithFlags = await admin.get(`/groups/${group._id}`);
+ const groupWithFlags = await admin.get(`/groups/${group._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck.flags[admin._id]).to.equal(true);
expect(messageToCheck.flagCount).to.equal(5);
});
it('allows admin to flag a message in a private group', async () => {
- let privateGroup = await user.post('/groups', {
+ const privateGroup = await user.post('/groups', {
name: 'Test party',
type: 'party',
privacy: 'private',
@@ -156,26 +157,26 @@ describe('POST /chat/:chatId/flag', () => {
uuids: [anotherUser._id],
});
await anotherUser.post(`/groups/${privateGroup._id}/join`);
- let { message } = await user.post(`/groups/${privateGroup._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await user.post(`/groups/${privateGroup._id}/chat`, { message: TEST_MESSAGE });
- let flagResult = await admin.post(`/groups/${privateGroup._id}/chat/${message.id}/flag`);
+ const flagResult = await admin.post(`/groups/${privateGroup._id}/chat/${message.id}/flag`);
expect(flagResult.flags[admin._id]).to.equal(true);
expect(flagResult.flagCount).to.equal(5);
- let groupWithFlags = await anotherUser.get(`/groups/${privateGroup._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const groupWithFlags = await anotherUser.get(`/groups/${privateGroup._id}`);
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck).to.not.exist;
});
it('does not allow non member to flag message in private group', async () => {
- let privateGroup = await user.post('/groups', {
+ const privateGroup = await user.post('/groups', {
name: 'Test party',
type: 'party',
privacy: 'private',
});
- let { message } = await user.post(`/groups/${privateGroup._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await user.post(`/groups/${privateGroup._id}/chat`, { message: TEST_MESSAGE });
await expect(anotherUser.post(`/groups/${privateGroup._id}/chat/${message.id}/flag`))
.to.eventually.be.rejected.and.eql({
@@ -186,7 +187,7 @@ describe('POST /chat/:chatId/flag', () => {
});
it('Returns an error when user tries to flag a message that they already flagged', async () => {
- let { message } = await anotherUser.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await anotherUser.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
await user.post(`/groups/${group._id}/chat/${message.id}/flag`);
@@ -199,17 +200,17 @@ describe('POST /chat/:chatId/flag', () => {
});
it('shows a hidden message to the original poster', async () => {
- let { message } = await user.post(`/groups/${group._id}/chat`, {message: TEST_MESSAGE});
+ const { message } = await user.post(`/groups/${group._id}/chat`, { message: TEST_MESSAGE });
await admin.post(`/groups/${group._id}/chat/${message.id}/flag`);
- let groupWithFlags = await user.get(`/groups/${group._id}`);
- let messageToCheck = find(groupWithFlags.chat, {id: message.id});
+ const groupWithFlags = await user.get(`/groups/${group._id}`);
+ const messageToCheck = find(groupWithFlags.chat, { id: message.id });
expect(messageToCheck).to.exist;
- let auGroupWithFlags = await anotherUser.get(`/groups/${group._id}`);
- let auMessageToCheck = find(auGroupWithFlags.chat, {id: message.id});
+ const auGroupWithFlags = await anotherUser.get(`/groups/${group._id}`);
+ const auMessageToCheck = find(auGroupWithFlags.chat, { id: message.id });
expect(auMessageToCheck).to.not.exist;
});
diff --git a/test/api/v3/integration/chat/POST-chat.like.test.js b/test/api/v3/integration/chat/POST-chat.like.test.js
index a6dfb7d795..192f3e3aa7 100644
--- a/test/api/v3/integration/chat/POST-chat.like.test.js
+++ b/test/api/v3/integration/chat/POST-chat.like.test.js
@@ -1,17 +1,17 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /chat/:chatId/like', () => {
let user;
let groupWithChat;
- let testMessage = 'Test Message';
+ const testMessage = 'Test Message';
let anotherUser;
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -22,7 +22,7 @@ describe('POST /chat/:chatId/like', () => {
user = groupLeader;
groupWithChat = group;
- anotherUser = members[0];
+ anotherUser = members[0]; // eslint-disable-line prefer-destructuring
});
it('Returns an error when chat message is not found', async () => {
@@ -35,7 +35,7 @@ describe('POST /chat/:chatId/like', () => {
});
it('Returns an error when user tries to like their own message', async () => {
- let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
await expect(user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`))
.to.eventually.be.rejected.and.eql({
@@ -46,30 +46,30 @@ describe('POST /chat/:chatId/like', () => {
});
it('Likes a chat', async () => {
- let message = await anotherUser.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await anotherUser.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
- let likeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
+ const likeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
expect(likeResult.likes[user._id]).to.equal(true);
- let groupWithChatLikes = await user.get(`/groups/${groupWithChat._id}`);
+ const groupWithChatLikes = await user.get(`/groups/${groupWithChat._id}`);
- let messageToCheck = find(groupWithChatLikes.chat, {id: message.message.id});
+ const messageToCheck = find(groupWithChatLikes.chat, { id: message.message.id });
expect(messageToCheck.likes[user._id]).to.equal(true);
});
it('Unlikes a chat', async () => {
- let message = await anotherUser.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await anotherUser.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
- let likeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
+ const likeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
expect(likeResult.likes[user._id]).to.equal(true);
- let unlikeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
+ const unlikeResult = await user.post(`/groups/${groupWithChat._id}/chat/${message.message.id}/like`);
expect(unlikeResult.likes[user._id]).to.equal(false);
- let groupWithoutChatLikes = await user.get(`/groups/${groupWithChat._id}`);
+ const groupWithoutChatLikes = await user.get(`/groups/${groupWithChat._id}`);
- let messageToCheck = find(groupWithoutChatLikes.chat, {id: message.message.id});
+ const messageToCheck = find(groupWithoutChatLikes.chat, { id: message.message.id });
expect(messageToCheck.likes[user._id]).to.equal(false);
});
});
diff --git a/test/api/v3/integration/chat/POST-chat.test.js b/test/api/v3/integration/chat/POST-chat.test.js
index 73ac2d3bf9..bf537ff449 100644
--- a/test/api/v3/integration/chat/POST-chat.test.js
+++ b/test/api/v3/integration/chat/POST-chat.test.js
@@ -1,5 +1,6 @@
import { IncomingWebhook } from '@slack/client';
import nconf from 'nconf';
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
generateUser,
@@ -13,7 +14,6 @@ import {
TAVERN_ID,
} from '../../../../../website/server/models/group';
import { CHAT_FLAG_FROM_SHADOW_MUTE } from '../../../../../website/common/script/constants';
-import { v4 as generateUUID } from 'uuid';
import { getMatchesByWordArray } from '../../../../../website/server/libs/stringUtils';
import bannedWords from '../../../../../website/server/libs/bannedWords';
import guildsAllowingBannedWords from '../../../../../website/server/libs/guildsAllowingBannedWords';
@@ -22,16 +22,17 @@ import * as email from '../../../../../website/server/libs/email';
const BASE_URL = nconf.get('BASE_URL');
describe('POST /chat', () => {
- let user, groupWithChat, member, additionalMember;
- let testMessage = 'Test Message';
- let testBannedWordMessage = 'TESTPLACEHOLDERSWEARWORDHERE';
- let testBannedWordMessage1 = 'TESTPLACEHOLDERSWEARWORDHERE1';
- let testSlurMessage = 'message with TESTPLACEHOLDERSLURWORDHERE';
- let testSlurMessage1 = 'TESTPLACEHOLDERSLURWORDHERE1';
- let bannedWordErrorMessage = t('bannedWordUsed', {swearWordsUsed: testBannedWordMessage});
+ let user; let groupWithChat; let member; let
+ additionalMember;
+ const testMessage = 'Test Message';
+ const testBannedWordMessage = 'TESTPLACEHOLDERSWEARWORDHERE';
+ const testBannedWordMessage1 = 'TESTPLACEHOLDERSWEARWORDHERE1';
+ const testSlurMessage = 'message with TESTPLACEHOLDERSLURWORDHERE';
+ const testSlurMessage1 = 'TESTPLACEHOLDERSLURWORDHERE1';
+ const bannedWordErrorMessage = t('bannedWordUsed', { swearWordsUsed: testBannedWordMessage });
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -40,14 +41,14 @@ describe('POST /chat', () => {
members: 2,
});
user = groupLeader;
- await user.update({'contributor.level': SPAM_MIN_EXEMPT_CONTRIB_LEVEL}); // prevent tests accidentally throwing messageGroupChatSpam
+ await user.update({ 'contributor.level': SPAM_MIN_EXEMPT_CONTRIB_LEVEL }); // prevent tests accidentally throwing messageGroupChatSpam
groupWithChat = group;
- member = members[0];
- additionalMember = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ additionalMember = members[1]; // eslint-disable-line prefer-destructuring
});
it('Returns an error when no message is provided', async () => {
- await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: ''}))
+ await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: '' }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -56,7 +57,7 @@ describe('POST /chat', () => {
});
it('Returns an error when an empty message is provided', async () => {
- await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: ' '}))
+ await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: ' ' }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -65,7 +66,7 @@ describe('POST /chat', () => {
});
it('Returns an error when an message containing only newlines is provided', async () => {
- await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: '\n\n'}))
+ await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: '\n\n' }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -74,7 +75,7 @@ describe('POST /chat', () => {
});
it('Returns an error when group is not found', async () => {
- await expect(user.post('/groups/invalidID/chat', { message: testMessage})).to.eventually.be.rejected.and.eql({
+ await expect(user.post('/groups/invalidID/chat', { message: testMessage })).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
message: t('groupNotFound'),
@@ -83,12 +84,12 @@ describe('POST /chat', () => {
describe('mute user', () => {
afterEach(() => {
- member.update({'flags.chatRevoked': false});
+ member.update({ 'flags.chatRevoked': false });
});
it('returns an error when chat privileges are revoked when sending a message to a public guild', async () => {
- const userWithChatRevoked = await member.update({'flags.chatRevoked': true});
- await expect(userWithChatRevoked.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage})).to.eventually.be.rejected.and.eql({
+ const userWithChatRevoked = await member.update({ 'flags.chatRevoked': true });
+ await expect(userWithChatRevoked.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage })).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
message: t('chatPrivilegesRevoked'),
@@ -106,9 +107,9 @@ describe('POST /chat', () => {
});
const privateGuildMemberWithChatsRevoked = members[0];
- await privateGuildMemberWithChatsRevoked.update({'flags.chatRevoked': true});
+ await privateGuildMemberWithChatsRevoked.update({ 'flags.chatRevoked': true });
- const message = await privateGuildMemberWithChatsRevoked.post(`/groups/${group._id}/chat`, { message: testMessage});
+ const message = await privateGuildMemberWithChatsRevoked.post(`/groups/${group._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
});
@@ -124,9 +125,9 @@ describe('POST /chat', () => {
});
const privatePartyMemberWithChatsRevoked = members[0];
- await privatePartyMemberWithChatsRevoked.update({'flags.chatRevoked': true});
+ await privatePartyMemberWithChatsRevoked.update({ 'flags.chatRevoked': true });
- const message = await privatePartyMemberWithChatsRevoked.post(`/groups/${group._id}/chat`, { message: testMessage});
+ const message = await privatePartyMemberWithChatsRevoked.post(`/groups/${group._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
});
@@ -140,12 +141,12 @@ describe('POST /chat', () => {
afterEach(() => {
sandbox.restore();
- member.update({'flags.chatShadowMuted': false});
+ member.update({ 'flags.chatShadowMuted': false });
});
it('creates a chat with flagCount already set and notifies mods when sending a message to a public guild', async () => {
- const userWithChatShadowMuted = await member.update({'flags.chatShadowMuted': true});
- const message = await userWithChatShadowMuted.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const userWithChatShadowMuted = await member.update({ 'flags.chatShadowMuted': true });
+ const message = await userWithChatShadowMuted.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
expect(message.message.flagCount).to.eql(CHAT_FLAG_FROM_SHADOW_MUTE);
@@ -185,9 +186,9 @@ describe('POST /chat', () => {
});
const userWithChatShadowMuted = members[0];
- await userWithChatShadowMuted.update({'flags.chatShadowMuted': true});
+ await userWithChatShadowMuted.update({ 'flags.chatShadowMuted': true });
- const message = await userWithChatShadowMuted.post(`/groups/${group._id}/chat`, { message: testMessage});
+ const message = await userWithChatShadowMuted.post(`/groups/${group._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
expect(message.message.flagCount).to.eql(0);
@@ -204,16 +205,16 @@ describe('POST /chat', () => {
});
const userWithChatShadowMuted = members[0];
- await userWithChatShadowMuted.update({'flags.chatShadowMuted': true});
+ await userWithChatShadowMuted.update({ 'flags.chatShadowMuted': true });
- const message = await userWithChatShadowMuted.post(`/groups/${group._id}/chat`, { message: testMessage});
+ const message = await userWithChatShadowMuted.post(`/groups/${group._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
expect(message.message.flagCount).to.eql(0);
});
it('creates a chat with zero flagCount when non-shadow-muted user sends a message to a public guild', async () => {
- const message = await member.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await member.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
expect(message.message.flagCount).to.eql(0);
});
@@ -221,7 +222,7 @@ describe('POST /chat', () => {
context('banned word', () => {
it('returns an error when chat message contains a banned word in tavern', async () => {
- await expect(user.post('/groups/habitrpg/chat', { message: testBannedWordMessage}))
+ await expect(user.post('/groups/habitrpg/chat', { message: testBannedWordMessage }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -230,7 +231,7 @@ describe('POST /chat', () => {
});
it('returns an error when chat message contains a banned word in a public guild', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'public guild',
type: 'guild',
@@ -239,7 +240,7 @@ describe('POST /chat', () => {
members: 1,
});
- await expect(members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage}))
+ await expect(members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -248,8 +249,8 @@ describe('POST /chat', () => {
});
it('errors when word is part of a phrase', async () => {
- let wordInPhrase = `phrase ${testBannedWordMessage} end`;
- await expect(user.post('/groups/habitrpg/chat', { message: wordInPhrase}))
+ const wordInPhrase = `phrase ${testBannedWordMessage} end`;
+ await expect(user.post('/groups/habitrpg/chat', { message: wordInPhrase }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -258,8 +259,8 @@ describe('POST /chat', () => {
});
it('errors when word is surrounded by non alphabet characters', async () => {
- let wordInPhrase = `_!${testBannedWordMessage}@_`;
- await expect(user.post('/groups/habitrpg/chat', { message: wordInPhrase}))
+ const wordInPhrase = `_!${testBannedWordMessage}@_`;
+ await expect(user.post('/groups/habitrpg/chat', { message: wordInPhrase }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -268,47 +269,51 @@ describe('POST /chat', () => {
});
it('errors when word is typed in mixed case', async () => {
- let substrLength = Math.floor(testBannedWordMessage.length / 2);
- let chatMessage = testBannedWordMessage.substring(0, substrLength).toLowerCase() + testBannedWordMessage.substring(substrLength).toUpperCase();
+ const substrLength = Math.floor(testBannedWordMessage.length / 2);
+ const chatMessage = testBannedWordMessage.substring(0, substrLength).toLowerCase()
+ + testBannedWordMessage.substring(substrLength).toUpperCase();
await expect(user.post('/groups/habitrpg/chat', { message: chatMessage }))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('bannedWordUsed', {swearWordsUsed: chatMessage}),
+ message: t('bannedWordUsed', { swearWordsUsed: chatMessage }),
});
});
it('checks error message has all the banned words used, regardless of case', async () => {
- let testBannedWords = [testBannedWordMessage.toUpperCase(), testBannedWordMessage1.toLowerCase()];
- let chatMessage = `Mixing ${testBannedWords[0]} and ${testBannedWords[1]} is bad for you.`;
- await expect(user.post('/groups/habitrpg/chat', { message: chatMessage}))
+ const testBannedWords = [
+ testBannedWordMessage.toUpperCase(),
+ testBannedWordMessage1.toLowerCase(),
+ ];
+ const chatMessage = `Mixing ${testBannedWords[0]} and ${testBannedWords[1]} is bad for you.`;
+ await expect(user.post('/groups/habitrpg/chat', { message: chatMessage }))
.to.eventually.be.rejected
.and.have.property('message')
.that.includes(testBannedWords.join(', '));
});
it('check all banned words are matched', async () => {
- let message = bannedWords.join(',').replace(/\\/g, '');
- let matches = getMatchesByWordArray(message, bannedWords);
+ const message = bannedWords.join(',').replace(/\\/g, '');
+ const matches = getMatchesByWordArray(message, bannedWords);
expect(matches.length).to.equal(bannedWords.length);
});
it('does not error when bad word is suffix of a word', async () => {
- let wordAsSuffix = `prefix${testBannedWordMessage}`;
- let message = await user.post('/groups/habitrpg/chat', { message: wordAsSuffix});
+ const wordAsSuffix = `prefix${testBannedWordMessage}`;
+ const message = await user.post('/groups/habitrpg/chat', { message: wordAsSuffix });
expect(message.message.id).to.exist;
});
it('does not error when bad word is prefix of a word', async () => {
- let wordAsPrefix = `${testBannedWordMessage}suffix`;
- let message = await user.post('/groups/habitrpg/chat', { message: wordAsPrefix});
+ const wordAsPrefix = `${testBannedWordMessage}suffix`;
+ const message = await user.post('/groups/habitrpg/chat', { message: wordAsPrefix });
expect(message.message.id).to.exist;
});
it('does not error when sending a chat message containing a banned word to a party', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'Party',
type: 'party',
@@ -317,13 +322,13 @@ describe('POST /chat', () => {
members: 1,
});
- let message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage});
+ const message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage });
expect(message.message.id).to.exist;
});
it('does not error when sending a chat message containing a banned word to a public guild in which banned words are allowed', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'public guild',
type: 'guild',
@@ -334,13 +339,13 @@ describe('POST /chat', () => {
guildsAllowingBannedWords[group._id] = true;
- let message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage});
+ const message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage });
expect(message.message.id).to.exist;
});
it('does not error when sending a chat message containing a banned word to a private guild', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'private guild',
type: 'guild',
@@ -349,7 +354,7 @@ describe('POST /chat', () => {
members: 1,
});
- let message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage});
+ const message = await members[0].post(`/groups/${group._id}/chat`, { message: testBannedWordMessage });
expect(message.message.id).to.exist;
});
@@ -363,11 +368,11 @@ describe('POST /chat', () => {
afterEach(() => {
sandbox.restore();
- user.update({'flags.chatRevoked': false});
+ user.update({ 'flags.chatRevoked': false });
});
it('errors and revokes privileges when chat message contains a banned slur', async () => {
- await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: testSlurMessage})).to.eventually.be.rejected.and.eql({
+ await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: testSlurMessage })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('bannedSlurUsed'),
@@ -398,7 +403,7 @@ describe('POST /chat', () => {
/* eslint-enable camelcase */
// Chat privileges are revoked
- await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage})).to.eventually.be.rejected.and.eql({
+ await expect(user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage })).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
message: t('chatPrivilegesRevoked'),
@@ -406,7 +411,7 @@ describe('POST /chat', () => {
});
it('does not allow slurs in private groups', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'Party',
type: 'party',
@@ -415,7 +420,7 @@ describe('POST /chat', () => {
members: 1,
});
- await expect(members[0].post(`/groups/${group._id}/chat`, { message: testSlurMessage})).to.eventually.be.rejected.and.eql({
+ await expect(members[0].post(`/groups/${group._id}/chat`, { message: testSlurMessage })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('bannedSlurUsed'),
@@ -446,7 +451,7 @@ describe('POST /chat', () => {
/* eslint-enable camelcase */
// Chat privileges are revoked
- await expect(members[0].post(`/groups/${groupWithChat._id}/chat`, { message: testMessage})).to.eventually.be.rejected.and.eql({
+ await expect(members[0].post(`/groups/${groupWithChat._id}/chat`, { message: testMessage })).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
message: t('chatPrivilegesRevoked'),
@@ -454,8 +459,9 @@ describe('POST /chat', () => {
});
it('errors when slur is typed in mixed case', async () => {
- let substrLength = Math.floor(testSlurMessage1.length / 2);
- let chatMessage = testSlurMessage1.substring(0, substrLength).toLowerCase() + testSlurMessage1.substring(substrLength).toUpperCase();
+ const substrLength = Math.floor(testSlurMessage1.length / 2);
+ const chatMessage = testSlurMessage1.substring(0, substrLength).toLowerCase()
+ + testSlurMessage1.substring(substrLength).toUpperCase();
await expect(user.post('/groups/habitrpg/chat', { message: chatMessage }))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -466,7 +472,7 @@ describe('POST /chat', () => {
});
it('creates a chat', async () => {
- const newMessage = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const newMessage = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
const groupMessages = await user.get(`/groups/${groupWithChat._id}/chat`);
expect(newMessage.message.id).to.exist;
@@ -479,7 +485,7 @@ describe('POST /chat', () => {
THIS PART WON'T BE IN THE MESSAGE (over 3000)
`;
- const newMessage = await user.post(`/groups/${groupWithChat._id}/chat`, { message: veryLongMessage});
+ const newMessage = await user.post(`/groups/${groupWithChat._id}/chat`, { message: veryLongMessage });
const groupMessages = await user.get(`/groups/${groupWithChat._id}/chat`);
expect(newMessage.message.id).to.exist;
@@ -501,7 +507,7 @@ describe('POST /chat', () => {
});
await userWithStyle.sync();
- const message = await userWithStyle.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await userWithStyle.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
expect(message.message.id).to.exist;
expect(message.message.userStyles.items.currentMount).to.eql(userWithStyle.items.currentMount);
@@ -511,7 +517,8 @@ describe('POST /chat', () => {
expect(message.message.userStyles.preferences.skin).to.eql(userWithStyle.preferences.skin);
expect(message.message.userStyles.preferences.shirt).to.eql(userWithStyle.preferences.shirt);
expect(message.message.userStyles.preferences.chair).to.eql(userWithStyle.preferences.chair);
- expect(message.message.userStyles.preferences.background).to.eql(userWithStyle.preferences.background);
+ expect(message.message.userStyles.preferences.background)
+ .to.eql(userWithStyle.preferences.background);
});
it('adds backer info to chat', async () => {
@@ -524,7 +531,7 @@ describe('POST /chat', () => {
backer: backerInfo,
});
- const message = await backer.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
+ const message = await backer.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
const messageBackerInfo = message.message.backer;
expect(messageBackerInfo.npc).to.equal(backerInfo.npc);
@@ -533,8 +540,8 @@ describe('POST /chat', () => {
});
it('sends group chat received webhooks', async () => {
- let userUuid = generateUUID();
- let memberUuid = generateUUID();
+ const userUuid = generateUUID();
+ const memberUuid = generateUUID();
await server.start();
await user.post('/user/webhook', {
@@ -554,16 +561,16 @@ describe('POST /chat', () => {
},
});
- let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
+ const message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
await sleep();
await server.close();
- let userBody = server.getWebhookData(userUuid);
- let memberBody = server.getWebhookData(memberUuid);
+ const userBody = server.getWebhookData(userUuid);
+ const memberBody = server.getWebhookData(memberUuid);
- [userBody, memberBody].forEach((body) => {
+ [userBody, memberBody].forEach(body => {
expect(body.group.id).to.eql(groupWithChat._id);
expect(body.group.name).to.eql(groupWithChat.name);
expect(body.chat).to.eql(message.message);
@@ -572,22 +579,20 @@ describe('POST /chat', () => {
context('chat notifications', () => {
beforeEach(() => {
- member.update({newMessages: {}, notifications: []});
+ member.update({ newMessages: {}, notifications: [] });
});
it('notifies other users of new messages for a guild', async () => {
- let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
- let memberWithNotification = await member.get('/user');
+ const message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
+ const memberWithNotification = await member.get('/user');
expect(message.message.id).to.exist;
expect(memberWithNotification.newMessages[`${groupWithChat._id}`]).to.exist;
- expect(memberWithNotification.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupWithChat._id;
- })).to.exist;
+ expect(memberWithNotification.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupWithChat._id)).to.exist;
});
it('notifies other users of new messages for a party', async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Party',
type: 'party',
@@ -596,36 +601,32 @@ describe('POST /chat', () => {
members: 1,
});
- let message = await groupLeader.post(`/groups/${group._id}/chat`, { message: testMessage });
- let memberWithNotification = await members[0].get('/user');
+ const message = await groupLeader.post(`/groups/${group._id}/chat`, { message: testMessage });
+ const memberWithNotification = await members[0].get('/user');
expect(message.message.id).to.exist;
expect(memberWithNotification.newMessages[`${group._id}`]).to.exist;
- expect(memberWithNotification.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === group._id;
- })).to.exist;
+ expect(memberWithNotification.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === group._id)).to.exist;
});
it('does not notify other users of a new message that is already hidden from shadow-muting', async () => {
- await user.update({'flags.chatShadowMuted': true});
- let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
- let memberWithNotification = await member.get('/user');
+ await user.update({ 'flags.chatShadowMuted': true });
+ const message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
+ const memberWithNotification = await member.get('/user');
- await user.update({'flags.chatShadowMuted': false});
+ await user.update({ 'flags.chatShadowMuted': false });
expect(message.message.id).to.exist;
expect(memberWithNotification.newMessages[`${groupWithChat._id}`]).to.not.exist;
- expect(memberWithNotification.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupWithChat._id;
- })).to.not.exist;
+ expect(memberWithNotification.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupWithChat._id)).to.not.exist;
});
});
context('Spam prevention', () => {
it('Returns an error when the user has been posting too many messages', async () => {
// Post as many messages are needed to reach the spam limit
- for (let i = 0; i < SPAM_MESSAGE_LIMIT; i++) {
- let result = await additionalMember.post(`/groups/${TAVERN_ID}/chat`, { message: testMessage }); // eslint-disable-line no-await-in-loop
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT; i += 1) {
+ const result = await additionalMember.post(`/groups/${TAVERN_ID}/chat`, { message: testMessage }); // eslint-disable-line no-await-in-loop
expect(result.message.id).to.exist;
}
@@ -637,11 +638,11 @@ describe('POST /chat', () => {
});
it('contributor should not receive spam alert', async () => {
- let userSocialite = await member.update({'contributor.level': SPAM_MIN_EXEMPT_CONTRIB_LEVEL});
+ const userSocialite = await member.update({ 'contributor.level': SPAM_MIN_EXEMPT_CONTRIB_LEVEL });
// Post 1 more message than the spam limit to ensure they do not reach the limit
- for (let i = 0; i < SPAM_MESSAGE_LIMIT + 1; i++) {
- let result = await userSocialite.post(`/groups/${TAVERN_ID}/chat`, { message: testMessage }); // eslint-disable-line no-await-in-loop
+ for (let i = 0; i < SPAM_MESSAGE_LIMIT + 1; i += 1) {
+ const result = await userSocialite.post(`/groups/${TAVERN_ID}/chat`, { message: testMessage }); // eslint-disable-line no-await-in-loop
expect(result.message.id).to.exist;
}
});
diff --git a/test/api/v3/integration/chat/POST-chat_seen.test.js b/test/api/v3/integration/chat/POST-chat_seen.test.js
index 6bd3f87b23..f64df56146 100644
--- a/test/api/v3/integration/chat/POST-chat_seen.test.js
+++ b/test/api/v3/integration/chat/POST-chat_seen.test.js
@@ -5,10 +5,11 @@ import {
describe('POST /groups/:id/chat/seen', () => {
context('Guild', () => {
- let guild, guildLeader, guildMember, guildMessage;
+ let guild; let guildLeader; let guildMember; let
+ guildMessage;
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -18,7 +19,7 @@ describe('POST /groups/:id/chat/seen', () => {
guild = group;
guildLeader = groupLeader;
- guildMember = members[0];
+ guildMember = members[0]; // eslint-disable-line prefer-destructuring
guildMessage = await guildLeader.post(`/groups/${guild._id}/chat`, { message: 'Some guild message' });
guildMessage = guildMessage.message;
@@ -32,7 +33,7 @@ describe('POST /groups/:id/chat/seen', () => {
await sleep(1);
- let guildThatHasSeenChat = await guildMember.get('/user');
+ const guildThatHasSeenChat = await guildMember.get('/user');
expect(guildThatHasSeenChat.notifications.length).to.equal(initialNotifications - 1);
expect(guildThatHasSeenChat.newMessages).to.be.empty;
@@ -40,10 +41,11 @@ describe('POST /groups/:id/chat/seen', () => {
});
context('Party', () => {
- let party, partyLeader, partyMember, partyMessage;
+ let party; let partyLeader; let partyMember; let
+ partyMessage;
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
type: 'party',
privacy: 'private',
@@ -53,7 +55,7 @@ describe('POST /groups/:id/chat/seen', () => {
party = group;
partyLeader = groupLeader;
- partyMember = members[0];
+ partyMember = members[0]; // eslint-disable-line prefer-destructuring
partyMessage = await partyLeader.post(`/groups/${party._id}/chat`, { message: 'Some party message' });
partyMessage = partyMessage.message;
@@ -67,7 +69,7 @@ describe('POST /groups/:id/chat/seen', () => {
await sleep(1);
- let partyMemberThatHasSeenChat = await partyMember.get('/user');
+ const partyMemberThatHasSeenChat = await partyMember.get('/user');
expect(partyMemberThatHasSeenChat.notifications.length).to.equal(initialNotifications - 1);
expect(partyMemberThatHasSeenChat.newMessages).to.be.empty;
diff --git a/test/api/v3/integration/chat/POST-groups_id_chat_id_clear_flags.test.js b/test/api/v3/integration/chat/POST-groups_id_chat_id_clear_flags.test.js
index 98ce34d35a..9bbc122244 100644
--- a/test/api/v3/integration/chat/POST-groups_id_chat_id_clear_flags.test.js
+++ b/test/api/v3/integration/chat/POST-groups_id_chat_id_clear_flags.test.js
@@ -1,18 +1,19 @@
+import moment from 'moment';
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
import config from '../../../../../config.json';
-import moment from 'moment';
-import { v4 as generateUUID } from 'uuid';
describe('POST /groups/:id/chat/:id/clearflags', () => {
const USER_AGE_FOR_FLAGGING = 3;
- let groupWithChat, message, author, nonAdmin, admin;
+ let groupWithChat; let message; let author; let nonAdmin; let
+ admin;
before(async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -21,8 +22,8 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
groupWithChat = group;
author = groupLeader;
- nonAdmin = await generateUser({'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate()});
- admin = await generateUser({'contributor.admin': true});
+ nonAdmin = await generateUser({ 'auth.timestamps.created': moment().subtract(USER_AGE_FOR_FLAGGING + 1, 'days').toDate() });
+ admin = await generateUser({ 'contributor.admin': true });
message = await author.post(`/groups/${groupWithChat._id}/chat`, { message: 'Some message' });
message = message.message;
@@ -30,17 +31,15 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
});
context('Single Message', () => {
- it('returns error when non-admin attempts to clear flags', async () => {
- return expect(nonAdmin.post(`/groups/${groupWithChat._id}/chat/${message.id}/clearflags`))
- .to.eventually.be.rejected.and.eql({
- code: 401,
- error: 'NotAuthorized',
- message: t('messageGroupChatAdminClearFlagCount'),
- });
- });
+ it('returns error when non-admin attempts to clear flags', async () => expect(nonAdmin.post(`/groups/${groupWithChat._id}/chat/${message.id}/clearflags`))
+ .to.eventually.be.rejected.and.eql({
+ code: 401,
+ error: 'NotAuthorized',
+ message: t('messageGroupChatAdminClearFlagCount'),
+ }));
it('returns error if message does not exist', async () => {
- let fakeMessageID = generateUUID();
+ const fakeMessageID = generateUUID();
await expect(admin.post(`/groups/${groupWithChat._id}/chat/${fakeMessageID}/clearflags`))
.to.eventually.be.rejected.and.eql({
@@ -52,13 +51,13 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
it('clears flags and leaves old flags on the flag object', async () => {
await admin.post(`/groups/${groupWithChat._id}/chat/${message.id}/clearflags`);
- let messages = await admin.get(`/groups/${groupWithChat._id}/chat`);
+ const messages = await admin.get(`/groups/${groupWithChat._id}/chat`);
expect(messages[0].flagCount).to.eql(0);
expect(messages[0].flags).to.have.property(admin._id, true);
});
it('clears flags in a private group', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
type: 'party',
privacy: 'private',
@@ -82,7 +81,7 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
});
it('can\'t flag a system message', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
type: 'party',
privacy: 'private',
@@ -90,7 +89,7 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
members: 1,
});
- let member = members[0];
+ const member = members[0];
// make member that can use skills
await member.update({
@@ -101,12 +100,12 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
await member.post('/user/class/cast/mpheal');
- let [skillMsg] = await member.get(`/groups/${group.id}/chat`);
+ const [skillMsg] = await member.get(`/groups/${group.id}/chat`);
await expect(member.post(`/groups/${group._id}/chat/${skillMsg.id}/flag`))
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('messageCannotFlagSystemMessages', {communityManagerEmail: config.EMAILS_COMMUNITY_MANAGER_EMAIL}),
+ message: t('messageCannotFlagSystemMessages', { communityManagerEmail: config.EMAILS_COMMUNITY_MANAGER_EMAIL }),
});
// let messages = await members[0].get(`/groups/${group._id}/chat`);
// expect(messages[0].id).to.eql(skillMsg.id);
@@ -115,7 +114,8 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
});
context('admin user, group with multiple messages', () => {
- let message2, message3, message4;
+ let message2; let message3; let
+ message4;
before(async () => {
message2 = await author.post(`/groups/${groupWithChat._id}/chat`, { message: 'Some message 2' });
@@ -133,14 +133,14 @@ describe('POST /groups/:id/chat/:id/clearflags', () => {
it('changes only the message that is flagged', async () => {
await admin.post(`/groups/${groupWithChat._id}/chat/${message.id}/clearflags`);
- let messages = await admin.get(`/groups/${groupWithChat._id}/chat`);
+ const messages = await admin.get(`/groups/${groupWithChat._id}/chat`);
expect(messages).to.have.lengthOf(4);
- let messageThatWasUnflagged = messages[3];
- let messageWith1Flag = messages[2];
- let messageWith2Flag = messages[1];
- let messageWithoutFlags = messages[0];
+ const messageThatWasUnflagged = messages[3];
+ const messageWith1Flag = messages[2];
+ const messageWith2Flag = messages[1];
+ const messageWithoutFlags = messages[0];
expect(messageThatWasUnflagged.flagCount).to.eql(0);
expect(messageThatWasUnflagged.flags).to.have.property(admin._id, true);
diff --git a/test/api/v3/integration/content/GET-content.test.js b/test/api/v3/integration/content/GET-content.test.js
index a9f9ce5ee9..a241058be5 100644
--- a/test/api/v3/integration/content/GET-content.test.js
+++ b/test/api/v3/integration/content/GET-content.test.js
@@ -6,19 +6,19 @@ import i18n from '../../../../../website/common/script/i18n';
describe('GET /content', () => {
it('returns content (and does not require authentication)', async () => {
- let res = await requester().get('/content');
+ const res = await requester().get('/content');
expect(res).to.have.nested.property('backgrounds.backgrounds062014.beach');
expect(res.backgrounds.backgrounds062014.beach.text).to.equal(t('backgroundBeachText'));
});
it('returns content not in English', async () => {
- let res = await requester().get('/content?language=de');
+ const res = await requester().get('/content?language=de');
expect(res).to.have.nested.property('backgrounds.backgrounds062014.beach');
expect(res.backgrounds.backgrounds062014.beach.text).to.equal(i18n.t('backgroundBeachText', 'de'));
});
it('falls back to English if the desired language is not found', async () => {
- let res = await requester().get('/content?language=wrong');
+ const res = await requester().get('/content?language=wrong');
expect(res).to.have.nested.property('backgrounds.backgrounds062014.beach');
expect(res.backgrounds.backgrounds062014.beach.text).to.equal(t('backgroundBeachText'));
});
diff --git a/test/api/v3/integration/coupons/GET-coupons.test.js b/test/api/v3/integration/coupons/GET-coupons.test.js
index 9eecfe681c..24cc230e49 100644
--- a/test/api/v3/integration/coupons/GET-coupons.test.js
+++ b/test/api/v3/integration/coupons/GET-coupons.test.js
@@ -28,9 +28,9 @@ describe('GET /coupons/', () => {
'contributor.sudo': true,
});
- let coupons = await user.post('/coupons/generate/wondercon?count=11');
- let res = await user.get('/coupons');
- let splitRes = res.split('\n');
+ const coupons = await user.post('/coupons/generate/wondercon?count=11');
+ const res = await user.get('/coupons');
+ const splitRes = res.split('\n');
expect(splitRes.length).to.equal(13);
expect(splitRes[0]).to.equal('code,event,date,user');
diff --git a/test/api/v3/integration/coupons/POST-coupons_enter_code.test.js b/test/api/v3/integration/coupons/POST-coupons_enter_code.test.js
index be3f982617..d2b0fdec44 100644
--- a/test/api/v3/integration/coupons/POST-coupons_enter_code.test.js
+++ b/test/api/v3/integration/coupons/POST-coupons_enter_code.test.js
@@ -36,7 +36,7 @@ describe('POST /coupons/enter/:code', () => {
});
it('returns an error if coupon has been used', async () => {
- let [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
+ const [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
await user.post(`/coupons/enter/${coupon._id}`); // use coupon
await expect(user.post(`/coupons/enter/${coupon._id}`)).to.eventually.be.rejected.and.eql({
@@ -47,8 +47,8 @@ describe('POST /coupons/enter/:code', () => {
});
it('should apply the coupon to the user', async () => {
- let [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
- let userRes = await user.post(`/coupons/enter/${coupon._id}`);
+ const [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
+ const userRes = await user.post(`/coupons/enter/${coupon._id}`);
expect(userRes._id).to.equal(user._id);
expect(userRes.items.gear.owned.eyewear_special_wondercon_red).to.be.true;
expect(userRes.items.gear.owned.eyewear_special_wondercon_black).to.be.true;
@@ -57,6 +57,6 @@ describe('POST /coupons/enter/:code', () => {
expect(userRes.items.gear.owned.body_special_wondercon_red).to.be.true;
expect(userRes.items.gear.owned.body_special_wondercon_black).to.be.true;
expect(userRes.items.gear.owned.body_special_wondercon_gold).to.be.true;
- expect(userRes.extra).to.eql({signupEvent: 'wondercon'});
+ expect(userRes.extra).to.eql({ signupEvent: 'wondercon' });
});
});
diff --git a/test/api/v3/integration/coupons/POST-coupons_generate_event.test.js b/test/api/v3/integration/coupons/POST-coupons_generate_event.test.js
index 1fe9af0d7a..591cf1a567 100644
--- a/test/api/v3/integration/coupons/POST-coupons_generate_event.test.js
+++ b/test/api/v3/integration/coupons/POST-coupons_generate_event.test.js
@@ -1,9 +1,9 @@
+import couponCode from 'coupon-code';
import {
generateUser,
translate as t,
resetHabiticaDB,
} from '../../../../helpers/api-integration/v3';
-import couponCode from 'coupon-code';
import apiError from '../../../../../website/server/libs/apiError';
describe('POST /coupons/generate/:event', () => {
@@ -51,7 +51,7 @@ describe('POST /coupons/generate/:event', () => {
'contributor.sudo': true,
});
- let coupons = await user.post('/coupons/generate/wondercon?count=2');
+ const coupons = await user.post('/coupons/generate/wondercon?count=2');
expect(coupons.length).to.equal(2);
expect(coupons[0].event).to.equal('wondercon');
expect(couponCode.validate(coupons[1]._id)).to.not.equal(''); // '' means invalid
diff --git a/test/api/v3/integration/coupons/POST-coupons_validate_code.test.js b/test/api/v3/integration/coupons/POST-coupons_validate_code.test.js
index 52d85c6210..5d6bef2b91 100644
--- a/test/api/v3/integration/coupons/POST-coupons_validate_code.test.js
+++ b/test/api/v3/integration/coupons/POST-coupons_validate_code.test.js
@@ -5,7 +5,7 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('POST /coupons/validate/:code', () => {
- let api = requester();
+ const api = requester();
before(async () => {
await resetHabiticaDB();
@@ -20,17 +20,17 @@ describe('POST /coupons/validate/:code', () => {
});
it('returns true if coupon code is valid', async () => {
- let sudoUser = await generateUser({
+ const sudoUser = await generateUser({
'contributor.sudo': true,
});
- let [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
- let res = await api.post(`/coupons/validate/${coupon._id}`);
- expect(res).to.eql({valid: true});
+ const [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
+ const res = await api.post(`/coupons/validate/${coupon._id}`);
+ expect(res).to.eql({ valid: true });
});
it('returns false if coupon code is valid', async () => {
- let res = await api.post('/coupons/validate/notValid');
- expect(res).to.eql({valid: false});
+ const res = await api.post('/coupons/validate/notValid');
+ expect(res).to.eql({ valid: false });
});
});
diff --git a/test/api/v3/integration/dataexport/GET-export_avatar-memberId.html.test.js b/test/api/v3/integration/dataexport/GET-export_avatar-memberId.html.test.js
index 0b24bb02bd..d75d0ead25 100644
--- a/test/api/v3/integration/dataexport/GET-export_avatar-memberId.html.test.js
+++ b/test/api/v3/integration/dataexport/GET-export_avatar-memberId.html.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
xdescribe('GET /export/avatar-:memberId.html', () => {
let user;
@@ -20,16 +20,16 @@ xdescribe('GET /export/avatar-:memberId.html', () => {
});
it('handles non-existing members', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/export/avatar-${dummyId}.html`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
it('returns an html page', async () => {
- let res = await user.get(`/export/avatar-${user._id}.html`);
+ const res = await user.get(`/export/avatar-${user._id}.html`);
expect(res.substring(0, 100).indexOf('')).to.equal(0);
});
});
diff --git a/test/api/v3/integration/dataexport/GET-export_history.csv.test.js b/test/api/v3/integration/dataexport/GET-export_history.csv.test.js
index 5f49213038..4f6a6c76a2 100644
--- a/test/api/v3/integration/dataexport/GET-export_history.csv.test.js
+++ b/test/api/v3/integration/dataexport/GET-export_history.csv.test.js
@@ -1,26 +1,24 @@
+import moment from 'moment';
import {
generateUser,
} from '../../../../helpers/api-integration/v3';
import {
updateDocument,
} from '../../../../helpers/mongo';
-import moment from 'moment';
describe('GET /export/history.csv', () => {
// TODO disabled because it randomly causes the build to fail
xit('should return a valid CSV file with tasks history data', async () => {
- let user = await generateUser();
+ const user = await generateUser();
let tasks = await user.post('/tasks/user', [
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2'},
- {type: 'todo', text: 'todo 1'},
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2' },
+ { type: 'todo', text: 'todo 1' },
]);
// to handle occasional inconsistency in task creation order
- tasks.sort(function (a, b) {
- return a.text.localeCompare(b.text);
- });
+ tasks.sort((a, b) => a.text.localeCompare(b.text));
// score all the tasks twice
await user.post(`/tasks/${tasks[0]._id}/score/up`);
@@ -35,16 +33,14 @@ describe('GET /export/history.csv', () => {
// adding an history entry to daily 1 manually because cron didn't run yet
await updateDocument('tasks', tasks[0], {
- history: [{value: 3.2, date: Number(new Date())}],
+ history: [{ value: 3.2, date: Number(new Date()) }],
});
// get updated tasks
- tasks = await Promise.all(tasks.map(task => {
- return user.get(`/tasks/${task._id}`);
- }));
+ tasks = await Promise.all(tasks.map(task => user.get(`/tasks/${task._id}`)));
- let res = await user.get('/export/history.csv');
- let splitRes = res.split('\n');
+ const res = await user.get('/export/history.csv');
+ const splitRes = res.split('\n');
expect(splitRes[0]).to.equal('Task Name,Task ID,Task Type,Date,Value');
expect(splitRes[1]).to.equal(`daily 1,${tasks[0]._id},daily,${moment(tasks[0].history[0].date).format('YYYY-MM-DD HH:mm:ss')},${tasks[0].history[0].value}`);
diff --git a/test/api/v3/integration/dataexport/GET-export_inbox.html.test.js b/test/api/v3/integration/dataexport/GET-export_inbox.html.test.js
index 61c4e6b933..b9f9b96fff 100644
--- a/test/api/v3/integration/dataexport/GET-export_inbox.html.test.js
+++ b/test/api/v3/integration/dataexport/GET-export_inbox.html.test.js
@@ -6,7 +6,7 @@ describe('GET /export/inbox.html', () => {
let user;
before(async () => {
- let otherUser = await generateUser({
+ const otherUser = await generateUser({
'profile.name': 'Other User',
});
user = await generateUser({
@@ -30,13 +30,13 @@ describe('GET /export/inbox.html', () => {
});
it('returns an html page', async () => {
- let res = await user.get('/export/inbox.html');
+ const res = await user.get('/export/inbox.html');
expect(res.substring(0, 100).indexOf('')).to.equal(0);
});
it('renders the markdown messages as html', async () => {
- let res = await user.get('/export/inbox.html');
+ const res = await user.get('/export/inbox.html');
expect(res).to.include('img class="habitica-emoji"');
expect(res).to.include('
Hello!
');
@@ -44,11 +44,11 @@ describe('GET /export/inbox.html', () => {
});
it('sorts messages from newest to oldest', async () => {
- let res = await user.get('/export/inbox.html');
+ const res = await user.get('/export/inbox.html');
- let emojiPosition = res.indexOf('img class="habitica-emoji"');
- let headingPosition = res.indexOf('Hello!
');
- let listPosition = res.indexOf('list 1');
+ const emojiPosition = res.indexOf('img class="habitica-emoji"');
+ const headingPosition = res.indexOf('Hello!
');
+ const listPosition = res.indexOf('list 1');
expect(emojiPosition).to.be.greaterThan(headingPosition);
expect(headingPosition).to.be.greaterThan(listPosition);
diff --git a/test/api/v3/integration/dataexport/GET-export_userdata.json.test.js b/test/api/v3/integration/dataexport/GET-export_userdata.json.test.js
index 38fbf6435f..7156c884a4 100644
--- a/test/api/v3/integration/dataexport/GET-export_userdata.json.test.js
+++ b/test/api/v3/integration/dataexport/GET-export_userdata.json.test.js
@@ -4,15 +4,15 @@ import {
describe('GET /export/userdata.json', () => {
it('should return a valid JSON file with user data', async () => {
- let user = await generateUser();
- let tasks = await user.post('/tasks/user', [
- {type: 'habit', text: 'habit 1'},
- {type: 'daily', text: 'daily 1'},
- {type: 'reward', text: 'reward 1'},
- {type: 'todo', text: 'todo 1'},
+ const user = await generateUser();
+ const tasks = await user.post('/tasks/user', [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'reward', text: 'reward 1' },
+ { type: 'todo', text: 'todo 1' },
]);
- let res = await user.get('/export/userdata.json');
+ const res = await user.get('/export/userdata.json');
expect(res._id).to.equal(user._id);
expect(res).to.contain.all.keys(['tasks', 'flags', 'tasksOrder', 'auth']);
expect(res.auth.local).not.to.have.keys(['salt', 'hashed_password']);
diff --git a/test/api/v3/integration/dataexport/GET-export_userdata.xml.test.js b/test/api/v3/integration/dataexport/GET-export_userdata.xml.test.js
index f99b34d869..685f0072f6 100644
--- a/test/api/v3/integration/dataexport/GET-export_userdata.xml.test.js
+++ b/test/api/v3/integration/dataexport/GET-export_userdata.xml.test.js
@@ -1,25 +1,25 @@
+import xml2js from 'xml2js';
+import util from 'util';
import {
generateUser,
} from '../../../../helpers/api-integration/v3';
-import xml2js from 'xml2js';
-import util from 'util';
-let parseStringAsync = util.promisify(xml2js.parseString).bind(xml2js);
+const parseStringAsync = util.promisify(xml2js.parseString).bind(xml2js);
describe('GET /export/userdata.xml', () => {
it('should return a valid XML file with user data', async () => {
- let user = await generateUser();
- let tasks = await user.post('/tasks/user', [
- {type: 'habit', text: 'habit 1'},
- {type: 'daily', text: 'daily 1'},
- {type: 'reward', text: 'reward 1'},
- {type: 'todo', text: 'todo 1'},
+ const user = await generateUser();
+ const tasks = await user.post('/tasks/user', [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'reward', text: 'reward 1' },
+ { type: 'todo', text: 'todo 1' },
// due to how the xml parser works an array is returned only if there's more than one children
// so we create two tasks for each type
- {type: 'habit', text: 'habit 2'},
- {type: 'daily', text: 'daily 2'},
- {type: 'reward', text: 'reward 2'},
- {type: 'todo', text: 'todo 2'},
+ { type: 'habit', text: 'habit 2' },
+ { type: 'daily', text: 'daily 2' },
+ { type: 'reward', text: 'reward 2' },
+ { type: 'todo', text: 'todo 2' },
]);
@@ -27,15 +27,15 @@ describe('GET /export/userdata.xml', () => {
await user.get('/user/toggle-pinned-item/marketGear/gear.flat.shield_rogue_5');
// add a private message
- let receiver = await generateUser();
+ const receiver = await generateUser();
user.post('/members/send-private-message', {
message: 'Your first message, hi!',
toUserId: receiver._id,
});
- let response = await user.get('/export/userdata.xml');
- let {user: res} = await parseStringAsync(response, {explicitArray: false});
+ const response = await user.get('/export/userdata.xml');
+ const { user: res } = await parseStringAsync(response, { explicitArray: false });
expect(res._id).to.equal(user._id);
expect(res).to.contain.all.keys(['tasks', 'flags', 'tasksOrder', 'auth']);
@@ -43,19 +43,19 @@ describe('GET /export/userdata.xml', () => {
expect(res.tasks).to.have.all.keys(['dailys', 'habits', 'todos', 'rewards']);
expect(res.tasks.habits.length).to.equal(2);
- let habitIds = _.map(res.tasks.habits, '_id');
+ const habitIds = _.map(res.tasks.habits, '_id');
expect(habitIds).to.have.deep.members([tasks[0]._id, tasks[4]._id]);
expect(res.tasks.dailys.length).to.equal(2);
- let dailyIds = _.map(res.tasks.dailys, '_id');
+ const dailyIds = _.map(res.tasks.dailys, '_id');
expect(dailyIds).to.have.deep.members([tasks[1]._id, tasks[5]._id]);
expect(res.tasks.rewards.length).to.equal(2);
- let rewardIds = _.map(res.tasks.rewards, '_id');
+ const rewardIds = _.map(res.tasks.rewards, '_id');
expect(rewardIds).to.have.deep.members([tasks[2]._id, tasks[6]._id]);
expect(res.tasks.todos.length).to.equal(3);
- let todoIds = _.map(res.tasks.todos, '_id');
+ const todoIds = _.map(res.tasks.todos, '_id');
expect(todoIds).to.deep.include.members([tasks[3]._id, tasks[7]._id]);
});
});
diff --git a/test/api/v3/integration/debug/POST-debug_addHourglass.test.js b/test/api/v3/integration/debug/POST-debug_addHourglass.test.js
index d528f79a81..b0ad288348 100644
--- a/test/api/v3/integration/debug/POST-debug_addHourglass.test.js
+++ b/test/api/v3/integration/debug/POST-debug_addHourglass.test.js
@@ -17,7 +17,7 @@ describe('POST /debug/add-hourglass', () => {
it('adds Hourglass to the current user', async () => {
await userToGetHourGlass.post('/debug/add-hourglass');
- let userWithHourGlass = await userToGetHourGlass.get('/user');
+ const userWithHourGlass = await userToGetHourGlass.get('/user');
expect(userWithHourGlass.purchased.plan.consecutive.trinkets).to.equal(1);
});
diff --git a/test/api/v3/integration/debug/POST-debug_addTenGems.test.js b/test/api/v3/integration/debug/POST-debug_addTenGems.test.js
index faaa2cbd10..74c39a153f 100644
--- a/test/api/v3/integration/debug/POST-debug_addTenGems.test.js
+++ b/test/api/v3/integration/debug/POST-debug_addTenGems.test.js
@@ -17,7 +17,7 @@ describe('POST /debug/add-ten-gems', () => {
it('adds ten gems to the current user', async () => {
await userToGainTenGems.post('/debug/add-ten-gems');
- let userWithTenGems = await userToGainTenGems.get('/user');
+ const userWithTenGems = await userToGainTenGems.get('/user');
expect(userWithTenGems.balance).to.equal(2.5);
});
diff --git a/test/api/v3/integration/debug/POST-debug_modify-inventory.test.js b/test/api/v3/integration/debug/POST-debug_modify-inventory.test.js
index cadb9e2b18..8b9f6ac10d 100644
--- a/test/api/v3/integration/debug/POST-debug_modify-inventory.test.js
+++ b/test/api/v3/integration/debug/POST-debug_modify-inventory.test.js
@@ -6,7 +6,8 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('POST /debug/modify-inventory', () => {
- let user, originalItems;
+ let user; let
+ originalItems;
before(async () => {
originalItems = {
@@ -43,7 +44,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets equipment', async () => {
- let gear = {
+ const gear = {
weapon_healer_2: true,
weapon_wizard_1: true,
weapon_special_critical: true,
@@ -59,7 +60,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets special spells', async () => {
- let special = {
+ const special = {
shinySeed: 3,
};
@@ -73,7 +74,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets mounts', async () => {
- let mounts = {
+ const mounts = {
'Orca-Base': true,
'Mammoth-Base': true,
};
@@ -88,7 +89,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets eggs', async () => {
- let eggs = {
+ const eggs = {
Gryphon: 3,
Hedgehog: 7,
};
@@ -103,7 +104,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets hatching potions', async () => {
- let hatchingPotions = {
+ const hatchingPotions = {
White: 7,
Spooky: 2,
};
@@ -118,7 +119,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets food', async () => {
- let food = {
+ const food = {
Meat: 5,
Candy_Red: 7,
};
@@ -133,7 +134,7 @@ describe('POST /debug/modify-inventory', () => {
});
it('sets quests', async () => {
- let quests = {
+ const quests = {
whale: 5,
cheetah: 10,
};
diff --git a/test/api/v3/integration/debug/POST-debug_set-cron.test.js b/test/api/v3/integration/debug/POST-debug_set-cron.test.js
index 254bca2d1a..dfcd99c625 100644
--- a/test/api/v3/integration/debug/POST-debug_set-cron.test.js
+++ b/test/api/v3/integration/debug/POST-debug_set-cron.test.js
@@ -15,7 +15,7 @@ describe('POST /debug/set-cron', () => {
});
it('sets last cron', async () => {
- let newCron = new Date(2015, 11, 20);
+ const newCron = new Date(2015, 11, 20);
await user.post('/debug/set-cron', {
lastCron: newCron,
diff --git a/test/api/v3/integration/emails/GET-email-unsubscribe.test.js b/test/api/v3/integration/emails/GET-email-unsubscribe.test.js
index fcd26b7904..e44f809c73 100644
--- a/test/api/v3/integration/emails/GET-email-unsubscribe.test.js
+++ b/test/api/v3/integration/emails/GET-email-unsubscribe.test.js
@@ -1,13 +1,13 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
import { encrypt } from '../../../../../website/server/libs/encryption';
-import { v4 as generateUUID } from 'uuid';
describe('GET /email/unsubscribe', () => {
let user;
- let testEmail = 'test@habitica.com';
+ const testEmail = 'test@habitica.com';
beforeEach(async () => {
user = await generateUser();
@@ -22,7 +22,7 @@ describe('GET /email/unsubscribe', () => {
});
it('return error when user is not found', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
_id: generateUUID(),
}));
@@ -34,34 +34,34 @@ describe('GET /email/unsubscribe', () => {
});
it('unsubscribes a user from email notifications', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
_id: user._id,
email: user.email,
}));
await user.get(`/email/unsubscribe?code=${code}`);
- let unsubscribedUser = await user.get('/user');
+ const unsubscribedUser = await user.get('/user');
expect(unsubscribedUser.preferences.emailNotifications.unsubscribeFromAll).to.be.true;
});
it('unsubscribes an email from notifications', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
email: testEmail,
}));
- let unsubscribedMessage = await user.get(`/email/unsubscribe?code=${code}`);
+ const unsubscribedMessage = await user.get(`/email/unsubscribe?code=${code}`);
expect(unsubscribedMessage).to.equal('Unsubscribed successfully!
You won\'t receive any other email from Habitica.');
});
it('returns okay when email is already unsubscribed', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
email: testEmail,
}));
- let unsubscribedMessage = await user.get(`/email/unsubscribe?code=${code}`);
+ const unsubscribedMessage = await user.get(`/email/unsubscribe?code=${code}`);
expect(unsubscribedMessage).to.equal('Unsubscribed successfully!
You won\'t receive any other email from Habitica.');
});
diff --git a/test/api/v3/integration/groups/GET-group-plans.test.js b/test/api/v3/integration/groups/GET-group-plans.test.js
index a56c01087d..42e82d133d 100644
--- a/test/api/v3/integration/groups/GET-group-plans.test.js
+++ b/test/api/v3/integration/groups/GET-group-plans.test.js
@@ -8,7 +8,7 @@ describe('GET /group-plans', () => {
let groupPlan;
before(async () => {
- user = await generateUser({balance: 4});
+ user = await generateUser({ balance: 4 });
groupPlan = await generateGroup(user,
{
name: 'public guild - is member',
@@ -25,7 +25,7 @@ describe('GET /group-plans', () => {
});
it('returns group plans for the user', async () => {
- let groupPlans = await user.get('/group-plans');
+ const groupPlans = await user.get('/group-plans');
expect(groupPlans[0]._id).to.eql(groupPlan._id);
});
diff --git a/test/api/v3/integration/groups/GET-groups.test.js b/test/api/v3/integration/groups/GET-groups.test.js
index 0baf835a02..5359cc4c85 100644
--- a/test/api/v3/integration/groups/GET-groups.test.js
+++ b/test/api/v3/integration/groups/GET-groups.test.js
@@ -16,7 +16,7 @@ describe('GET /groups', () => {
const NUMBER_OF_USERS_PRIVATE_GUILDS = 1;
const NUMBER_OF_GROUPS_USER_CAN_VIEW = 5;
const GUILD_PER_PAGE = 30;
- let categories = [{
+ const categories = [{
slug: 'newCat',
name: 'New Category',
}];
@@ -26,15 +26,15 @@ describe('GET /groups', () => {
before(async () => {
await resetHabiticaDB();
- let leader = await generateUser({ balance: 10 });
- user = await generateUser({balance: 4});
+ const leader = await generateUser({ balance: 10 });
+ user = await generateUser({ balance: 4 });
- let publicGuildUserIsMemberOf = await generateGroup(leader, {
+ const publicGuildUserIsMemberOf = await generateGroup(leader, {
name: 'public guild - is member',
type: 'guild',
privacy: 'public',
});
- await leader.post(`/groups/${publicGuildUserIsMemberOf._id}/invite`, { uuids: [user._id]});
+ await leader.post(`/groups/${publicGuildUserIsMemberOf._id}/invite`, { uuids: [user._id] });
await user.post(`/groups/${publicGuildUserIsMemberOf._id}/join`);
publicGuildNotMember = await generateGroup(leader, {
@@ -50,7 +50,7 @@ describe('GET /groups', () => {
privacy: 'private',
categories,
});
- await leader.post(`/groups/${privateGuildUserIsMemberOf._id}/invite`, { uuids: [user._id]});
+ await leader.post(`/groups/${privateGuildUserIsMemberOf._id}/invite`, { uuids: [user._id] });
await user.post(`/groups/${privateGuildUserIsMemberOf._id}/join`);
await generateGroup(leader, {
@@ -110,13 +110,13 @@ describe('GET /groups', () => {
describe('filters', () => {
it('returns public guilds filtered by category', async () => {
- let guilds = await user.get(`/groups?type=publicGuilds&categories=${categories[0].slug}`);
+ const guilds = await user.get(`/groups?type=publicGuilds&categories=${categories[0].slug}`);
expect(guilds[0]._id).to.equal(publicGuildNotMember._id);
});
it('returns private guilds filtered by category', async () => {
- let guilds = await user.get(`/groups?type=privateGuilds&categories=${categories[0].slug}`);
+ const guilds = await user.get(`/groups?type=privateGuilds&categories=${categories[0].slug}`);
expect(guilds[0]._id).to.equal(privateGuildUserIsMemberOf._id);
});
@@ -131,7 +131,7 @@ describe('GET /groups', () => {
// @TODO: anyway to set higher memberCount in tests right now?
- let guilds = await user.get('/groups?type=publicGuilds&minMemberCount=3');
+ const guilds = await user.get('/groups?type=publicGuilds&minMemberCount=3');
expect(guilds.length).to.equal(0);
});
@@ -146,7 +146,7 @@ describe('GET /groups', () => {
// @TODO: anyway to set higher memberCount in tests right now?
- let guilds = await user.get('/groups?type=privateGuilds&minMemberCount=3');
+ const guilds = await user.get('/groups?type=privateGuilds&minMemberCount=3');
expect(guilds.length).to.equal(0);
});
@@ -181,26 +181,24 @@ describe('GET /groups', () => {
});
it('returns 30 guilds per page ordered by number of members', async () => {
- await user.update({balance: 9000});
- let groups = await Promise.all(_.times(60, (i) => {
- return generateGroup(user, {
- name: `public guild ${i} - is member`,
- type: 'guild',
- privacy: 'public',
- });
- }));
+ await user.update({ balance: 9000 });
+ const groups = await Promise.all(_.times(60, i => generateGroup(user, {
+ name: `public guild ${i} - is member`,
+ type: 'guild',
+ privacy: 'public',
+ })));
// update group number 32 and not the first to make sure sorting works
- await groups[32].update({name: 'guild with most members', memberCount: 199});
- await groups[33].update({name: 'guild with less members', memberCount: -100});
+ await groups[32].update({ name: 'guild with most members', memberCount: 199 });
+ await groups[33].update({ name: 'guild with less members', memberCount: -100 });
- let page0 = await expect(user.get('/groups?type=publicGuilds&paginate=true'))
+ const page0 = await expect(user.get('/groups?type=publicGuilds&paginate=true'))
.to.eventually.have.a.lengthOf(GUILD_PER_PAGE);
expect(page0[0].name).to.equal('guild with most members');
await expect(user.get('/groups?type=publicGuilds&paginate=true&page=1'))
.to.eventually.have.a.lengthOf(GUILD_PER_PAGE);
- let page2 = await expect(user.get('/groups?type=publicGuilds&paginate=true&page=2'))
+ const page2 = await expect(user.get('/groups?type=publicGuilds&paginate=true&page=2'))
.to.eventually.have.a.lengthOf(1 + 4); // 1 created now, 4 by other tests
expect(page2[4].name).to.equal('guild with less members');
}).timeout(10000);
@@ -208,7 +206,8 @@ describe('GET /groups', () => {
it('returns all the user\'s guilds when guilds passed in as query', async () => {
await expect(user.get('/groups?type=guilds'))
- .to.eventually.have.a.lengthOf(NUMBER_OF_PUBLIC_GUILDS_USER_IS_MEMBER + NUMBER_OF_USERS_PRIVATE_GUILDS);
+ .to.eventually.have.a
+ .lengthOf(NUMBER_OF_PUBLIC_GUILDS_USER_IS_MEMBER + NUMBER_OF_USERS_PRIVATE_GUILDS);
});
it('returns all private guilds user is a part of when privateGuilds passed in as query', async () => {
@@ -222,7 +221,7 @@ describe('GET /groups', () => {
});
it('returns a list of groups user has access to', async () => {
- let group = await generateGroup(user, {
+ const group = await generateGroup(user, {
name: 'c++ coders',
type: 'guild',
privacy: 'public',
diff --git a/test/api/v3/integration/groups/GET-groups_groupId_invites.test.js b/test/api/v3/integration/groups/GET-groups_groupId_invites.test.js
index 832efe66e9..aa2a666bf4 100644
--- a/test/api/v3/integration/groups/GET-groups_groupId_invites.test.js
+++ b/test/api/v3/integration/groups/GET-groups_groupId_invites.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /groups/:groupId/invites', () => {
let user;
@@ -29,8 +29,8 @@ describe('GET /groups/:groupId/invites', () => {
});
it('fails if user doesn\'t have access to the group', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let anotherUser = await generateUser();
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/groups/${group._id}/invites`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -39,17 +39,17 @@ describe('GET /groups/:groupId/invites', () => {
});
it('works when passing party as req.params.groupId', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let invited = await generateUser();
- await user.post(`/groups/${group._id}/invite`, {uuids: [invited._id]});
- let res = await user.get('/groups/party/invites');
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const invited = await generateUser();
+ await user.post(`/groups/${group._id}/invite`, { uuids: [invited._id] });
+ const res = await user.get('/groups/party/invites');
expect(res).to.be.an('array');
expect(res.length).to.equal(1);
expect(res[0]).to.eql({
_id: invited._id,
id: invited._id,
- profile: {name: invited.profile.name},
+ profile: { name: invited.profile.name },
auth: {
local: {
username: invited.auth.local.username,
@@ -62,26 +62,26 @@ describe('GET /groups/:groupId/invites', () => {
});
it('populates only some fields', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let invited = await generateUser();
- await user.post(`/groups/${group._id}/invite`, {uuids: [invited._id]});
- let res = await user.get('/groups/party/invites');
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const invited = await generateUser();
+ await user.post(`/groups/${group._id}/invite`, { uuids: [invited._id] });
+ const res = await user.get('/groups/party/invites');
expect(res[0]).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
expect(res[0].profile).to.have.all.keys(['name']);
});
it('returns only first 30 invites', async () => {
- let leader = await generateUser({balance: 4});
- let group = await generateGroup(leader, {type: 'guild', privacy: 'public', name: generateUUID()});
+ const leader = await generateUser({ balance: 4 });
+ const group = await generateGroup(leader, { type: 'guild', privacy: 'public', name: generateUUID() });
- let invitesToGenerate = [];
- for (let i = 0; i < 31; i++) {
+ const invitesToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
invitesToGenerate.push(generateUser());
}
- let generatedInvites = await Promise.all(invitesToGenerate);
- await leader.post(`/groups/${group._id}/invite`, {uuids: generatedInvites.map(invite => invite._id)});
+ const generatedInvites = await Promise.all(invitesToGenerate);
+ await leader.post(`/groups/${group._id}/invite`, { uuids: generatedInvites.map(invite => invite._id) });
- let res = await leader.get(`/groups/${group._id}/invites`);
+ const res = await leader.get(`/groups/${group._id}/invites`);
expect(res.length).to.equal(30);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -89,25 +89,25 @@ describe('GET /groups/:groupId/invites', () => {
});
}).timeout(10000);
- it('supports using req.query.lastId to get more invites', async function () {
+ it('supports using req.query.lastId to get more invites', async function test () {
this.timeout(30000); // @TODO: times out after 8 seconds
- let leader = await generateUser({balance: 4});
- let group = await generateGroup(leader, {type: 'guild', privacy: 'public', name: generateUUID()});
+ const leader = await generateUser({ balance: 4 });
+ const group = await generateGroup(leader, { type: 'guild', privacy: 'public', name: generateUUID() });
- let invitesToGenerate = [];
- for (let i = 0; i < 32; i++) {
+ const invitesToGenerate = [];
+ for (let i = 0; i < 32; i += 1) {
invitesToGenerate.push(generateUser());
}
- let generatedInvites = await Promise.all(invitesToGenerate); // Group has 32 invites
- let expectedIds = generatedInvites.map(generatedInvite => generatedInvite._id);
- await user.post(`/groups/${group._id}/invite`, {uuids: expectedIds});
+ const generatedInvites = await Promise.all(invitesToGenerate); // Group has 32 invites
+ const expectedIds = generatedInvites.map(generatedInvite => generatedInvite._id);
+ await user.post(`/groups/${group._id}/invite`, { uuids: expectedIds });
- let res = await user.get(`/groups/${group._id}/invites`);
+ const res = await user.get(`/groups/${group._id}/invites`);
expect(res.length).to.equal(30);
- let res2 = await user.get(`/groups/${group._id}/invites?lastId=${res[res.length - 1]._id}`);
+ const res2 = await user.get(`/groups/${group._id}/invites?lastId=${res[res.length - 1]._id}`);
expect(res2.length).to.equal(2);
- let resIds = res.concat(res2).map(invite => invite._id);
+ const resIds = res.concat(res2).map(invite => invite._id);
expect(resIds).to.eql(expectedIds.sort());
});
});
diff --git a/test/api/v3/integration/groups/GET-groups_groupId_members.test.js b/test/api/v3/integration/groups/GET-groups_groupId_members.test.js
index 603b2f64b1..b5e6f70c0f 100644
--- a/test/api/v3/integration/groups/GET-groups_groupId_members.test.js
+++ b/test/api/v3/integration/groups/GET-groups_groupId_members.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import common from '../../../../../website/common';
describe('GET /groups/:groupId/members', () => {
@@ -12,8 +12,8 @@ describe('GET /groups/:groupId/members', () => {
beforeEach(async () => {
user = await generateUser({
balance: 10,
- contributor: {level: 1},
- backer: {tier: 3},
+ contributor: { level: 1 },
+ backer: { tier: 3 },
preferences: {
costume: false,
background: 'volcano',
@@ -38,8 +38,8 @@ describe('GET /groups/:groupId/members', () => {
});
it('fails if user doesn\'t have access to the group', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
- let anotherUser = await generateUser();
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/groups/${group._id}/members`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -48,14 +48,14 @@ describe('GET /groups/:groupId/members', () => {
});
it('works when passing party as req.params.groupId', async () => {
- await generateGroup(user, {type: 'party', name: generateUUID()});
- let res = await user.get('/groups/party/members');
+ await generateGroup(user, { type: 'party', name: generateUUID() });
+ const res = await user.get('/groups/party/members');
expect(res).to.be.an('array');
expect(res.length).to.equal(1);
expect(res[0]).to.eql({
_id: user._id,
id: user._id,
- profile: {name: user.profile.name},
+ profile: { name: user.profile.name },
auth: {
local: {
username: user.auth.local.username,
@@ -68,15 +68,15 @@ describe('GET /groups/:groupId/members', () => {
});
it('populates only some fields', async () => {
- await generateGroup(user, {type: 'party', name: generateUUID()});
- let res = await user.get('/groups/party/members');
+ await generateGroup(user, { type: 'party', name: generateUUID() });
+ const res = await user.get('/groups/party/members');
expect(res[0]).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
expect(res[0].profile).to.have.all.keys(['name']);
});
it('req.query.includeAllPublicFields === true works with guilds', async () => {
- let group = await generateGroup(user, {type: 'guild', name: generateUUID()});
- let [memberRes] = await user.get(`/groups/${group._id}/members?includeAllPublicFields=true`);
+ const group = await generateGroup(user, { type: 'guild', name: generateUUID() });
+ const [memberRes] = await user.get(`/groups/${group._id}/members?includeAllPublicFields=true`);
expect(memberRes).to.have.all.keys([ // works as: object has all and only these keys
'_id', 'id', 'preferences', 'profile', 'stats', 'achievements', 'party',
@@ -96,8 +96,8 @@ describe('GET /groups/:groupId/members', () => {
});
it('populates all public fields if req.query.includeAllPublicFields === true and it is a party', async () => {
- await generateGroup(user, {type: 'party', name: generateUUID()});
- let [memberRes] = await user.get('/groups/party/members?includeAllPublicFields=true');
+ await generateGroup(user, { type: 'party', name: generateUUID() });
+ const [memberRes] = await user.get('/groups/party/members?includeAllPublicFields=true');
expect(memberRes).to.have.all.keys([ // works as: object has all and only these keys
'_id', 'id', 'preferences', 'profile', 'stats', 'achievements', 'party',
@@ -117,15 +117,15 @@ describe('GET /groups/:groupId/members', () => {
});
it('returns only first 30 members', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
- let usersToGenerate = [];
- for (let i = 0; i < 31; i++) {
- usersToGenerate.push(generateUser({party: {_id: group._id}}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
+ usersToGenerate.push(generateUser({ party: { _id: group._id } }));
}
await Promise.all(usersToGenerate);
- let res = await user.get('/groups/party/members');
+ const res = await user.get('/groups/party/members');
expect(res.length).to.equal(30);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -134,15 +134,15 @@ describe('GET /groups/:groupId/members', () => {
});
it('returns only first 30 members even when ?includeAllMembers=true', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
- let usersToGenerate = [];
- for (let i = 0; i < 31; i++) {
- usersToGenerate.push(generateUser({party: {_id: group._id}}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 31; i += 1) {
+ usersToGenerate.push(generateUser({ party: { _id: group._id } }));
}
await Promise.all(usersToGenerate);
- let res = await user.get('/groups/party/members?includeAllMembers=true');
+ const res = await user.get('/groups/party/members?includeAllMembers=true');
expect(res.length).to.equal(30);
res.forEach(member => {
expect(member).to.have.all.keys(['_id', 'auth', 'flags', 'id', 'profile']);
@@ -150,38 +150,39 @@ describe('GET /groups/:groupId/members', () => {
});
});
- it('supports using req.query.lastId to get more members', async function () {
+ it('supports using req.query.lastId to get more members', async function test () {
this.timeout(30000); // @TODO: times out after 8 seconds
- let leader = await generateUser({balance: 4});
- let group = await generateGroup(leader, {type: 'guild', privacy: 'public', name: generateUUID()});
+ const leader = await generateUser({ balance: 4 });
+ const group = await generateGroup(leader, { type: 'guild', privacy: 'public', name: generateUUID() });
- let usersToGenerate = [];
- for (let i = 0; i < 57; i++) {
- usersToGenerate.push(generateUser({guilds: [group._id]}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 57; i += 1) {
+ usersToGenerate.push(generateUser({ guilds: [group._id] }));
}
- let generatedUsers = await Promise.all(usersToGenerate); // Group has 59 members (1 is the leader)
- let expectedIds = [leader._id].concat(generatedUsers.map(generatedUser => generatedUser._id));
+ // Group has 59 members (1 is the leader)
+ const generatedUsers = await Promise.all(usersToGenerate);
+ const expectedIds = [leader._id].concat(generatedUsers.map(generatedUser => generatedUser._id));
- let res = await user.get(`/groups/${group._id}/members`);
+ const res = await user.get(`/groups/${group._id}/members`);
expect(res.length).to.equal(30);
- let res2 = await user.get(`/groups/${group._id}/members?lastId=${res[res.length - 1]._id}`);
+ const res2 = await user.get(`/groups/${group._id}/members?lastId=${res[res.length - 1]._id}`);
expect(res2.length).to.equal(28);
- let resIds = res.concat(res2).map(member => member._id);
+ const resIds = res.concat(res2).map(member => member._id);
expect(resIds).to.eql(expectedIds.sort());
});
it('searches members', async () => {
- let group = await generateGroup(user, {type: 'party', name: generateUUID()});
+ const group = await generateGroup(user, { type: 'party', name: generateUUID() });
- let usersToGenerate = [];
- for (let i = 0; i < 2; i++) {
- usersToGenerate.push(generateUser({party: {_id: group._id}}));
+ const usersToGenerate = [];
+ for (let i = 0; i < 2; i += 1) {
+ usersToGenerate.push(generateUser({ party: { _id: group._id } }));
}
const usersCreated = await Promise.all(usersToGenerate);
const userToSearch = usersCreated[0].profile.name;
- let res = await user.get(`/groups/party/members?search=${userToSearch}`);
+ const res = await user.get(`/groups/party/members?search=${userToSearch}`);
expect(res.length).to.equal(1);
expect(res[0].profile.name).to.equal(userToSearch);
});
diff --git a/test/api/v3/integration/groups/GET-groups_id.test.js b/test/api/v3/integration/groups/GET-groups_id.test.js
index 9b9aba0e6f..3e2f3b8742 100644
--- a/test/api/v3/integration/groups/GET-groups_id.test.js
+++ b/test/api/v3/integration/groups/GET-groups_id.test.js
@@ -1,37 +1,38 @@
-import {
- generateUser,
- createAndPopulateGroup,
- translate as t,
-} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID } from 'uuid';
import {
each,
} from 'lodash';
+import {
+ generateUser,
+ createAndPopulateGroup,
+ translate as t,
+} from '../../../../helpers/api-integration/v3';
describe('GET /groups/:id', () => {
- let typesOfGroups = {};
+ const typesOfGroups = {};
typesOfGroups['public guild'] = { type: 'guild', privacy: 'public' };
typesOfGroups['private guild'] = { type: 'guild', privacy: 'private' };
typesOfGroups.party = { type: 'party', privacy: 'private' };
each(typesOfGroups, (groupDetails, groupType) => {
context(`Member of a ${groupType}`, () => {
- let leader, member, createdGroup;
+ let leader; let member; let
+ createdGroup;
before(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
members: 30,
groupDetails,
});
leader = groupData.groupLeader;
- member = groupData.members[0];
+ member = groupData.members[0]; // eslint-disable-line prefer-destructuring
createdGroup = groupData.group;
});
it('returns the group object', async () => {
- let group = await member.get(`/groups/${createdGroup._id}`);
+ const group = await member.get(`/groups/${createdGroup._id}`);
expect(group._id).to.eql(createdGroup._id);
expect(group.name).to.eql(createdGroup.name);
@@ -40,7 +41,7 @@ describe('GET /groups/:id', () => {
});
it('transforms leader id to leader object', async () => {
- let group = await member.get(`/groups/${createdGroup._id}`);
+ const group = await member.get(`/groups/${createdGroup._id}`);
expect(group.leader._id).to.eql(leader._id);
expect(group.leader.profile.name).to.eql(leader.profile.name);
@@ -49,10 +50,11 @@ describe('GET /groups/:id', () => {
});
context('Non-member of a public guild', () => {
- let nonMember, createdGroup;
+ let nonMember; let
+ createdGroup;
before(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
members: 1,
groupDetails: {
name: 'test guild',
@@ -62,11 +64,11 @@ describe('GET /groups/:id', () => {
});
createdGroup = groupData.group;
- nonMember = await generateUser();
+ nonMember = await generateUser();
});
it('returns the group object for a non-member', async () => {
- let group = await nonMember.get(`/groups/${createdGroup._id}`);
+ const group = await nonMember.get(`/groups/${createdGroup._id}`);
expect(group._id).to.eql(createdGroup._id);
expect(group.name).to.eql(createdGroup.name);
@@ -76,10 +78,11 @@ describe('GET /groups/:id', () => {
});
context('Non-member of a private guild', () => {
- let nonMember, createdGroup;
+ let nonMember; let
+ createdGroup;
before(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
members: 1,
groupDetails: {
name: 'test guild',
@@ -103,10 +106,11 @@ describe('GET /groups/:id', () => {
});
context('Non-member of a party', () => {
- let nonMember, createdGroup;
+ let nonMember; let
+ createdGroup;
before(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
members: 1,
groupDetails: {
name: 'test party',
@@ -130,10 +134,11 @@ describe('GET /groups/:id', () => {
});
context('Member of a party', () => {
- let member, createdGroup;
+ let member; let
+ createdGroup;
before(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
members: 1,
groupDetails: {
name: 'test party',
@@ -143,11 +148,11 @@ describe('GET /groups/:id', () => {
});
createdGroup = groupData.group;
- member = groupData.members[0];
+ member = groupData.members[0]; // eslint-disable-line prefer-destructuring
});
it('returns the user\'s party if an id of "party" is passed in', async () => {
- let group = await member.get('/groups/party');
+ const group = await member.get('/groups/party');
expect(group._id).to.eql(createdGroup._id);
expect(group.name).to.eql(createdGroup.name);
@@ -173,7 +178,7 @@ describe('GET /groups/:id', () => {
});
it('removes non-existant guild from user\'s guild list', async () => {
- let guildId = generateUUID();
+ const guildId = generateUUID();
await user.update({
guilds: [guildId, generateUUID()],
@@ -193,7 +198,7 @@ describe('GET /groups/:id', () => {
});
it('removes non-existant party from user\'s party object', async () => {
- let partyId = generateUUID();
+ const partyId = generateUUID();
await user.update({
party: { _id: partyId },
@@ -215,20 +220,20 @@ describe('GET /groups/:id', () => {
context('Flagged messages', () => {
let group;
- let chat1 = {
+ const chat1 = {
id: 'chat1',
text: 'chat 1',
flags: {},
};
- let chat2 = {
+ const chat2 = {
id: 'chat2',
text: 'chat 2',
flags: {},
flagCount: 0,
};
- let chat3 = {
+ const chat3 = {
id: 'chat3',
text: 'chat 3',
flags: {
@@ -237,7 +242,7 @@ describe('GET /groups/:id', () => {
flagCount: 1,
};
- let chat4 = {
+ const chat4 = {
id: 'chat4',
text: 'chat 4',
flags: {
@@ -247,7 +252,7 @@ describe('GET /groups/:id', () => {
flagCount: 2,
};
- let chat5 = {
+ const chat5 = {
id: 'chat5',
text: 'chat 5',
flags: {
@@ -259,7 +264,7 @@ describe('GET /groups/:id', () => {
};
beforeEach(async () => {
- let groupData = await createAndPopulateGroup({
+ const groupData = await createAndPopulateGroup({
groupDetails: {
name: 'test guild',
type: 'guild',
@@ -287,7 +292,7 @@ describe('GET /groups/:id', () => {
});
it('does not include messages with a flag count of 2 or greater', async () => {
- let fetchedGroup = await nonAdmin.get(`/groups/${group._id}`);
+ const fetchedGroup = await nonAdmin.get(`/groups/${group._id}`);
expect(fetchedGroup.chat).to.have.lengthOf(3);
expect(fetchedGroup.chat[0].id).to.eql(chat1.id);
@@ -296,8 +301,8 @@ describe('GET /groups/:id', () => {
});
it('does not include user ids in flags object', async () => {
- let fetchedGroup = await nonAdmin.get(`/groups/${group._id}`);
- let chatWithOneFlag = fetchedGroup.chat[2];
+ const fetchedGroup = await nonAdmin.get(`/groups/${group._id}`);
+ const chatWithOneFlag = fetchedGroup.chat[2];
expect(chatWithOneFlag.id).to.eql(chat3.id);
expect(chat3.flags).to.eql({ 'user-id': true });
@@ -315,7 +320,7 @@ describe('GET /groups/:id', () => {
});
it('includes all messages', async () => {
- let fetchedGroup = await admin.get(`/groups/${group._id}`);
+ const fetchedGroup = await admin.get(`/groups/${group._id}`);
expect(fetchedGroup.chat).to.have.lengthOf(5);
expect(fetchedGroup.chat[0].id).to.eql(chat1.id);
@@ -326,8 +331,8 @@ describe('GET /groups/:id', () => {
});
it('includes user ids in flags object', async () => {
- let fetchedGroup = await admin.get(`/groups/${group._id}`);
- let chatWithOneFlag = fetchedGroup.chat[2];
+ const fetchedGroup = await admin.get(`/groups/${group._id}`);
+ const chatWithOneFlag = fetchedGroup.chat[2];
expect(chatWithOneFlag.id).to.eql(chat3.id);
expect(chat3.flags).to.eql({ 'user-id': true });
diff --git a/test/api/v3/integration/groups/POST-group_remove_manager.test.js b/test/api/v3/integration/groups/POST-group_remove_manager.test.js
index c07e868009..e8cae4ab29 100644
--- a/test/api/v3/integration/groups/POST-group_remove_manager.test.js
+++ b/test/api/v3/integration/groups/POST-group_remove_manager.test.js
@@ -1,13 +1,14 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /group/:groupId/remove-manager', () => {
- let leader, nonLeader, groupToUpdate;
- let groupName = 'Test Public Guild';
- let groupType = 'guild';
+ let leader; let nonLeader; let
+ groupToUpdate;
+ const groupName = 'Test Public Guild';
+ const groupType = 'guild';
let nonManager;
function findAssignedTask (memberTask) {
@@ -15,7 +16,7 @@ describe('POST /group/:groupId/remove-manager', () => {
}
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: groupName,
type: groupType,
@@ -26,8 +27,8 @@ describe('POST /group/:groupId/remove-manager', () => {
groupToUpdate = group;
leader = groupLeader;
- nonLeader = members[0];
- nonManager = members[1];
+ nonLeader = members[0]; // eslint-disable-line prefer-destructuring
+ nonManager = members[1]; // eslint-disable-line prefer-destructuring
});
it('returns an error when a non group leader tries to add member', async () => {
@@ -55,7 +56,7 @@ describe('POST /group/:groupId/remove-manager', () => {
managerId: nonLeader._id,
});
- let updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/remove-manager`, {
+ const updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/remove-manager`, {
managerId: nonLeader._id,
});
@@ -66,14 +67,14 @@ describe('POST /group/:groupId/remove-manager', () => {
await leader.post(`/groups/${groupToUpdate._id}/add-manager`, {
managerId: nonLeader._id,
});
- let task = await leader.post(`/tasks/group/${groupToUpdate._id}`, {
+ const task = await leader.post(`/tasks/group/${groupToUpdate._id}`, {
text: 'test todo',
type: 'todo',
requiresApproval: true,
});
await nonLeader.post(`/tasks/${task._id}/assign/${nonManager._id}`);
- let memberTasks = await nonManager.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await nonManager.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(nonManager.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -81,7 +82,7 @@ describe('POST /group/:groupId/remove-manager', () => {
message: t('taskApprovalHasBeenRequested'),
});
- let updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/remove-manager`, {
+ const updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/remove-manager`, {
managerId: nonLeader._id,
});
diff --git a/test/api/v3/integration/groups/POST-groups.test.js b/test/api/v3/integration/groups/POST-groups.test.js
index 5fd322a564..934281209f 100644
--- a/test/api/v3/integration/groups/POST-groups.test.js
+++ b/test/api/v3/integration/groups/POST-groups.test.js
@@ -13,7 +13,7 @@ describe('POST /group', () => {
context('All Groups', () => {
it('it returns validation error when type is not provided', async () => {
await expect(
- user.post('/groups', { name: 'Test Group Without Type' })
+ user.post('/groups', { name: 'Test Group Without Type' }),
).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -23,7 +23,7 @@ describe('POST /group', () => {
it('it returns validation error when type is not supported', async () => {
await expect(
- user.post('/groups', { name: 'Group with unsupported type', type: 'foo' })
+ user.post('/groups', { name: 'Group with unsupported type', type: 'foo' }),
).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -32,7 +32,7 @@ describe('POST /group', () => {
});
it('sets the group leader to the user who created the group', async () => {
- let group = await user.post('/groups', {
+ const group = await user.post('/groups', {
name: 'Test Public Guild',
type: 'guild',
});
@@ -80,7 +80,7 @@ describe('POST /group', () => {
user.post('/groups', {
name: 'Test Public Guild',
type: 'guild',
- })
+ }),
).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
@@ -89,13 +89,13 @@ describe('POST /group', () => {
});
it('adds guild to user\'s list of guilds', async () => {
- let guild = await user.post('/groups', {
+ const guild = await user.post('/groups', {
name: 'some guild',
type: 'guild',
privacy: 'public',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.guilds).to.include(guild._id);
});
@@ -107,18 +107,18 @@ describe('POST /group', () => {
privacy: 'public',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.achievements.joinedGuild).to.eql(true);
});
context('public guild', () => {
it('creates a group', async () => {
- let groupName = 'Test Public Guild';
- let groupType = 'guild';
- let groupPrivacy = 'public';
+ const groupName = 'Test Public Guild';
+ const groupType = 'guild';
+ const groupPrivacy = 'public';
- let publicGuild = await user.post('/groups', {
+ const publicGuild = await user.post('/groups', {
name: groupName,
type: groupType,
privacy: groupPrivacy,
@@ -145,7 +145,7 @@ describe('POST /group', () => {
name: 'Test Public Guild',
type: 'guild',
privacy: 'public',
- })
+ }),
).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
@@ -155,12 +155,12 @@ describe('POST /group', () => {
});
context('private guild', () => {
- let groupName = 'Test Private Guild';
- let groupType = 'guild';
- let groupPrivacy = 'private';
+ const groupName = 'Test Private Guild';
+ const groupType = 'guild';
+ const groupPrivacy = 'private';
it('creates a group', async () => {
- let privateGuild = await user.post('/groups', {
+ const privateGuild = await user.post('/groups', {
name: groupName,
type: groupType,
privacy: groupPrivacy,
@@ -181,7 +181,7 @@ describe('POST /group', () => {
it('creates a private guild when the user has no chat privileges', async () => {
await user.update({ 'flags.chatRevoked': true });
- let privateGuild = await user.post('/groups', {
+ const privateGuild = await user.post('/groups', {
name: groupName,
type: groupType,
privacy: groupPrivacy,
@@ -191,7 +191,7 @@ describe('POST /group', () => {
});
it('deducts gems from user and adds them to guild bank', async () => {
- let privateGuild = await user.post('/groups', {
+ const privateGuild = await user.post('/groups', {
name: groupName,
type: groupType,
privacy: groupPrivacy,
@@ -199,7 +199,7 @@ describe('POST /group', () => {
expect(privateGuild.balance).to.eql(1);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.balance).to.eql(user.balance - 1);
});
@@ -207,11 +207,11 @@ describe('POST /group', () => {
});
context('Parties', () => {
- let partyName = 'Test Party';
- let partyType = 'party';
+ const partyName = 'Test Party';
+ const partyType = 'party';
it('creates a party', async () => {
- let party = await user.post('/groups', {
+ const party = await user.post('/groups', {
name: partyName,
type: partyType,
});
@@ -230,7 +230,7 @@ describe('POST /group', () => {
it('creates a party when the user has no chat privileges', async () => {
await user.update({ 'flags.chatRevoked': true });
- let party = await user.post('/groups', {
+ const party = await user.post('/groups', {
name: partyName,
type: partyType,
});
@@ -241,25 +241,25 @@ describe('POST /group', () => {
it('does not require gems to create a party', async () => {
await user.update({ balance: 0 });
- let party = await user.post('/groups', {
+ const party = await user.post('/groups', {
name: partyName,
type: partyType,
});
expect(party._id).to.exist;
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.balance).to.eql(user.balance);
});
it('sets party id on user object', async () => {
- let party = await user.post('/groups', {
+ const party = await user.post('/groups', {
name: partyName,
type: partyType,
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.party._id).to.eql(party._id);
});
@@ -270,7 +270,7 @@ describe('POST /group', () => {
type: partyType,
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.achievements.partyUp).to.not.eql(true);
});
diff --git a/test/api/v3/integration/groups/POST-groups_groupId_join.test.js b/test/api/v3/integration/groups/POST-groups_groupId_join.test.js
index a3d88d82a4..319e1f1373 100644
--- a/test/api/v3/integration/groups/POST-groups_groupId_join.test.js
+++ b/test/api/v3/integration/groups/POST-groups_groupId_join.test.js
@@ -1,16 +1,16 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
createAndPopulateGroup,
checkExistence,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /group/:groupId/join', () => {
const PET_QUEST = 'whale';
it('returns error when groupId is not for a valid group', async () => {
- let joiningUser = await generateUser();
+ const joiningUser = await generateUser();
await expect(joiningUser.post(`/groups/${generateUUID()}/join`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -20,10 +20,11 @@ describe('POST /group/:groupId/join', () => {
});
context('Joining a public guild', () => {
- let user, joiningUser, publicGuild;
+ let user; let joiningUser; let
+ publicGuild;
beforeEach(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -37,7 +38,7 @@ describe('POST /group/:groupId/join', () => {
});
it('allows non-invited users to join public guilds', async () => {
- let res = await joiningUser.post(`/groups/${publicGuild._id}/join`);
+ const res = await joiningUser.post(`/groups/${publicGuild._id}/join`);
await expect(joiningUser.get('/user')).to.eventually.have.property('guilds').to.include(publicGuild._id);
expect(res.leader._id).to.eql(user._id);
@@ -62,7 +63,7 @@ describe('POST /group/:groupId/join', () => {
});
it('increments memberCount when joining guilds', async () => {
- let oldMemberCount = publicGuild.memberCount;
+ const oldMemberCount = publicGuild.memberCount;
await joiningUser.post(`/groups/${publicGuild._id}/join`);
@@ -77,10 +78,11 @@ describe('POST /group/:groupId/join', () => {
});
context('Joining a private guild', () => {
- let user, invitedUser, guild;
+ let user; let invitedUser; let
+ guild;
beforeEach(async () => {
- let { group, groupLeader, invitees } = await createAndPopulateGroup({
+ const { group, groupLeader, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -91,11 +93,11 @@ describe('POST /group/:groupId/join', () => {
guild = group;
user = groupLeader;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when user is not invited to private guild', async () => {
- let userWithoutInvite = await generateUser();
+ const userWithoutInvite = await generateUser();
await expect(userWithoutInvite.post(`/groups/${guild._id}/join`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -116,11 +118,11 @@ describe('POST /group/:groupId/join', () => {
await expect(invitedUser.get('/user'))
.to.eventually.have.nested.property('invitations.guilds')
- .to.not.include({id: guild._id});
+ .to.not.include({ id: guild._id });
});
it('increments memberCount when joining guilds', async () => {
- let oldMemberCount = guild.memberCount;
+ const oldMemberCount = guild.memberCount;
await invitedUser.post(`/groups/${guild._id}/join`);
@@ -144,8 +146,8 @@ describe('POST /group/:groupId/join', () => {
it('notifies inviting user that their invitation was accepted', async () => {
await invitedUser.post(`/groups/${guild._id}/join`);
- let inviter = await user.get('/user');
- let expectedData = {
+ const inviter = await user.get('/user');
+ const expectedData = {
headerText: t('invitationAcceptedHeader'),
bodyText: t('invitationAcceptedBody', {
username: invitedUser.auth.local.username,
@@ -166,10 +168,11 @@ describe('POST /group/:groupId/join', () => {
});
context('Joining a party', () => {
- let user, invitedUser, party;
+ let user; let invitedUser; let
+ party;
beforeEach(async () => {
- let { group, groupLeader, invitees } = await createAndPopulateGroup({
+ const { group, groupLeader, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Party',
type: 'party',
@@ -180,11 +183,11 @@ describe('POST /group/:groupId/join', () => {
party = group;
user = groupLeader;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when user is not invited to party', async () => {
- let userWithoutInvite = await generateUser();
+ const userWithoutInvite = await generateUser();
await expect(userWithoutInvite.post(`/groups/${party._id}/join`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -203,9 +206,9 @@ describe('POST /group/:groupId/join', () => {
it('notifies inviting user that their invitation was accepted', async () => {
await invitedUser.post(`/groups/${party._id}/join`);
- let inviter = await user.get('/user');
+ const inviter = await user.get('/user');
- let expectedData = {
+ const expectedData = {
headerText: t('invitationAcceptedHeader'),
bodyText: t('invitationAcceptedBody', {
username: invitedUser.auth.local.username,
@@ -224,7 +227,7 @@ describe('POST /group/:groupId/join', () => {
});
it('increments memberCount when joining party', async () => {
- let oldMemberCount = party.memberCount;
+ const oldMemberCount = party.memberCount;
await invitedUser.post(`/groups/${party._id}/join`);
@@ -238,7 +241,7 @@ describe('POST /group/:groupId/join', () => {
});
it('increments basilist quest item count to inviter when joining a party', async () => {
- await user.update({'items.quests.basilist': 1 });
+ await user.update({ 'items.quests.basilist': 1 });
await invitedUser.post(`/groups/${party._id}/join`);
@@ -246,8 +249,8 @@ describe('POST /group/:groupId/join', () => {
});
it('deletes previous party where the user was the only member', async () => {
- let userToInvite = await generateUser();
- let oldParty = await userToInvite.post('/groups', { // add user to a party
+ const userToInvite = await generateUser();
+ const oldParty = await userToInvite.post('/groups', { // add user to a party
name: 'Another Test Party',
type: 'party',
});
@@ -263,8 +266,8 @@ describe('POST /group/:groupId/join', () => {
});
it('does not allow user to leave a party if a quest was active and they were the only member', async () => {
- let userToInvite = await generateUser();
- let oldParty = await userToInvite.post('/groups', { // add user to a party
+ const userToInvite = await generateUser();
+ const oldParty = await userToInvite.post('/groups', { // add user to a party
name: 'Another Test Party',
type: 'party',
});
@@ -305,7 +308,8 @@ describe('POST /group/:groupId/join', () => {
});
context('Party incentive achievements', () => {
- let leader, member, party;
+ let leader; let member; let
+ party;
beforeEach(async () => {
leader = await generateUser();
@@ -337,8 +341,8 @@ describe('POST /group/:groupId/join', () => {
});
it('awards Party On achievement to party of size 4', async () => {
- let addlMemberOne = await generateUser();
- let addlMemberTwo = await generateUser();
+ const addlMemberOne = await generateUser();
+ const addlMemberTwo = await generateUser();
await leader.post(`/groups/${party._id}/invite`, {
uuids: [addlMemberOne._id, addlMemberTwo._id],
});
diff --git a/test/api/v3/integration/groups/POST-groups_groupId_leave.js b/test/api/v3/integration/groups/POST-groups_groupId_leave.js
index f8636662da..70d60cc3d0 100644
--- a/test/api/v3/integration/groups/POST-groups_groupId_leave.js
+++ b/test/api/v3/integration/groups/POST-groups_groupId_leave.js
@@ -1,3 +1,7 @@
+import { v4 as generateUUID } from 'uuid';
+import {
+ each,
+} from 'lodash';
import {
generateChallenge,
checkExistence,
@@ -6,15 +10,11 @@ import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import {
- each,
-} from 'lodash';
import { model as User } from '../../../../../website/server/models/user';
import payments from '../../../../../website/server/libs/payments/payments';
describe('POST /groups/:groupId/leave', () => {
- let typesOfGroups = {
+ const typesOfGroups = {
'public guild': { type: 'guild', privacy: 'public' },
'private guild': { type: 'guild', privacy: 'private' },
party: { type: 'party', privacy: 'private' },
@@ -28,19 +28,19 @@ describe('POST /groups/:groupId/leave', () => {
let memberCount;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails,
members: 1,
});
groupToLeave = group;
leader = groupLeader;
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
memberCount = group.memberCount;
});
it('prevents non members from leaving', async () => {
- let user = await generateUser();
+ const user = await generateUser();
await expect(user.post(`/groups/${groupToLeave._id}/leave`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -51,7 +51,7 @@ describe('POST /groups/:groupId/leave', () => {
it(`lets user leave a ${groupType}`, async () => {
await member.post(`/groups/${groupToLeave._id}/leave`);
- let userThatLeftGroup = await member.get('/user');
+ const userThatLeftGroup = await member.get('/user');
expect(userThatLeftGroup.guilds).to.be.empty;
expect(userThatLeftGroup.party._id).to.not.exist;
@@ -74,17 +74,13 @@ describe('POST /groups/:groupId/leave', () => {
await leader.sync();
- expect(leader.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupToLeave._id;
- })).to.exist;
+ expect(leader.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupToLeave._id)).to.exist;
expect(leader.newMessages[groupToLeave._id]).to.not.be.empty;
await leader.post(`/groups/${groupToLeave._id}/leave`);
await leader.sync();
- expect(leader.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupToLeave._id;
- })).to.not.exist;
+ expect(leader.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === groupToLeave._id)).to.not.exist;
expect(leader.newMessages[groupToLeave._id]).to.be.undefined;
});
@@ -106,7 +102,7 @@ describe('POST /groups/:groupId/leave', () => {
it('removes all challenge tasks when keep parameter is set to remove', async () => {
await leader.post(`/groups/${groupToLeave._id}/leave?keep=remove-all`);
- let userWithoutChallengeTasks = await leader.get('/user');
+ const userWithoutChallengeTasks = await leader.get('/user');
expect(userWithoutChallengeTasks.challenges).to.not.include(challenge._id);
expect(userWithoutChallengeTasks.tasksOrder.habits).to.be.empty;
@@ -115,16 +111,16 @@ describe('POST /groups/:groupId/leave', () => {
it('keeps all challenge tasks when keep parameter is not set', async () => {
await leader.post(`/groups/${groupToLeave._id}/leave`);
- let userWithChallengeTasks = await leader.get('/user');
+ const userWithChallengeTasks = await leader.get('/user');
// @TODO find elegant way to assert against the task existing
expect(userWithChallengeTasks.tasksOrder.habits).to.not.be.empty;
});
it('keeps the user in the challenge when the keepChallenges parameter is set to remain-in-challenges', async () => {
- await leader.post(`/groups/${groupToLeave._id}/leave`, {keepChallenges: 'remain-in-challenges'});
+ await leader.post(`/groups/${groupToLeave._id}/leave`, { keepChallenges: 'remain-in-challenges' });
- let userWithChallengeTasks = await leader.get('/user');
+ const userWithChallengeTasks = await leader.get('/user');
expect(userWithChallengeTasks.challenges).to.include(challenge._id);
});
@@ -132,7 +128,7 @@ describe('POST /groups/:groupId/leave', () => {
it('drops the user in the challenge when the keepChallenges parameter isn\'t set', async () => {
await leader.post(`/groups/${groupToLeave._id}/leave`);
- let userWithChallengeTasks = await leader.get('/user');
+ const userWithChallengeTasks = await leader.get('/user');
expect(userWithChallengeTasks.challenges).to.not.include(challenge._id);
});
@@ -150,7 +146,7 @@ describe('POST /groups/:groupId/leave', () => {
let invitedUser;
beforeEach(async () => {
- let { group, groupLeader, invitees } = await createAndPopulateGroup({
+ const { group, groupLeader, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Private Guild',
type: 'guild',
@@ -160,7 +156,7 @@ describe('POST /groups/:groupId/leave', () => {
privateGuild = group;
leader = groupLeader;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
await leader.post(`/groups/${group._id}/chat`, { message: 'Some message' });
});
@@ -174,7 +170,7 @@ describe('POST /groups/:groupId/leave', () => {
it('removes invitations when the last member leaves', async () => {
await leader.post(`/groups/${privateGuild._id}/leave`);
- let userWithoutInvitation = await invitedUser.get('/user');
+ const userWithoutInvitation = await invitedUser.get('/user');
expect(userWithoutInvitation.invitations.guilds).to.be.empty;
});
@@ -186,7 +182,7 @@ describe('POST /groups/:groupId/leave', () => {
let invitedUser;
beforeEach(async () => {
- let { group, groupLeader, invitees } = await createAndPopulateGroup({
+ const { group, groupLeader, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Public Guild',
type: 'guild',
@@ -197,7 +193,7 @@ describe('POST /groups/:groupId/leave', () => {
publicGuild = group;
leader = groupLeader;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('keeps the group when the last member leaves', async () => {
@@ -209,14 +205,14 @@ describe('POST /groups/:groupId/leave', () => {
it('keeps the invitations when the last member leaves a public guild', async () => {
await leader.post(`/groups/${publicGuild._id}/leave`);
- let userWithoutInvitation = await invitedUser.get('/user');
+ const userWithoutInvitation = await invitedUser.get('/user');
expect(userWithoutInvitation.invitations.guilds).to.not.be.empty;
});
it('deletes non existant guild from user when user tries to leave', async () => {
- let nonExistentGuildId = generateUUID();
- let userWithNonExistentGuild = await generateUser({guilds: [nonExistentGuildId]});
+ const nonExistentGuildId = generateUUID();
+ const userWithNonExistentGuild = await generateUser({ guilds: [nonExistentGuildId] });
expect(userWithNonExistentGuild.guilds).to.contain(nonExistentGuildId);
await expect(userWithNonExistentGuild.post(`/groups/${nonExistentGuildId}/leave`))
@@ -234,7 +230,7 @@ describe('POST /groups/:groupId/leave', () => {
let invitedUser;
beforeEach(async () => {
- let { group, groupLeader, invitees } = await createAndPopulateGroup({
+ const { group, groupLeader, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Party',
type: 'party',
@@ -244,7 +240,7 @@ describe('POST /groups/:groupId/leave', () => {
party = group;
leader = groupLeader;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('removes a group when the last member leaves a party', async () => {
@@ -256,15 +252,15 @@ describe('POST /groups/:groupId/leave', () => {
it('removes invitations when the last member leaves a party', async () => {
await leader.post(`/groups/${party._id}/leave`);
- let userWithoutInvitation = await invitedUser.get('/user');
+ const userWithoutInvitation = await invitedUser.get('/user');
expect(userWithoutInvitation.invitations.parties[0]).to.be.undefined;
});
});
it('deletes non existant party from user when user tries to leave', async () => {
- let nonExistentPartyId = generateUUID();
- let userWithNonExistentParty = await generateUser({'party._id': nonExistentPartyId});
+ const nonExistentPartyId = generateUUID();
+ const userWithNonExistentParty = await generateUser({ 'party._id': nonExistentPartyId });
expect(userWithNonExistentParty.party._id).to.eql(nonExistentPartyId);
await expect(userWithNonExistentParty.post(`/groups/${nonExistentPartyId}/leave`))
@@ -283,17 +279,17 @@ describe('POST /groups/:groupId/leave', () => {
let member;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails,
members: 1,
});
leader = groupLeader;
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
groupWithPlan = group;
- let userWithFreePlan = await User.findById(leader._id).exec();
+ const userWithFreePlan = await User.findById(leader._id).exec();
// Create subscription
- let paymentData = {
+ const paymentData = {
user: userWithFreePlan,
groupId: groupWithPlan._id,
sub: {
@@ -322,7 +318,7 @@ describe('POST /groups/:groupId/leave', () => {
it('preserves the free subscription when leaving a any other group without a plan', async () => {
// Joining a guild without a group plan
- let { group: groupWithNoPlan } = await createAndPopulateGroup({
+ const { group: groupWithNoPlan } = await createAndPopulateGroup({
groupDetails: {
name: 'Group Without Plan',
type: 'guild',
diff --git a/test/api/v3/integration/groups/POST-groups_groupId_reject.test.js b/test/api/v3/integration/groups/POST-groups_groupId_reject.test.js
index 59d8645d01..68fba0e772 100644
--- a/test/api/v3/integration/groups/POST-groups_groupId_reject.test.js
+++ b/test/api/v3/integration/groups/POST-groups_groupId_reject.test.js
@@ -6,10 +6,11 @@ import {
describe('POST /group/:groupId/reject-invite', () => {
context('Rejecting a public guild invite', () => {
- let publicGuild, invitedUser;
+ let publicGuild; let
+ invitedUser;
beforeEach(async () => {
- let {group, invitees} = await createAndPopulateGroup({
+ const { group, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -19,11 +20,11 @@ describe('POST /group/:groupId/reject-invite', () => {
});
publicGuild = group;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when user is not invited', async () => {
- let userWithoutInvite = await generateUser();
+ const userWithoutInvite = await generateUser();
await expect(userWithoutInvite.post(`/groups/${publicGuild._id}/reject-invite`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -37,15 +38,16 @@ describe('POST /group/:groupId/reject-invite', () => {
await expect(invitedUser.get('/user'))
.to.eventually.have.nested.property('invitations.guilds')
- .to.not.include({id: publicGuild._id});
+ .to.not.include({ id: publicGuild._id });
});
});
context('Rejecting a private guild invite', () => {
- let invitedUser, guild;
+ let invitedUser; let
+ guild;
beforeEach(async () => {
- let { group, invitees } = await createAndPopulateGroup({
+ const { group, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -55,11 +57,11 @@ describe('POST /group/:groupId/reject-invite', () => {
});
guild = group;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when user is not invited', async () => {
- let userWithoutInvite = await generateUser();
+ const userWithoutInvite = await generateUser();
await expect(userWithoutInvite.post(`/groups/${guild._id}/reject-invite`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -73,15 +75,16 @@ describe('POST /group/:groupId/reject-invite', () => {
await expect(invitedUser.get('/user'))
.to.eventually.have.nested.property('invitations.guilds')
- .to.not.include({id: guild._id});
+ .to.not.include({ id: guild._id });
});
});
context('Rejecting a party invite', () => {
- let invitedUser, party;
+ let invitedUser; let
+ party;
beforeEach(async () => {
- let { group, invitees } = await createAndPopulateGroup({
+ const { group, invitees } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Party',
type: 'party',
@@ -91,11 +94,11 @@ describe('POST /group/:groupId/reject-invite', () => {
});
party = group;
- invitedUser = invitees[0];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when user is not invited', async () => {
- let userWithoutInvite = await generateUser();
+ const userWithoutInvite = await generateUser();
await expect(userWithoutInvite.post(`/groups/${party._id}/reject-invite`)).to.eventually.be.rejected.and.eql({
code: 401,
diff --git a/test/api/v3/integration/groups/POST-groups_id_removeMember.test.js b/test/api/v3/integration/groups/POST-groups_id_removeMember.test.js
index b29902bc20..43de0a59ce 100644
--- a/test/api/v3/integration/groups/POST-groups_id_removeMember.test.js
+++ b/test/api/v3/integration/groups/POST-groups_id_removeMember.test.js
@@ -15,7 +15,9 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
let adminUser;
beforeEach(async () => {
- let { group, groupLeader, invitees, members } = await createAndPopulateGroup({
+ const {
+ group, groupLeader, invitees, members,
+ } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -27,15 +29,15 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
guild = group;
leader = groupLeader;
- invitedUser = invitees[0];
- member = members[0];
- member2 = members[1];
+ invitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
adminUser = await generateUser({ 'contributor.admin': true });
});
context('All Groups', () => {
it('returns an error when user is not member of the group', async () => {
- let nonMember = await generateUser();
+ const nonMember = await generateUser();
expect(nonMember.post(`/groups/${guild._id}/removeMember/${member._id}`))
.to.eventually.be.rejected.and.eql({
@@ -74,13 +76,13 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
it('can remove other members', async () => {
await leader.post(`/groups/${guild._id}/removeMember/${member._id}`);
- let memberRemoved = await member.get('/user');
+ const memberRemoved = await member.get('/user');
expect(memberRemoved.guilds.indexOf(guild._id)).eql(-1);
});
it('updates memberCount', async () => {
- let oldMemberCount = guild.memberCount;
+ const oldMemberCount = guild.memberCount;
await leader.post(`/groups/${guild._id}/removeMember/${member._id}`);
await expect(leader.get(`/groups/${guild._id}`)).to.eventually.have.property('memberCount', oldMemberCount - 1);
});
@@ -88,14 +90,14 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
it('can remove other invites', async () => {
await leader.post(`/groups/${guild._id}/removeMember/${invitedUser._id}`);
- let invitedUserWithoutInvite = await invitedUser.get('/user');
+ const invitedUserWithoutInvite = await invitedUser.get('/user');
expect(_.findIndex(invitedUserWithoutInvite.invitations.guilds, { id: guild._id })).eql(-1);
});
it('allows an admin to remove other members', async () => {
await adminUser.post(`/groups/${guild._id}/removeMember/${member._id}`);
- let memberRemoved = await member.get('/user');
+ const memberRemoved = await member.get('/user');
expect(memberRemoved.guilds.indexOf(guild._id)).eql(-1);
});
@@ -103,7 +105,7 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
it('allows an admin to remove other invites', async () => {
await adminUser.post(`/groups/${guild._id}/removeMember/${invitedUser._id}`);
- let invitedUserWithoutInvite = await invitedUser.get('/user');
+ const invitedUserWithoutInvite = await invitedUser.get('/user');
expect(_.findIndex(invitedUserWithoutInvite.invitations.guilds, { id: guild._id })).eql(-1);
});
@@ -141,7 +143,9 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
let removedMember;
beforeEach(async () => {
- let { group, groupLeader, invitees, members } = await createAndPopulateGroup({
+ const {
+ group, groupLeader, invitees, members,
+ } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Party',
type: 'party',
@@ -153,9 +157,9 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
party = group;
partyLeader = groupLeader;
- partyInvitedUser = invitees[0];
- partyMember = members[0];
- removedMember = members[1];
+ partyInvitedUser = invitees[0]; // eslint-disable-line prefer-destructuring
+ partyMember = members[0]; // eslint-disable-line prefer-destructuring
+ removedMember = members[1]; // eslint-disable-line prefer-destructuring
sandbox.spy(email, 'sendTxn');
});
@@ -166,13 +170,13 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
it('can remove other members', async () => {
await partyLeader.post(`/groups/${party._id}/removeMember/${partyMember._id}`);
- let memberRemoved = await partyMember.get('/user');
+ const memberRemoved = await partyMember.get('/user');
expect(memberRemoved.party._id).eql(undefined);
});
it('updates memberCount', async () => {
- let oldMemberCount = party.memberCount;
+ const oldMemberCount = party.memberCount;
await partyLeader.post(`/groups/${party._id}/removeMember/${partyMember._id}`);
await expect(partyLeader.get(`/groups/${party._id}`)).to.eventually.have.property('memberCount', oldMemberCount - 1);
});
@@ -182,7 +186,7 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
await partyLeader.post(`/groups/${party._id}/removeMember/${partyInvitedUser._id}`);
- let invitedUserWithoutInvite = await partyInvitedUser.get('/user');
+ const invitedUserWithoutInvite = await partyInvitedUser.get('/user');
expect(invitedUserWithoutInvite.invitations.parties[0]).to.be.undefined;
});
@@ -192,22 +196,18 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
await sleep(0.5);
await removedMember.sync();
- expect(removedMember.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === party._id;
- })).to.exist;
+ expect(removedMember.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === party._id)).to.exist;
expect(removedMember.newMessages[party._id]).to.not.be.empty;
await partyLeader.post(`/groups/${party._id}/removeMember/${removedMember._id}`);
await removedMember.sync();
- expect(removedMember.notifications.find(n => {
- return n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === party._id;
- })).to.not.exist;
+ expect(removedMember.notifications.find(n => n.type === 'NEW_CHAT_MESSAGE' && n.data.group.id === party._id)).to.not.exist;
expect(removedMember.newMessages[party._id]).to.be.undefined;
});
it('removes user from quest when removing user from party after quest starts', async () => {
- let petQuest = 'whale';
+ const petQuest = 'whale';
await partyLeader.update({
[`items.quests.${petQuest}`]: 1,
});
@@ -229,7 +229,7 @@ describe('POST /groups/:groupId/removeMember/:memberId', () => {
});
it('removes user from quest when removing user from party before quest starts', async () => {
- let petQuest = 'whale';
+ const petQuest = 'whale';
await partyLeader.update({
[`items.quests.${petQuest}`]: 1,
});
diff --git a/test/api/v3/integration/groups/POST-groups_invite.test.js b/test/api/v3/integration/groups/POST-groups_invite.test.js
index 2a648e2bb3..f677f038fe 100644
--- a/test/api/v3/integration/groups/POST-groups_invite.test.js
+++ b/test/api/v3/integration/groups/POST-groups_invite.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
+import nconf from 'nconf';
import {
generateUser,
generateGroup,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import nconf from 'nconf';
const INVITES_LIMIT = 100;
const PARTY_LIMIT_MEMBERS = 30;
@@ -13,10 +13,10 @@ const MAX_EMAIL_INVITES_BY_USER = 200;
describe('Post /groups/:groupId/invite', () => {
let inviter;
let group;
- let groupName = 'Test Public Guild';
+ const groupName = 'Test Public Guild';
beforeEach(async () => {
- inviter = await generateUser({balance: 4});
+ inviter = await generateUser({ balance: 4 });
group = await inviter.post('/groups', {
name: groupName,
type: 'guild',
@@ -33,7 +33,7 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithUsernameNotFound', {username: fakeID}),
+ message: t('userWithUsernameNotFound', { username: fakeID }),
});
});
@@ -69,7 +69,10 @@ describe('Post /groups/:groupId/invite', () => {
const userToInvite2 = await generateUser();
await expect(inviter.post(`/groups/${group._id}/invite`, {
- usernames: [userToInvite.auth.local.lowerCaseUsername, userToInvite2.auth.local.lowerCaseUsername],
+ usernames: [
+ userToInvite.auth.local.lowerCaseUsername,
+ userToInvite2.auth.local.lowerCaseUsername,
+ ],
})).to.eventually.deep.equal([
{
id: group._id,
@@ -92,8 +95,8 @@ describe('Post /groups/:groupId/invite', () => {
describe('user id invites', () => {
it('returns an error when inviter has no chat privileges', async () => {
- let inviterMuted = await inviter.update({'flags.chatRevoked': true});
- let userToInvite = await generateUser();
+ const inviterMuted = await inviter.update({ 'flags.chatRevoked': true });
+ const userToInvite = await generateUser();
await expect(inviterMuted.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id],
}))
@@ -105,7 +108,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when invited user is not found', async () => {
- let fakeID = generateUUID();
+ const fakeID = generateUUID();
await expect(inviter.post(`/groups/${group._id}/invite`, {
uuids: [fakeID],
@@ -113,7 +116,7 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: fakeID}),
+ message: t('userWithIDNotFound', { userId: fakeID }),
});
});
@@ -129,10 +132,10 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when uuids is not an array', async () => {
- let fakeID = generateUUID();
+ const fakeID = generateUUID();
await expect(inviter.post(`/groups/${group._id}/invite`, {
- uuids: {fakeID},
+ uuids: { fakeID },
}))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -165,7 +168,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when there are more than INVITES_LIMIT uuids', async () => {
- let uuids = [];
+ const uuids = [];
for (let i = 0; i < 101; i += 1) {
uuids.push(generateUUID());
@@ -177,13 +180,13 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT}),
+ message: t('canOnlyInviteMaxInvites', { maxInvites: INVITES_LIMIT }),
});
});
it('returns error when recipient has blocked the senders', async () => {
- const inviterNoBlocks = await inviter.update({'inbox.blocks': []});
- let userWithBlockedInviter = await generateUser({'inbox.blocks': [inviter._id]});
+ const inviterNoBlocks = await inviter.update({ 'inbox.blocks': [] });
+ const userWithBlockedInviter = await generateUser({ 'inbox.blocks': [inviter._id] });
await expect(inviterNoBlocks.post(`/groups/${group._id}/invite`, {
uuids: [userWithBlockedInviter._id],
}))
@@ -195,7 +198,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('invites a user to a group by uuid', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
await expect(inviter.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id],
@@ -211,8 +214,8 @@ describe('Post /groups/:groupId/invite', () => {
});
it('invites multiple users to a group by uuid', async () => {
- let userToInvite = await generateUser();
- let userToInvite2 = await generateUser();
+ const userToInvite = await generateUser();
+ const userToInvite2 = await generateUser();
await expect(inviter.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id, userToInvite2._id],
@@ -236,8 +239,8 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when inviting multiple users and a user is not found', async () => {
- let userToInvite = await generateUser();
- let fakeID = generateUUID();
+ const userToInvite = await generateUser();
+ const fakeID = generateUUID();
await expect(inviter.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id, fakeID],
@@ -245,16 +248,16 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: fakeID}),
+ message: t('userWithIDNotFound', { userId: fakeID }),
});
});
});
describe('email invites', () => {
- let testInvite = {name: 'test', email: 'test@habitica.com'};
+ const testInvite = { name: 'test', email: 'test@habitica.com' };
it('returns an error when inviter has no chat privileges', async () => {
- let inviterMuted = await inviter.update({'flags.chatRevoked': true});
+ const inviterMuted = await inviter.update({ 'flags.chatRevoked': true });
await expect(inviterMuted.post(`/groups/${group._id}/invite`, {
emails: [testInvite],
inviter: 'inviter name',
@@ -268,7 +271,7 @@ describe('Post /groups/:groupId/invite', () => {
it('returns an error when invite is missing an email', async () => {
await expect(inviter.post(`/groups/${group._id}/invite`, {
- emails: [{name: 'test'}],
+ emails: [{ name: 'test' }],
}))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -279,7 +282,7 @@ describe('Post /groups/:groupId/invite', () => {
it('returns an error when emails is not an array', async () => {
await expect(inviter.post(`/groups/${group._id}/invite`, {
- emails: {testInvite},
+ emails: { testInvite },
}))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -300,7 +303,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when there are more than INVITES_LIMIT emails', async () => {
- let emails = [];
+ const emails = [];
for (let i = 0; i < 101; i += 1) {
emails.push(`${generateUUID()}@habitica.com`);
@@ -312,16 +315,16 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT}),
+ message: t('canOnlyInviteMaxInvites', { maxInvites: INVITES_LIMIT }),
});
});
it('returns an error when a user has sent the max number of email invites', async () => {
- let inviterWithMax = await generateUser({
+ const inviterWithMax = await generateUser({
invitesSent: MAX_EMAIL_INVITES_BY_USER,
balance: 4,
});
- let tmpGroup = await inviterWithMax.post('/groups', {
+ const tmpGroup = await inviterWithMax.post('/groups', {
name: groupName,
type: 'guild',
});
@@ -333,28 +336,28 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('inviteLimitReached', {techAssistanceEmail: nconf.get('EMAILS_TECH_ASSISTANCE_EMAIL')}),
+ message: t('inviteLimitReached', { techAssistanceEmail: nconf.get('EMAILS_TECH_ASSISTANCE_EMAIL') }),
});
});
it('invites a user to a group by email', async () => {
- let res = await inviter.post(`/groups/${group._id}/invite`, {
+ const res = await inviter.post(`/groups/${group._id}/invite`, {
emails: [testInvite],
inviter: 'inviter name',
});
- let updatedUser = await inviter.sync();
+ const updatedUser = await inviter.sync();
expect(res).to.exist;
expect(updatedUser.invitesSent).to.eql(1);
});
it('invites multiple users to a group by email', async () => {
- let res = await inviter.post(`/groups/${group._id}/invite`, {
- emails: [testInvite, {name: 'test2', email: 'test2@habitica.com'}],
+ const res = await inviter.post(`/groups/${group._id}/invite`, {
+ emails: [testInvite, { name: 'test2', email: 'test2@habitica.com' }],
});
- let updatedUser = await inviter.sync();
+ const updatedUser = await inviter.sync();
expect(res).to.exist;
expect(updatedUser.invitesSent).to.eql(2);
@@ -372,8 +375,8 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when there are more than INVITES_LIMIT uuids and emails', async () => {
- let emails = [];
- let uuids = [];
+ const emails = [];
+ const uuids = [];
for (let i = 0; i < 50; i += 1) {
emails.push(`${generateUUID()}@habitica.com`);
@@ -390,35 +393,35 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT}),
+ message: t('canOnlyInviteMaxInvites', { maxInvites: INVITES_LIMIT }),
});
});
it('invites users to a group by uuid and email', async () => {
- let newUser = await generateUser();
- let invite = await inviter.post(`/groups/${group._id}/invite`, {
+ const newUser = await generateUser();
+ const invite = await inviter.post(`/groups/${group._id}/invite`, {
uuids: [newUser._id],
- emails: [{name: 'test', email: 'test@habitica.com'}],
+ emails: [{ name: 'test', email: 'test@habitica.com' }],
});
- let invitedUser = await newUser.get('/user');
+ const invitedUser = await newUser.get('/user');
expect(invitedUser.invitations.guilds[0].id).to.equal(group._id);
expect(invite).to.exist;
});
it('invites marks invite with cancelled plan', async () => {
- let cancelledPlanGroup = await generateGroup(inviter, {
+ const cancelledPlanGroup = await generateGroup(inviter, {
type: 'guild',
name: generateUUID(),
});
await cancelledPlanGroup.createCancelledSubscription();
- let newUser = await generateUser();
- let invite = await inviter.post(`/groups/${cancelledPlanGroup._id}/invite`, {
+ const newUser = await generateUser();
+ const invite = await inviter.post(`/groups/${cancelledPlanGroup._id}/invite`, {
uuids: [newUser._id],
- emails: [{name: 'test', email: 'test@habitica.com'}],
+ emails: [{ name: 'test', email: 'test@habitica.com' }],
});
- let invitedUser = await newUser.get('/user');
+ const invitedUser = await newUser.get('/user');
expect(invitedUser.invitations.guilds[0].id).to.equal(cancelledPlanGroup._id);
expect(invitedUser.invitations.guilds[0].cancelledPlan).to.be.true;
@@ -428,8 +431,8 @@ describe('Post /groups/:groupId/invite', () => {
describe('guild invites', () => {
it('returns an error when inviter has no chat privileges', async () => {
- let inviterMuted = await inviter.update({'flags.chatRevoked': true});
- let userToInvite = await generateUser();
+ const inviterMuted = await inviter.update({ 'flags.chatRevoked': true });
+ const userToInvite = await generateUser();
await expect(inviterMuted.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id],
}))
@@ -441,7 +444,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when invited user is already invited to the group', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
await inviter.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id],
});
@@ -452,12 +455,12 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('userAlreadyInvitedToGroup', { userId: userToInvite._id, username: userToInvite.profile.name}),
+ message: t('userAlreadyInvitedToGroup', { userId: userToInvite._id, username: userToInvite.profile.name }),
});
});
it('returns an error when invited user is already in the group', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
await inviter.post(`/groups/${group._id}/invite`, {
uuids: [userToInvite._id],
});
@@ -469,17 +472,17 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('userAlreadyInGroup', { userId: userToInvite._id, username: userToInvite.profile.name}),
+ message: t('userAlreadyInGroup', { userId: userToInvite._id, username: userToInvite.profile.name }),
});
});
it('allows 30+ members in a guild', async () => {
- let invitesToGenerate = [];
+ const invitesToGenerate = [];
// Generate 30 users to invite (30 + leader = 31 members)
- for (let i = 0; i < PARTY_LIMIT_MEMBERS; i++) {
+ for (let i = 0; i < PARTY_LIMIT_MEMBERS; i += 1) {
invitesToGenerate.push(generateUser());
}
- let generatedInvites = await Promise.all(invitesToGenerate);
+ const generatedInvites = await Promise.all(invitesToGenerate);
// Invite users
expect(await inviter.post(`/groups/${group._id}/invite`, {
uuids: generatedInvites.map(invite => invite._id),
@@ -488,9 +491,9 @@ describe('Post /groups/:groupId/invite', () => {
// @TODO: Add this after we are able to mock the group plan route
xit('returns an error when a non-leader invites to a group plan', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
- let nonGroupLeader = await generateUser();
+ const nonGroupLeader = await generateUser();
await inviter.post(`/groups/${group._id}/invite`, {
uuids: [nonGroupLeader._id],
});
@@ -518,8 +521,8 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when inviter has no chat privileges', async () => {
- let inviterMuted = await inviter.update({'flags.chatRevoked': true});
- let userToInvite = await generateUser();
+ const inviterMuted = await inviter.update({ 'flags.chatRevoked': true });
+ const userToInvite = await generateUser();
await expect(inviterMuted.post(`/groups/${party._id}/invite`, {
uuids: [userToInvite._id],
}))
@@ -531,7 +534,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('returns an error when invited user has a pending invitation to the party', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
await inviter.post(`/groups/${party._id}/invite`, {
uuids: [userToInvite._id],
});
@@ -542,13 +545,13 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('userAlreadyPendingInvitation', { userId: userToInvite._id, username: userToInvite.profile.name}),
+ message: t('userAlreadyPendingInvitation', { userId: userToInvite._id, username: userToInvite.profile.name }),
});
});
it('returns an error when invited user is already in a party of more than 1 member', async () => {
- let userToInvite = await generateUser();
- let userToInvite2 = await generateUser();
+ const userToInvite = await generateUser();
+ const userToInvite2 = await generateUser();
await inviter.post(`/groups/${party._id}/invite`, {
uuids: [userToInvite._id, userToInvite2._id],
});
@@ -561,12 +564,12 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('userAlreadyInAParty', { userId: userToInvite._id, username: userToInvite.profile.name}),
+ message: t('userAlreadyInAParty', { userId: userToInvite._id, username: userToInvite.profile.name }),
});
});
it('allow inviting a user to a party if they are partying solo', async () => {
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
await userToInvite.post('/groups', { // add user to a party
name: 'Another Test Party',
type: 'party',
@@ -580,13 +583,13 @@ describe('Post /groups/:groupId/invite', () => {
it('allow inviting a user to 2 different parties', async () => {
// Create another inviter
- let inviter2 = await generateUser();
+ const inviter2 = await generateUser();
// Create user to invite
- let userToInvite = await generateUser();
+ const userToInvite = await generateUser();
// Create second group
- let party2 = await inviter2.post('/groups', {
+ const party2 = await inviter2.post('/groups', {
name: 'Test Party 2',
type: 'party',
});
@@ -602,7 +605,7 @@ describe('Post /groups/:groupId/invite', () => {
});
// Get updated user
- let invitedUser = await userToInvite.get('/user');
+ const invitedUser = await userToInvite.get('/user');
expect(invitedUser.invitations.parties.length).to.equal(2);
expect(invitedUser.invitations.parties[0].id).to.equal(party._id);
@@ -610,7 +613,7 @@ describe('Post /groups/:groupId/invite', () => {
});
it('allow inviting a user if party id is not associated with a real party', async () => {
- let userToInvite = await generateUser({
+ const userToInvite = await generateUser({
party: { _id: generateUUID() },
});
@@ -621,12 +624,12 @@ describe('Post /groups/:groupId/invite', () => {
});
it('allows 30 members in a party', async () => {
- let invitesToGenerate = [];
+ const invitesToGenerate = [];
// Generate 29 users to invite (29 + leader = 30 members)
- for (let i = 0; i < PARTY_LIMIT_MEMBERS - 1; i++) {
+ for (let i = 0; i < PARTY_LIMIT_MEMBERS - 1; i += 1) {
invitesToGenerate.push(generateUser());
}
- let generatedInvites = await Promise.all(invitesToGenerate);
+ const generatedInvites = await Promise.all(invitesToGenerate);
// Invite users
expect(await inviter.post(`/groups/${party._id}/invite`, {
uuids: generatedInvites.map(invite => invite._id),
@@ -634,12 +637,12 @@ describe('Post /groups/:groupId/invite', () => {
}).timeout(10000);
it('does not allow 30+ members in a party', async () => {
- let invitesToGenerate = [];
+ const invitesToGenerate = [];
// Generate 30 users to invite (30 + leader = 31 members)
- for (let i = 0; i < PARTY_LIMIT_MEMBERS; i++) {
+ for (let i = 0; i < PARTY_LIMIT_MEMBERS; i += 1) {
invitesToGenerate.push(generateUser());
}
- let generatedInvites = await Promise.all(invitesToGenerate);
+ const generatedInvites = await Promise.all(invitesToGenerate);
// Invite users
await expect(inviter.post(`/groups/${party._id}/invite`, {
uuids: generatedInvites.map(invite => invite._id),
@@ -647,7 +650,7 @@ describe('Post /groups/:groupId/invite', () => {
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: t('partyExceedsMembersLimit', {maxMembersParty: PARTY_LIMIT_MEMBERS}),
+ message: t('partyExceedsMembersLimit', { maxMembersParty: PARTY_LIMIT_MEMBERS }),
});
}).timeout(10000);
});
diff --git a/test/api/v3/integration/groups/POST-groups_manager.test.js b/test/api/v3/integration/groups/POST-groups_manager.test.js
index 8730ea8c95..e7b6cad9de 100644
--- a/test/api/v3/integration/groups/POST-groups_manager.test.js
+++ b/test/api/v3/integration/groups/POST-groups_manager.test.js
@@ -5,14 +5,15 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('POST /group/:groupId/add-manager', () => {
- let leader, nonLeader, groupToUpdate;
- let groupName = 'Test Public Guild';
- let groupType = 'guild';
+ let leader; let nonLeader; let
+ groupToUpdate;
+ const groupName = 'Test Public Guild';
+ const groupType = 'guild';
let nonMember;
context('Guilds', () => {
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: groupName,
type: groupType,
@@ -23,7 +24,7 @@ describe('POST /group/:groupId/add-manager', () => {
groupToUpdate = group;
leader = groupLeader;
- nonLeader = members[0];
+ nonLeader = members[0]; // eslint-disable-line prefer-destructuring
nonMember = await generateUser();
});
@@ -48,7 +49,7 @@ describe('POST /group/:groupId/add-manager', () => {
});
it('allows a leader to add managers', async () => {
- let updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/add-manager`, {
+ const updatedGroup = await leader.post(`/groups/${groupToUpdate._id}/add-manager`, {
managerId: nonLeader._id,
});
@@ -57,10 +58,11 @@ describe('POST /group/:groupId/add-manager', () => {
});
context('Party', () => {
- let party, partyLeader, partyNonLeader;
+ let party; let partyLeader; let
+ partyNonLeader;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: groupName,
type: 'party',
@@ -71,11 +73,11 @@ describe('POST /group/:groupId/add-manager', () => {
party = group;
partyLeader = groupLeader;
- partyNonLeader = members[0];
+ partyNonLeader = members[0]; // eslint-disable-line prefer-destructuring
});
it('allows leader of party to add managers', async () => {
- let updatedGroup = await partyLeader.post(`/groups/${party._id}/add-manager`, {
+ const updatedGroup = await partyLeader.post(`/groups/${party._id}/add-manager`, {
managerId: partyNonLeader._id,
});
diff --git a/test/api/v3/integration/groups/PUT-groups.test.js b/test/api/v3/integration/groups/PUT-groups.test.js
index 9dc00cb891..a471bafd1c 100644
--- a/test/api/v3/integration/groups/PUT-groups.test.js
+++ b/test/api/v3/integration/groups/PUT-groups.test.js
@@ -5,13 +5,14 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('PUT /group', () => {
- let leader, nonLeader, groupToUpdate, adminUser;
- let groupName = 'Test Public Guild';
- let groupType = 'guild';
- let groupUpdatedName = 'Test Public Guild Updated';
+ let leader; let nonLeader; let groupToUpdate; let
+ adminUser;
+ const groupName = 'Test Public Guild';
+ const groupType = 'guild';
+ const groupUpdatedName = 'Test Public Guild Updated';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: groupName,
type: groupType,
@@ -22,7 +23,7 @@ describe('PUT /group', () => {
adminUser = await generateUser({ 'contributor.admin': true });
groupToUpdate = group;
leader = groupLeader;
- nonLeader = members[0];
+ nonLeader = members[0]; // eslint-disable-line prefer-destructuring
});
it('returns an error when a user that is not an admin or group leader tries to update', async () => {
@@ -36,7 +37,7 @@ describe('PUT /group', () => {
});
it('updates a group', async () => {
- let updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
+ const updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
name: groupUpdatedName,
});
@@ -46,12 +47,12 @@ describe('PUT /group', () => {
});
it('updates a group categories', async () => {
- let categories = [{
+ const categories = [{
slug: 'newCat',
name: 'New Category',
}];
- let updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
+ const updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
categories,
});
@@ -60,7 +61,7 @@ describe('PUT /group', () => {
});
it('allows an admin to update a guild', async () => {
- let updatedGroup = await adminUser.put(`/groups/${groupToUpdate._id}`, {
+ const updatedGroup = await adminUser.put(`/groups/${groupToUpdate._id}`, {
name: groupUpdatedName,
});
expect(updatedGroup.leader._id).to.eql(leader._id);
@@ -69,7 +70,7 @@ describe('PUT /group', () => {
});
it('allows a leader to change leaders', async () => {
- let updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
+ const updatedGroup = await leader.put(`/groups/${groupToUpdate._id}`, {
name: groupUpdatedName,
leader: nonLeader._id,
});
diff --git a/test/api/v3/integration/hall/GET-hall_heroes.test.js b/test/api/v3/integration/hall/GET-hall_heroes.test.js
index f0fa59ad6b..a8fb9f70ec 100644
--- a/test/api/v3/integration/hall/GET-hall_heroes.test.js
+++ b/test/api/v3/integration/hall/GET-hall_heroes.test.js
@@ -7,15 +7,15 @@ describe('GET /hall/heroes', () => {
it('returns all heroes sorted by -contributor.level and with correct fields', async () => {
await resetHabiticaDB();
- let nonHero = await generateUser();
- let hero1 = await generateUser({
- contributor: {level: 1},
+ const nonHero = await generateUser();
+ const hero1 = await generateUser({
+ contributor: { level: 1 },
});
- let hero2 = await generateUser({
- contributor: {level: 3},
+ const hero2 = await generateUser({
+ contributor: { level: 3 },
});
- let heroes = await nonHero.get('/hall/heroes');
+ const heroes = await nonHero.get('/hall/heroes');
expect(heroes.length).to.equal(2);
expect(heroes[0]._id).to.equal(hero2._id);
expect(heroes[1]._id).to.equal(hero1._id);
diff --git a/test/api/v3/integration/hall/GET-hall_heroes_heroId.test.js b/test/api/v3/integration/hall/GET-hall_heroes_heroId.test.js
index 4b5bab8f0b..c3e78a8f79 100644
--- a/test/api/v3/integration/hall/GET-hall_heroes_heroId.test.js
+++ b/test/api/v3/integration/hall/GET-hall_heroes_heroId.test.js
@@ -1,20 +1,20 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /heroes/:heroId', () => {
let user;
before(async () => {
user = await generateUser({
- contributor: {admin: true},
+ contributor: { admin: true },
});
});
it('requires the caller to be an admin', async () => {
- let nonAdmin = await generateUser();
+ const nonAdmin = await generateUser();
await expect(nonAdmin.get(`/hall/heroes/${user._id}`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -27,24 +27,24 @@ describe('GET /heroes/:heroId', () => {
await expect(user.get('/hall/heroes/invalidUUID')).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: 'invalidUUID'}),
+ message: t('userWithIDNotFound', { userId: 'invalidUUID' }),
});
});
it('handles non-existing heroes', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/hall/heroes/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
it('returns only necessary hero data given user id', async () => {
- let hero = await generateUser({
- contributor: {tier: 23},
+ const hero = await generateUser({
+ contributor: { tier: 23 },
});
- let heroRes = await user.get(`/hall/heroes/${hero._id}`);
+ const heroRes = await user.get(`/hall/heroes/${hero._id}`);
expect(heroRes).to.have.all.keys([ // works as: object has all and only these keys
'_id', 'id', 'balance', 'profile', 'purchased',
@@ -55,10 +55,10 @@ describe('GET /heroes/:heroId', () => {
});
it('returns only necessary hero data given username', async () => {
- let hero = await generateUser({
- contributor: {tier: 23},
+ const hero = await generateUser({
+ contributor: { tier: 23 },
});
- let heroRes = await user.get(`/hall/heroes/${hero.auth.local.username}`);
+ const heroRes = await user.get(`/hall/heroes/${hero.auth.local.username}`);
expect(heroRes).to.have.all.keys([ // works as: object has all and only these keys
'_id', 'id', 'balance', 'profile', 'purchased',
@@ -70,7 +70,7 @@ describe('GET /heroes/:heroId', () => {
it('returns correct hero using search with difference case', async () => {
await generateUser({}, { username: 'TestUpperCaseName123' });
- let heroRes = await user.get('/hall/heroes/TestuPPerCasEName123');
+ const heroRes = await user.get('/hall/heroes/TestuPPerCasEName123');
expect(heroRes.auth.local.username).to.equal('TestUpperCaseName123');
});
});
diff --git a/test/api/v3/integration/hall/GET-hall_patrons.test.js b/test/api/v3/integration/hall/GET-hall_patrons.test.js
index 1e9064ad43..ea58db24c4 100644
--- a/test/api/v3/integration/hall/GET-hall_patrons.test.js
+++ b/test/api/v3/integration/hall/GET-hall_patrons.test.js
@@ -1,9 +1,9 @@
+import { times } from 'lodash';
import {
generateUser,
translate as t,
resetHabiticaDB,
} from '../../../../helpers/api-integration/v3';
-import { times } from 'lodash';
describe('GET /hall/patrons', () => {
let user;
@@ -22,14 +22,14 @@ describe('GET /hall/patrons', () => {
});
it('returns all patrons sorted by -backer.tier and with correct fields', async () => {
- let patron1 = await generateUser({
- backer: {tier: 1},
+ const patron1 = await generateUser({
+ backer: { tier: 1 },
});
- let patron2 = await generateUser({
- backer: {tier: 3},
+ const patron2 = await generateUser({
+ backer: { tier: 3 },
});
- let patrons = await user.get('/hall/patrons');
+ const patrons = await user.get('/hall/patrons');
expect(patrons.length).to.equal(2);
expect(patrons[0]._id).to.equal(patron2._id);
expect(patrons[1]._id).to.equal(patron1._id);
@@ -45,14 +45,12 @@ describe('GET /hall/patrons', () => {
});
it('returns only first 50 patrons per request, more if req.query.page is passed', async () => {
- await Promise.all(times(53, n => {
- return generateUser({backer: {tier: n}});
- }));
+ await Promise.all(times(53, n => generateUser({ backer: { tier: n } })));
- let patrons = await user.get('/hall/patrons');
+ const patrons = await user.get('/hall/patrons');
expect(patrons.length).to.equal(50);
- let morePatrons = await user.get('/hall/patrons?page=1');
+ const morePatrons = await user.get('/hall/patrons?page=1');
expect(morePatrons.length).to.equal(2);
expect(morePatrons[0].backer.tier).to.equal(2);
expect(morePatrons[1].backer.tier).to.equal(1);
diff --git a/test/api/v3/integration/hall/PUT-hall_heores_heroId.test.js b/test/api/v3/integration/hall/PUT-hall_heores_heroId.test.js
index 36e8e27842..db6eaf82ae 100644
--- a/test/api/v3/integration/hall/PUT-hall_heores_heroId.test.js
+++ b/test/api/v3/integration/hall/PUT-hall_heores_heroId.test.js
@@ -1,20 +1,20 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT /heroes/:heroId', () => {
let user;
before(async () => {
user = await generateUser({
- contributor: {admin: true},
+ contributor: { admin: true },
});
});
it('requires the caller to be an admin', async () => {
- let nonAdmin = await generateUser();
+ const nonAdmin = await generateUser();
await expect(nonAdmin.put(`/hall/heroes/${user._id}`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -32,22 +32,22 @@ describe('PUT /heroes/:heroId', () => {
});
it('handles non-existing heroes', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.put(`/hall/heroes/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
it('change contributor level, balance, ads', async () => {
- let hero = await generateUser();
- let prevBlockState = hero.auth.blocked;
- let prevSleepState = hero.preferences.sleep;
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ const hero = await generateUser();
+ const prevBlockState = hero.auth.blocked;
+ const prevSleepState = hero.preferences.sleep;
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
balance: 3,
- contributor: {level: 1},
- purchased: {ads: true},
+ contributor: { level: 1 },
+ purchased: { ads: true },
});
// test response
@@ -74,10 +74,10 @@ describe('PUT /heroes/:heroId', () => {
});
it('block a user', async () => {
- let hero = await generateUser();
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
- auth: {blocked: true},
- preferences: {sleep: true},
+ const hero = await generateUser();
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ auth: { blocked: true },
+ preferences: { sleep: true },
});
// test response values
@@ -89,10 +89,10 @@ describe('PUT /heroes/:heroId', () => {
});
it('unblock a user', async () => {
- let hero = await generateUser();
- let prevSleepState = hero.preferences.sleep;
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
- auth: {blocked: false},
+ const hero = await generateUser();
+ const prevSleepState = hero.preferences.sleep;
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ auth: { blocked: false },
});
// test response values
@@ -104,29 +104,29 @@ describe('PUT /heroes/:heroId', () => {
});
it('updates chatRevoked flag', async () => {
- let hero = await generateUser();
+ const hero = await generateUser();
await user.put(`/hall/heroes/${hero._id}`, {
- flags: {chatRevoked: true},
+ flags: { chatRevoked: true },
});
await hero.sync();
expect(hero.flags.chatRevoked).to.eql(true);
});
it('updates chatShadowMuted flag', async () => {
- let hero = await generateUser();
+ const hero = await generateUser();
await user.put(`/hall/heroes/${hero._id}`, {
- flags: {chatShadowMuted: true},
+ flags: { chatShadowMuted: true },
});
await hero.sync();
expect(hero.flags.chatShadowMuted).to.eql(true);
});
it('updates contributor level', async () => {
- let hero = await generateUser({
- contributor: {level: 5},
+ const hero = await generateUser({
+ contributor: { level: 5 },
});
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
- contributor: {level: 6},
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ contributor: { level: 6 },
});
// test response
@@ -149,11 +149,11 @@ describe('PUT /heroes/:heroId', () => {
});
it('updates contributor data', async () => {
- let hero = await generateUser({
- contributor: {level: 5},
+ const hero = await generateUser({
+ contributor: { level: 5 },
});
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
- contributor: {text: 'Astronaut'},
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ contributor: { text: 'Astronaut' },
});
// test response
@@ -174,8 +174,8 @@ describe('PUT /heroes/:heroId', () => {
});
it('updates items', async () => {
- let hero = await generateUser();
- let heroRes = await user.put(`/hall/heroes/${hero._id}`, {
+ const hero = await generateUser();
+ const heroRes = await user.put(`/hall/heroes/${hero._id}`, {
itemPath: 'items.special.snowball',
itemVal: 5,
});
diff --git a/test/api/v3/integration/inbox/GET-inbox_messages.test.js b/test/api/v3/integration/inbox/GET-inbox_messages.test.js
index 491b444cab..e3436a3cc4 100644
--- a/test/api/v3/integration/inbox/GET-inbox_messages.test.js
+++ b/test/api/v3/integration/inbox/GET-inbox_messages.test.js
@@ -47,7 +47,7 @@ describe('GET /inbox/messages', () => {
it('returns four messages when using page-query ', async () => {
const promises = [];
- for (let i = 0; i < 10; i++) {
+ for (let i = 0; i < 10; i += 1) {
promises.push(user.post('/members/send-private-message', {
toUserId: user.id,
message: 'fourth',
diff --git a/test/api/v3/integration/members/GET-achievements.test.js b/test/api/v3/integration/members/GET-achievements.test.js
index 9f46780b3e..f3d2f73c99 100644
--- a/test/api/v3/integration/members/GET-achievements.test.js
+++ b/test/api/v3/integration/members/GET-achievements.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /members/:memberId/achievements', () => {
let user;
@@ -20,11 +20,11 @@ describe('GET /members/:memberId/achievements', () => {
});
it('returns achievements based on given user', async () => {
- let member = await generateUser({
- contributor: {level: 1},
- backer: {tier: 3},
+ const member = await generateUser({
+ contributor: { level: 1 },
+ backer: { tier: 3 },
});
- let achievementsRes = await user.get(`/members/${member._id}/achievements`);
+ const achievementsRes = await user.get(`/members/${member._id}/achievements`);
expect(achievementsRes.special.achievements.contributor.earned).to.equal(true);
expect(achievementsRes.special.achievements.contributor.value).to.equal(1);
@@ -34,11 +34,11 @@ describe('GET /members/:memberId/achievements', () => {
});
it('handles non-existing members', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/members/${dummyId}/achievements`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
});
diff --git a/test/api/v3/integration/members/GET-members_id.test.js b/test/api/v3/integration/members/GET-members_id.test.js
index f93ea28498..9b58dd61c1 100644
--- a/test/api/v3/integration/members/GET-members_id.test.js
+++ b/test/api/v3/integration/members/GET-members_id.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import common from '../../../../../website/common';
describe('GET /members/:memberId', () => {
@@ -21,15 +21,16 @@ describe('GET /members/:memberId', () => {
});
it('returns a member public data only', async () => {
- let member = await generateUser({ // make sure user has all the fields that can be returned by the getMember call
- contributor: {level: 1},
- backer: {tier: 3},
+ // make sure user has all the fields that can be returned by the getMember call
+ const member = await generateUser({
+ contributor: { level: 1 },
+ backer: { tier: 3 },
preferences: {
costume: false,
background: 'volcano',
},
});
- let memberRes = await user.get(`/members/${member._id}`);
+ const memberRes = await user.get(`/members/${member._id}`);
expect(memberRes).to.have.all.keys([ // works as: object has all and only these keys
'_id', 'id', 'preferences', 'profile', 'stats', 'achievements', 'party',
'backer', 'contributor', 'auth', 'items', 'inbox', 'loginIncentives', 'flags',
@@ -48,11 +49,11 @@ describe('GET /members/:memberId', () => {
});
it('handles non-existing members', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/members/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
});
diff --git a/test/api/v3/integration/members/GET-objections_interaction.test.js b/test/api/v3/integration/members/GET-objections_interaction.test.js
index 5c7a8c0677..c117e2f950 100644
--- a/test/api/v3/integration/members/GET-objections_interaction.test.js
+++ b/test/api/v3/integration/members/GET-objections_interaction.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /members/:toUserId/objections/:interaction', () => {
let user;
@@ -13,7 +13,7 @@ describe('GET /members/:toUserId/objections/:interaction', () => {
it('validates req.params.memberId', async () => {
await expect(
- user.get('/members/invalidUUID/objections/send-private-message')
+ user.get('/members/invalidUUID/objections/send-private-message'),
).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -22,21 +22,21 @@ describe('GET /members/:toUserId/objections/:interaction', () => {
});
it('handles non-existing members', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(
- user.get(`/members/${dummyId}/objections/send-private-message`)
+ user.get(`/members/${dummyId}/objections/send-private-message`),
).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: dummyId}),
+ message: t('userWithIDNotFound', { userId: dummyId }),
});
});
it('handles non-existing interactions', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
await expect(
- user.get(`/members/${receiver._id}/objections/hug-a-whole-forest-of-trees`)
+ user.get(`/members/${receiver._id}/objections/hug-a-whole-forest-of-trees`),
).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -45,18 +45,18 @@ describe('GET /members/:toUserId/objections/:interaction', () => {
});
it('returns an empty array if there are no objections', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
await expect(
- user.get(`/members/${receiver._id}/objections/send-private-message`)
+ user.get(`/members/${receiver._id}/objections/send-private-message`),
).to.eventually.be.fulfilled.and.eql([]);
});
it('returns an array of objections if any exist', async () => {
- let receiver = await generateUser({'inbox.blocks': [user._id]});
+ const receiver = await generateUser({ 'inbox.blocks': [user._id] });
await expect(
- user.get(`/members/${receiver._id}/objections/send-private-message`)
+ user.get(`/members/${receiver._id}/objections/send-private-message`),
).to.eventually.be.fulfilled.and.eql([
t('notAuthorizedToSendMessageToThisUser'),
]);
diff --git a/test/api/v3/integration/members/POST-send_private_message.test.js b/test/api/v3/integration/members/POST-send_private_message.test.js
index 0012e6ce37..78b5d6467c 100644
--- a/test/api/v3/integration/members/POST-send_private_message.test.js
+++ b/test/api/v3/integration/members/POST-send_private_message.test.js
@@ -1,12 +1,12 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /members/send-private-message', () => {
let userToSendMessage;
- let messageToSend = 'Test Private Message';
+ const messageToSend = 'Test Private Message';
beforeEach(async () => {
userToSendMessage = await generateUser();
@@ -43,7 +43,7 @@ describe('POST /members/send-private-message', () => {
});
it('returns error when to user has blocked the sender', async () => {
- let receiver = await generateUser({'inbox.blocks': [userToSendMessage._id]});
+ const receiver = await generateUser({ 'inbox.blocks': [userToSendMessage._id] });
await expect(userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
@@ -56,8 +56,8 @@ describe('POST /members/send-private-message', () => {
});
it('returns error when sender has blocked to user', async () => {
- let receiver = await generateUser();
- let sender = await generateUser({'inbox.blocks': [receiver._id]});
+ const receiver = await generateUser();
+ const sender = await generateUser({ 'inbox.blocks': [receiver._id] });
await expect(sender.post('/members/send-private-message', {
message: messageToSend,
@@ -70,7 +70,7 @@ describe('POST /members/send-private-message', () => {
});
it('returns error when to user has opted out of messaging', async () => {
- let receiver = await generateUser({'inbox.optOut': true});
+ const receiver = await generateUser({ 'inbox.optOut': true });
await expect(userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
@@ -83,8 +83,8 @@ describe('POST /members/send-private-message', () => {
});
it('returns an error when chat privileges are revoked', async () => {
- let userWithChatRevoked = await generateUser({'flags.chatRevoked': true});
- let receiver = await generateUser();
+ const userWithChatRevoked = await generateUser({ 'flags.chatRevoked': true });
+ const receiver = await generateUser();
await expect(userWithChatRevoked.post('/members/send-private-message', {
message: messageToSend,
@@ -97,7 +97,7 @@ describe('POST /members/send-private-message', () => {
});
it('sends a private message to a user', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
// const initialNotifications = receiver.notifications.length;
const response = await userToSendMessage.post('/members/send-private-message', {
@@ -105,16 +105,18 @@ describe('POST /members/send-private-message', () => {
toUserId: receiver._id,
});
- let updatedReceiver = await receiver.get('/user');
- let updatedSender = await userToSendMessage.get('/user');
+ const updatedReceiver = await receiver.get('/user');
+ const updatedSender = await userToSendMessage.get('/user');
- let sendersMessageInReceiversInbox = _.find(updatedReceiver.inbox.messages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === messageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ updatedReceiver.inbox.messages,
+ message => message.uuid === userToSendMessage._id && message.text === messageToSend,
+ );
- let sendersMessageInSendersInbox = _.find(updatedSender.inbox.messages, (message) => {
- return message.uuid === receiver._id && message.text === messageToSend;
- });
+ const sendersMessageInSendersInbox = _.find(
+ updatedSender.inbox.messages,
+ message => message.uuid === receiver._id && message.text === messageToSend,
+ );
expect(response.message.text).to.deep.equal(sendersMessageInSendersInbox.text);
expect(response.message.uuid).to.deep.equal(sendersMessageInSendersInbox.uuid);
@@ -135,20 +137,21 @@ describe('POST /members/send-private-message', () => {
// @TODO waiting for mobile support
xit('creates a notification with an excerpt if the message is too long', async () => {
- let receiver = await generateUser();
- let longerMessageToSend = 'A very long message, that for sure exceeds the limit of 100 chars for the excerpt that we set to 100 chars';
- let messageExcerpt = `${longerMessageToSend.substring(0, 100)}...`;
+ const receiver = await generateUser();
+ const longerMessageToSend = 'A very long message, that for sure exceeds the limit of 100 chars for the excerpt that we set to 100 chars';
+ const messageExcerpt = `${longerMessageToSend.substring(0, 100)}...`;
await userToSendMessage.post('/members/send-private-message', {
message: longerMessageToSend,
toUserId: receiver._id,
});
- let updatedReceiver = await receiver.get('/user');
+ const updatedReceiver = await receiver.get('/user');
- let sendersMessageInReceiversInbox = _.find(updatedReceiver.inbox.messages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === longerMessageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ updatedReceiver.inbox.messages,
+ message => message.uuid === userToSendMessage._id && message.text === longerMessageToSend,
+ );
const notification = updatedReceiver.notifications[updatedReceiver.notifications.length - 1];
@@ -161,7 +164,7 @@ describe('POST /members/send-private-message', () => {
userToSendMessage = await generateUser({
'contributor.admin': 1,
});
- const receiver = await generateUser({'inbox.blocks': [userToSendMessage._id]});
+ const receiver = await generateUser({ 'inbox.blocks': [userToSendMessage._id] });
await userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
@@ -171,13 +174,15 @@ describe('POST /members/send-private-message', () => {
const updatedReceiver = await receiver.get('/user');
const updatedSender = await userToSendMessage.get('/user');
- const sendersMessageInReceiversInbox = _.find(updatedReceiver.inbox.messages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === messageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ updatedReceiver.inbox.messages,
+ message => message.uuid === userToSendMessage._id && message.text === messageToSend,
+ );
- const sendersMessageInSendersInbox = _.find(updatedSender.inbox.messages, (message) => {
- return message.uuid === receiver._id && message.text === messageToSend;
- });
+ const sendersMessageInSendersInbox = _.find(
+ updatedSender.inbox.messages,
+ message => message.uuid === receiver._id && message.text === messageToSend,
+ );
expect(sendersMessageInReceiversInbox).to.exist;
expect(sendersMessageInSendersInbox).to.exist;
@@ -187,7 +192,7 @@ describe('POST /members/send-private-message', () => {
userToSendMessage = await generateUser({
'contributor.admin': 1,
});
- const receiver = await generateUser({'inbox.optOut': true});
+ const receiver = await generateUser({ 'inbox.optOut': true });
await userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
@@ -197,13 +202,15 @@ describe('POST /members/send-private-message', () => {
const updatedReceiver = await receiver.get('/user');
const updatedSender = await userToSendMessage.get('/user');
- const sendersMessageInReceiversInbox = _.find(updatedReceiver.inbox.messages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === messageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ updatedReceiver.inbox.messages,
+ message => message.uuid === userToSendMessage._id && message.text === messageToSend,
+ );
- const sendersMessageInSendersInbox = _.find(updatedSender.inbox.messages, (message) => {
- return message.uuid === receiver._id && message.text === messageToSend;
- });
+ const sendersMessageInSendersInbox = _.find(
+ updatedSender.inbox.messages,
+ message => message.uuid === receiver._id && message.text === messageToSend,
+ );
expect(sendersMessageInReceiversInbox).to.exist;
expect(sendersMessageInSendersInbox).to.exist;
diff --git a/test/api/v3/integration/members/POST-transfer_gems.test.js b/test/api/v3/integration/members/POST-transfer_gems.test.js
index 0b5b0cfa93..88c6446097 100644
--- a/test/api/v3/integration/members/POST-transfer_gems.test.js
+++ b/test/api/v3/integration/members/POST-transfer_gems.test.js
@@ -1,13 +1,11 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
function findMessage (messages, receiverId) {
- let message = _.find(messages, (inboxMessage) => {
- return inboxMessage.uuid === receiverId;
- });
+ const message = _.find(messages, inboxMessage => inboxMessage.uuid === receiverId);
return message;
}
@@ -15,11 +13,11 @@ function findMessage (messages, receiverId) {
describe('POST /members/transfer-gems', () => {
let userToSendMessage;
let receiver;
- let message = 'Test Private Message';
- let gemAmount = 20;
+ const message = 'Test Private Message';
+ const gemAmount = 20;
beforeEach(async () => {
- userToSendMessage = await generateUser({balance: 5});
+ userToSendMessage = await generateUser({ balance: 5 });
receiver = await generateUser();
});
@@ -68,7 +66,7 @@ describe('POST /members/transfer-gems', () => {
});
it('returns error when recipient has blocked the sender', async () => {
- let receiverWhoBlocksUser = await generateUser({'inbox.blocks': [userToSendMessage._id]});
+ const receiverWhoBlocksUser = await generateUser({ 'inbox.blocks': [userToSendMessage._id] });
await expect(userToSendMessage.post('/members/transfer-gems', {
message,
@@ -82,7 +80,7 @@ describe('POST /members/transfer-gems', () => {
});
it('returns error when sender has blocked recipient', async () => {
- let sender = await generateUser({'inbox.blocks': [receiver._id]});
+ const sender = await generateUser({ 'inbox.blocks': [receiver._id] });
await expect(sender.post('/members/transfer-gems', {
message,
@@ -96,7 +94,7 @@ describe('POST /members/transfer-gems', () => {
});
it('returns an error when chat privileges are revoked', async () => {
- let userWithChatRevoked = await generateUser({'flags.chatRevoked': true});
+ const userWithChatRevoked = await generateUser({ 'flags.chatRevoked': true });
await expect(userWithChatRevoked.post('/members/transfer-gems', {
message,
@@ -110,7 +108,7 @@ describe('POST /members/transfer-gems', () => {
});
it('works when only the recipient\'s chat privileges are revoked', async () => {
- let receiverWithChatRevoked = await generateUser({'flags.chatRevoked': true});
+ const receiverWithChatRevoked = await generateUser({ 'flags.chatRevoked': true });
await expect(userToSendMessage.post('/members/transfer-gems', {
message,
@@ -118,8 +116,8 @@ describe('POST /members/transfer-gems', () => {
toUserId: receiverWithChatRevoked._id,
})).to.eventually.be.fulfilled;
- let updatedReceiver = await receiverWithChatRevoked.get('/user');
- let updatedSender = await userToSendMessage.get('/user');
+ const updatedReceiver = await receiverWithChatRevoked.get('/user');
+ const updatedSender = await userToSendMessage.get('/user');
expect(updatedReceiver.balance).to.equal(gemAmount / 4);
expect(updatedSender.balance).to.equal(0);
@@ -179,18 +177,20 @@ describe('POST /members/transfer-gems', () => {
toUserId: receiver._id,
});
- let updatedReceiver = await receiver.get('/user');
- let updatedSender = await userToSendMessage.get('/user');
+ const updatedReceiver = await receiver.get('/user');
+ const updatedSender = await userToSendMessage.get('/user');
- let sendersMessageInReceiversInbox = findMessage(updatedReceiver.inbox.messages, userToSendMessage._id);
- let sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
+ const sendersMessageInReceiversInbox = findMessage(
+ updatedReceiver.inbox.messages, userToSendMessage._id,
+ );
+ const sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
let messageSentContent = t('privateMessageGiftGemsMessage', {
receiverName: receiver.profile.name,
senderName: userToSendMessage.profile.name,
gemAmount,
});
- messageSentContent = `\`${messageSentContent}\` `;
+ messageSentContent = `\`${messageSentContent}\` `;
messageSentContent += message;
expect(sendersMessageInReceiversInbox).to.exist;
@@ -208,18 +208,20 @@ describe('POST /members/transfer-gems', () => {
toUserId: receiver._id,
});
- let updatedReceiver = await receiver.get('/user');
- let updatedSender = await userToSendMessage.get('/user');
+ const updatedReceiver = await receiver.get('/user');
+ const updatedSender = await userToSendMessage.get('/user');
- let sendersMessageInReceiversInbox = findMessage(updatedReceiver.inbox.messages, userToSendMessage._id);
- let sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
+ const sendersMessageInReceiversInbox = findMessage(
+ updatedReceiver.inbox.messages, userToSendMessage._id,
+ );
+ const sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
let messageSentContent = t('privateMessageGiftGemsMessage', {
receiverName: receiver.profile.name,
senderName: userToSendMessage.profile.name,
gemAmount,
});
- messageSentContent = `\`${messageSentContent}\` `;
+ messageSentContent = `\`${messageSentContent}\` `;
expect(sendersMessageInReceiversInbox).to.exist;
expect(sendersMessageInReceiversInbox.text).to.equal(messageSentContent);
@@ -242,14 +244,16 @@ describe('POST /members/transfer-gems', () => {
toUserId: receiver._id,
});
- let updatedReceiver = await receiver.get('/user');
- let updatedSender = await userToSendMessage.get('/user');
+ const updatedReceiver = await receiver.get('/user');
+ const updatedSender = await userToSendMessage.get('/user');
- let sendersMessageInReceiversInbox = findMessage(updatedReceiver.inbox.messages, userToSendMessage._id);
- let sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
+ const sendersMessageInReceiversInbox = findMessage(
+ updatedReceiver.inbox.messages, userToSendMessage._id,
+ );
+ const sendersMessageInSendersInbox = findMessage(updatedSender.inbox.messages, receiver._id);
- let [receieversMessageContent, sendersMessageContent] = ['es', 'cs'].map((lang) => {
- let messageContent = t('privateMessageGiftGemsMessage', {
+ const [receieversMessageContent, sendersMessageContent] = ['es', 'cs'].map(lang => {
+ const messageContent = t('privateMessageGiftGemsMessage', {
receiverName: receiver.profile.name,
senderName: userToSendMessage.profile.name,
gemAmount,
diff --git a/test/api/v3/integration/models/GET-model_paths.test.js b/test/api/v3/integration/models/GET-model_paths.test.js
index 9e4b4fb4fa..15ef35faed 100644
--- a/test/api/v3/integration/models/GET-model_paths.test.js
+++ b/test/api/v3/integration/models/GET-model_paths.test.js
@@ -18,10 +18,10 @@ describe('GET /models/:model/paths', () => {
});
});
- let models = ['habit', 'daily', 'todo', 'reward', 'user', 'tag', 'challenge', 'group'];
+ const models = ['habit', 'daily', 'todo', 'reward', 'user', 'tag', 'challenge', 'group'];
models.forEach(model => {
it(`returns the model paths for ${model}`, async () => {
- let res = await user.get(`/models/${model}/paths`);
+ const res = await user.get(`/models/${model}/paths`);
if (model !== 'tag') expect(res._id).to.equal('String');
if (model === 'tag') expect(res.id).to.equal('String');
diff --git a/test/api/v3/integration/notFound.test.js b/test/api/v3/integration/notFound.test.js
index 747b370af9..721b4f391c 100644
--- a/test/api/v3/integration/notFound.test.js
+++ b/test/api/v3/integration/notFound.test.js
@@ -2,7 +2,7 @@ import { requester } from '../../../helpers/api-integration/v3';
describe('notFound Middleware', () => {
it('returns a 404 error when the resource is not found', async () => {
- let request = requester().get('/api/v3/dummy-url');
+ const request = requester().get('/api/v3/dummy-url');
await expect(request).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/notifications/POST-notifications_notificationId_read.test.js b/test/api/v3/integration/notifications/POST-notifications_notificationId_read.test.js
index a5678d3c80..29011cb3fa 100644
--- a/test/api/v3/integration/notifications/POST-notifications_notificationId_read.test.js
+++ b/test/api/v3/integration/notifications/POST-notifications_notificationId_read.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /notifications/:notificationId/read', () => {
let user;
@@ -12,7 +12,7 @@ describe('POST /notifications/:notificationId/read', () => {
});
it('errors when notification is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.post(`/notifications/${dummyId}/read`)).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/notifications/POST-notifications_notificationId_see.test.js b/test/api/v3/integration/notifications/POST-notifications_notificationId_see.test.js
index a31b60d18c..f1104563ee 100644
--- a/test/api/v3/integration/notifications/POST-notifications_notificationId_see.test.js
+++ b/test/api/v3/integration/notifications/POST-notifications_notificationId_see.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /notifications/:notificationId/see', () => {
let user;
@@ -12,7 +12,7 @@ describe('POST /notifications/:notificationId/see', () => {
});
it('errors when notification is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.post(`/notifications/${dummyId}/see`)).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/notifications/POST-notifications_read.test.js b/test/api/v3/integration/notifications/POST-notifications_read.test.js
index 47844bcd18..1839e38630 100644
--- a/test/api/v3/integration/notifications/POST-notifications_read.test.js
+++ b/test/api/v3/integration/notifications/POST-notifications_read.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /notifications/read', () => {
let user;
@@ -12,7 +12,7 @@ describe('POST /notifications/read', () => {
});
it('errors when notification is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.post('/notifications/read', {
notificationIds: [dummyId],
diff --git a/test/api/v3/integration/notifications/POST_notifications_see.test.js b/test/api/v3/integration/notifications/POST_notifications_see.test.js
index bb8f6b7fbf..eb1cb599db 100644
--- a/test/api/v3/integration/notifications/POST_notifications_see.test.js
+++ b/test/api/v3/integration/notifications/POST_notifications_see.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /notifications/see', () => {
let user;
@@ -12,7 +12,7 @@ describe('POST /notifications/see', () => {
});
it('errors when notification is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.post('/notifications/see', {
notificationIds: [dummyId],
diff --git a/test/api/v3/integration/notifications/prevent-multiple-notification.js b/test/api/v3/integration/notifications/prevent-multiple-notification.js
index 6fcf655d55..cc4fd20a3d 100644
--- a/test/api/v3/integration/notifications/prevent-multiple-notification.js
+++ b/test/api/v3/integration/notifications/prevent-multiple-notification.js
@@ -3,10 +3,11 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('Prevent multiple notifications', () => {
- let partyLeader, partyMembers, party;
+ let partyLeader; let partyMembers; let
+ party;
before(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
type: 'party',
privacy: 'private',
@@ -22,10 +23,10 @@ describe('Prevent multiple notifications', () => {
it('does not add the same notification twice', async () => {
const multipleChatMessages = [];
- for (let i = 0; i < 4; i++) {
- for (let memberIndex = 0; memberIndex < partyMembers.length; memberIndex++) {
+ for (let i = 0; i < 4; i += 1) {
+ for (let memberIndex = 0; memberIndex < partyMembers.length; memberIndex += 1) {
multipleChatMessages.push(
- partyMembers[memberIndex].post(`/groups/${party._id}/chat`, { message: `Message ${i}_${memberIndex}`}),
+ partyMembers[memberIndex].post(`/groups/${party._id}/chat`, { message: `Message ${i}_${memberIndex}` }),
);
}
}
diff --git a/test/api/v3/integration/payments/amazon/GET-payments_amazon_subscribe_cancel.test.js b/test/api/v3/integration/payments/amazon/GET-payments_amazon_subscribe_cancel.test.js
index c6de3b1709..67313693be 100644
--- a/test/api/v3/integration/payments/amazon/GET-payments_amazon_subscribe_cancel.test.js
+++ b/test/api/v3/integration/payments/amazon/GET-payments_amazon_subscribe_cancel.test.js
@@ -6,8 +6,9 @@ import {
import amzLib from '../../../../../../website/server/libs/payments/amazon';
describe('payments : amazon #subscribeCancel', () => {
- let endpoint = '/amazon/subscribe/cancel?noRedirect=true';
- let user, group, amazonSubscribeCancelStub;
+ const endpoint = '/amazon/subscribe/cancel?noRedirect=true';
+ let user; let group; let
+ amazonSubscribeCancelStub;
beforeEach(async () => {
user = await generateUser();
diff --git a/test/api/v3/integration/payments/amazon/POST-payments_amazon_checkout.test.js b/test/api/v3/integration/payments/amazon/POST-payments_amazon_checkout.test.js
index 948c948f13..93d08dc44b 100644
--- a/test/api/v3/integration/payments/amazon/POST-payments_amazon_checkout.test.js
+++ b/test/api/v3/integration/payments/amazon/POST-payments_amazon_checkout.test.js
@@ -4,8 +4,9 @@ import {
import amzLib from '../../../../../../website/server/libs/payments/amazon';
describe('payments - amazon - #checkout', () => {
- let endpoint = '/amazon/checkout';
- let user, amazonCheckoutStub;
+ const endpoint = '/amazon/checkout';
+ let user; let
+ amazonCheckoutStub;
beforeEach(async () => {
user = await generateUser();
@@ -37,7 +38,7 @@ describe('payments - amazon - #checkout', () => {
balance: 2,
});
- let gift = {
+ const gift = {
type: 'gems',
gems: {
amount: 16,
@@ -45,7 +46,7 @@ describe('payments - amazon - #checkout', () => {
},
};
- let orderReferenceId = 'orderReferenceId-example';
+ const orderReferenceId = 'orderReferenceId-example';
await user.post(endpoint, {
gift,
diff --git a/test/api/v3/integration/payments/amazon/POST-payments_amazon_createOrderReferenceId.test.js b/test/api/v3/integration/payments/amazon/POST-payments_amazon_createOrderReferenceId.test.js
index ce9a361353..d965253426 100644
--- a/test/api/v3/integration/payments/amazon/POST-payments_amazon_createOrderReferenceId.test.js
+++ b/test/api/v3/integration/payments/amazon/POST-payments_amazon_createOrderReferenceId.test.js
@@ -3,7 +3,7 @@ import {
} from '../../../../../helpers/api-integration/v3';
describe('payments - amazon - #createOrderReferenceId', () => {
- let endpoint = '/amazon/createOrderReferenceId';
+ const endpoint = '/amazon/createOrderReferenceId';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/amazon/POST-payments_amazon_subscribe.test.js b/test/api/v3/integration/payments/amazon/POST-payments_amazon_subscribe.test.js
index c925579979..b6c09848a3 100644
--- a/test/api/v3/integration/payments/amazon/POST-payments_amazon_subscribe.test.js
+++ b/test/api/v3/integration/payments/amazon/POST-payments_amazon_subscribe.test.js
@@ -6,8 +6,9 @@ import {
import amzLib from '../../../../../../website/server/libs/payments/amazon';
describe('payments - amazon - #subscribe', () => {
- let endpoint = '/amazon/subscribe';
- let user, group, subscribeWithAmazonStub;
+ const endpoint = '/amazon/subscribe';
+ let user; let group; let
+ subscribeWithAmazonStub;
beforeEach(async () => {
user = await generateUser();
@@ -22,8 +23,8 @@ describe('payments - amazon - #subscribe', () => {
});
describe('success', () => {
- let billingAgreementId = 'billingAgreementId-example';
- let subscription = 'basic_3mo';
+ const billingAgreementId = 'billingAgreementId-example';
+ const subscription = 'basic_3mo';
let coupon;
beforeEach(() => {
diff --git a/test/api/v3/integration/payments/amazon/POST-payments_amazon_verifyAccessToken.test.js b/test/api/v3/integration/payments/amazon/POST-payments_amazon_verifyAccessToken.test.js
index e086091d05..e7e0b81d65 100644
--- a/test/api/v3/integration/payments/amazon/POST-payments_amazon_verifyAccessToken.test.js
+++ b/test/api/v3/integration/payments/amazon/POST-payments_amazon_verifyAccessToken.test.js
@@ -3,7 +3,7 @@ import {
} from '../../../../../helpers/api-integration/v3';
describe('payments : amazon', () => {
- let endpoint = '/amazon/verifyAccessToken';
+ const endpoint = '/amazon/verifyAccessToken';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/apple/GET-payments_apple_cancelSubscribe.js b/test/api/v3/integration/payments/apple/GET-payments_apple_cancelSubscribe.js
index 797d2126bb..778626b5b9 100644
--- a/test/api/v3/integration/payments/apple/GET-payments_apple_cancelSubscribe.js
+++ b/test/api/v3/integration/payments/apple/GET-payments_apple_cancelSubscribe.js
@@ -1,8 +1,8 @@
-import {generateUser} from '../../../../../helpers/api-integration/v3';
+import { generateUser } from '../../../../../helpers/api-integration/v3';
import applePayments from '../../../../../../website/server/libs/payments/apple';
describe('payments : apple #cancelSubscribe', () => {
- let endpoint = '/iap/ios/subscribe/cancel?noRedirect=true';
+ const endpoint = '/iap/ios/subscribe/cancel?noRedirect=true';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/apple/POST-payments_apple_norenewsubscribe.test.js b/test/api/v3/integration/payments/apple/POST-payments_apple_norenewsubscribe.test.js
index bd4223d247..78b7bc3a38 100644
--- a/test/api/v3/integration/payments/apple/POST-payments_apple_norenewsubscribe.test.js
+++ b/test/api/v3/integration/payments/apple/POST-payments_apple_norenewsubscribe.test.js
@@ -1,9 +1,9 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import applePayments from '../../../../../../website/server/libs/payments/apple';
describe('payments : apple #norenewsubscribe', () => {
- let endpoint = '/iap/ios/norenew-subscribe';
- let sku = 'com.habitrpg.ios.habitica.subscription.3month';
+ const endpoint = '/iap/ios/norenew-subscribe';
+ const sku = 'com.habitrpg.ios.habitica.subscription.3month';
let user;
beforeEach(async () => {
@@ -50,7 +50,7 @@ describe('payments : apple #norenewsubscribe', () => {
await user.post(endpoint, {
sku,
- transaction: {receipt: 'receipt'},
+ transaction: { receipt: 'receipt' },
gift: {
uuid: '1',
},
diff --git a/test/api/v3/integration/payments/apple/POST-payments_apple_subscribe.test.js b/test/api/v3/integration/payments/apple/POST-payments_apple_subscribe.test.js
index 63d76fcea0..faf5f0e6ea 100644
--- a/test/api/v3/integration/payments/apple/POST-payments_apple_subscribe.test.js
+++ b/test/api/v3/integration/payments/apple/POST-payments_apple_subscribe.test.js
@@ -1,8 +1,8 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import applePayments from '../../../../../../website/server/libs/payments/apple';
describe('payments : apple #subscribe', () => {
- let endpoint = '/iap/ios/subscribe';
+ const endpoint = '/iap/ios/subscribe';
let user;
beforeEach(async () => {
@@ -37,7 +37,7 @@ describe('payments : apple #subscribe', () => {
balance: 2,
});
- let sku = 'com.habitrpg.ios.habitica.subscription.3month';
+ const sku = 'com.habitrpg.ios.habitica.subscription.3month';
await user.post(endpoint, {
sku,
diff --git a/test/api/v3/integration/payments/apple/POST-payments_apple_verifyiap.js b/test/api/v3/integration/payments/apple/POST-payments_apple_verifyiap.js
index b0b52ffdd8..d142fe2a24 100644
--- a/test/api/v3/integration/payments/apple/POST-payments_apple_verifyiap.js
+++ b/test/api/v3/integration/payments/apple/POST-payments_apple_verifyiap.js
@@ -1,8 +1,8 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import applePayments from '../../../../../../website/server/libs/payments/apple';
describe('payments : apple #verify', () => {
- let endpoint = '/iap/ios/verify';
+ const endpoint = '/iap/ios/verify';
let user;
beforeEach(async () => {
@@ -36,7 +36,8 @@ describe('payments : apple #verify', () => {
await user.post(endpoint, {
transaction: {
receipt: 'receipt',
- }});
+ },
+ });
expect(verifyStub).to.be.calledOnce;
expect(verifyStub.args[0][0].user._id).to.eql(user._id);
@@ -56,7 +57,8 @@ describe('payments : apple #verify', () => {
},
gift: {
uuid: '1',
- }});
+ },
+ });
expect(verifyStub).to.be.calledOnce;
expect(verifyStub.args[0][0].user._id).to.eql(user._id);
diff --git a/test/api/v3/integration/payments/google/GET-payments_google_cancelSubscribe.js b/test/api/v3/integration/payments/google/GET-payments_google_cancelSubscribe.js
index ad375b89c5..9bc3a443c8 100644
--- a/test/api/v3/integration/payments/google/GET-payments_google_cancelSubscribe.js
+++ b/test/api/v3/integration/payments/google/GET-payments_google_cancelSubscribe.js
@@ -1,8 +1,8 @@
-import {generateUser} from '../../../../../helpers/api-integration/v3';
+import { generateUser } from '../../../../../helpers/api-integration/v3';
import googlePayments from '../../../../../../website/server/libs/payments/google';
describe('payments : google #cancelSubscribe', () => {
- let endpoint = '/iap/android/subscribe/cancel?noRedirect=true';
+ const endpoint = '/iap/android/subscribe/cancel?noRedirect=true';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/google/POST-payments_google_norenewsubscribe.test.js b/test/api/v3/integration/payments/google/POST-payments_google_norenewsubscribe.test.js
index 9d15135537..888ffe3bbb 100644
--- a/test/api/v3/integration/payments/google/POST-payments_google_norenewsubscribe.test.js
+++ b/test/api/v3/integration/payments/google/POST-payments_google_norenewsubscribe.test.js
@@ -1,9 +1,9 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import googlePayments from '../../../../../../website/server/libs/payments/google';
describe('payments : google #norenewsubscribe', () => {
- let endpoint = '/iap/android/norenew-subscribe';
- let sku = 'com.habitrpg.android.habitica.subscription.3month';
+ const endpoint = '/iap/android/norenew-subscribe';
+ const sku = 'com.habitrpg.android.habitica.subscription.3month';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/google/POST-payments_google_subscribe.test.js b/test/api/v3/integration/payments/google/POST-payments_google_subscribe.test.js
index 1ee940efef..48e4b68281 100644
--- a/test/api/v3/integration/payments/google/POST-payments_google_subscribe.test.js
+++ b/test/api/v3/integration/payments/google/POST-payments_google_subscribe.test.js
@@ -1,8 +1,8 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import googlePayments from '../../../../../../website/server/libs/payments/google';
describe('payments : google #subscribe', () => {
- let endpoint = '/iap/android/subscribe';
+ const endpoint = '/iap/android/subscribe';
let user;
beforeEach(async () => {
@@ -37,11 +37,11 @@ describe('payments : google #subscribe', () => {
balance: 2,
});
- let sku = 'com.habitrpg.android.habitica.subscription.3month';
+ const sku = 'com.habitrpg.android.habitica.subscription.3month';
await user.post(endpoint, {
sku,
- transaction: {receipt: 'receipt', signature: 'signature'},
+ transaction: { receipt: 'receipt', signature: 'signature' },
});
expect(subscribeStub).to.be.calledOnce;
diff --git a/test/api/v3/integration/payments/google/POST-payments_google_verifyiap.js b/test/api/v3/integration/payments/google/POST-payments_google_verifyiap.js
index 0149a44fc3..ecdf17dfc0 100644
--- a/test/api/v3/integration/payments/google/POST-payments_google_verifyiap.js
+++ b/test/api/v3/integration/payments/google/POST-payments_google_verifyiap.js
@@ -1,8 +1,8 @@
-import {generateUser, translate as t} from '../../../../../helpers/api-integration/v3';
+import { generateUser, translate as t } from '../../../../../helpers/api-integration/v3';
import googlePayments from '../../../../../../website/server/libs/payments/google';
describe('payments : google #verify', () => {
- let endpoint = '/iap/android/verify';
+ const endpoint = '/iap/android/verify';
let user;
beforeEach(async () => {
@@ -34,7 +34,7 @@ describe('payments : google #verify', () => {
});
await user.post(endpoint, {
- transaction: {receipt: 'receipt', signature: 'signature'},
+ transaction: { receipt: 'receipt', signature: 'signature' },
});
expect(verifyStub).to.be.calledOnce;
@@ -51,8 +51,8 @@ describe('payments : google #verify', () => {
});
await user.post(endpoint, {
- transaction: {receipt: 'receipt', signature: 'signature'},
- gift: {uuid: '1'},
+ transaction: { receipt: 'receipt', signature: 'signature' },
+ gift: { uuid: '1' },
});
expect(verifyStub).to.be.calledOnce;
diff --git a/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout.test.js b/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout.test.js
index ffaf8fbc8d..da1d342b7f 100644
--- a/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout.test.js
+++ b/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout.test.js
@@ -4,7 +4,7 @@ import {
import paypalPayments from '../../../../../../website/server/libs/payments/paypal';
describe('payments : paypal #checkout', () => {
- let endpoint = '/paypal/checkout';
+ const endpoint = '/paypal/checkout';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout_success.test.js b/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout_success.test.js
index 9c2947c95e..24544903fd 100644
--- a/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout_success.test.js
+++ b/test/api/v3/integration/payments/paypal/GET-payments_paypal_checkout_success.test.js
@@ -5,7 +5,7 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import apiError from '../../../../../../website/server/libs/apiError';
describe('payments : paypal #checkoutSuccess', () => {
- let endpoint = '/paypal/checkout/success';
+ const endpoint = '/paypal/checkout/success';
let user;
beforeEach(async () => {
@@ -42,8 +42,8 @@ describe('payments : paypal #checkoutSuccess', () => {
});
it('makes a purchase', async () => {
- let paymentId = 'test-paymentid';
- let customerId = 'test-customerId';
+ const paymentId = 'test-paymentid';
+ const customerId = 'test-customerId';
user = await generateUser({
'profile.name': 'sender',
diff --git a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe.test.js b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe.test.js
index 156df85340..735750786c 100644
--- a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe.test.js
+++ b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe.test.js
@@ -6,7 +6,7 @@ import shared from '../../../../../../website/common';
import apiError from '../../../../../../website/server/libs/apiError';
describe('payments : paypal #subscribe', () => {
- let endpoint = '/paypal/subscribe';
+ const endpoint = '/paypal/subscribe';
let user;
beforeEach(async () => {
@@ -33,8 +33,8 @@ describe('payments : paypal #subscribe', () => {
});
it('makes a purchase', async () => {
- let subKey = 'basic_3mo';
- let sub = shared.content.subscriptionBlocks[subKey];
+ const subKey = 'basic_3mo';
+ const sub = shared.content.subscriptionBlocks[subKey];
user = await generateUser({
'profile.name': 'sender',
diff --git a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_cancel.test.js b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_cancel.test.js
index 4a3f416dd8..ff50da8a0e 100644
--- a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_cancel.test.js
+++ b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_cancel.test.js
@@ -5,7 +5,7 @@ import {
import paypalPayments from '../../../../../../website/server/libs/payments/paypal';
describe('payments : paypal #subscribeCancel', () => {
- let endpoint = '/paypal/subscribe/cancel';
+ const endpoint = '/paypal/subscribe/cancel';
let user;
beforeEach(async () => {
diff --git a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_success.test.js b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_success.test.js
index db0d53838f..bd402c5600 100644
--- a/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_success.test.js
+++ b/test/api/v3/integration/payments/paypal/GET-payments_paypal_subscribe_success.test.js
@@ -5,7 +5,7 @@ import apiError from '../../../../../../website/server/libs/apiError';
import paypalPayments from '../../../../../../website/server/libs/payments/paypal';
describe('payments : paypal #subscribeSuccess', () => {
- let endpoint = '/paypal/subscribe/success';
+ const endpoint = '/paypal/subscribe/success';
let user;
beforeEach(async () => {
@@ -32,7 +32,7 @@ describe('payments : paypal #subscribeSuccess', () => {
});
it('creates a subscription', async () => {
- let token = 'test-token';
+ const token = 'test-token';
user = await generateUser({
'profile.name': 'sender',
diff --git a/test/api/v3/integration/payments/paypal/POST-payments_paypal_ipn.test.js b/test/api/v3/integration/payments/paypal/POST-payments_paypal_ipn.test.js
index 3e233ce9c5..7632a79e9c 100644
--- a/test/api/v3/integration/payments/paypal/POST-payments_paypal_ipn.test.js
+++ b/test/api/v3/integration/payments/paypal/POST-payments_paypal_ipn.test.js
@@ -4,7 +4,7 @@ import {
import paypalPayments from '../../../../../../website/server/libs/payments/paypal';
describe('payments - paypal - #ipn', () => {
- let endpoint = '/paypal/ipn';
+ const endpoint = '/paypal/ipn';
let user;
beforeEach(async () => {
@@ -12,7 +12,7 @@ describe('payments - paypal - #ipn', () => {
});
it('verifies credentials', async () => {
- let result = await user.post(endpoint);
+ const result = await user.post(endpoint);
expect(result).to.eql('OK');
});
diff --git a/test/api/v3/integration/payments/stripe/GET-payments_stripe_subscribe_cancel.test.js b/test/api/v3/integration/payments/stripe/GET-payments_stripe_subscribe_cancel.test.js
index 6f074ac077..d6ec1e0312 100644
--- a/test/api/v3/integration/payments/stripe/GET-payments_stripe_subscribe_cancel.test.js
+++ b/test/api/v3/integration/payments/stripe/GET-payments_stripe_subscribe_cancel.test.js
@@ -6,8 +6,9 @@ import {
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
describe('payments - stripe - #subscribeCancel', () => {
- let endpoint = '/stripe/subscribe/cancel?noRedirect=true';
- let user, group, stripeCancelSubscriptionStub;
+ const endpoint = '/stripe/subscribe/cancel?noRedirect=true';
+ let user; let group; let
+ stripeCancelSubscriptionStub;
beforeEach(async () => {
user = await generateUser();
diff --git a/test/api/v3/integration/payments/stripe/POST-payments_stripe_checkout.test.js b/test/api/v3/integration/payments/stripe/POST-payments_stripe_checkout.test.js
index c7ad5015b9..a576e4aed8 100644
--- a/test/api/v3/integration/payments/stripe/POST-payments_stripe_checkout.test.js
+++ b/test/api/v3/integration/payments/stripe/POST-payments_stripe_checkout.test.js
@@ -5,15 +5,16 @@ import {
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
describe('payments - stripe - #checkout', () => {
- let endpoint = '/stripe/checkout';
- let user, group;
+ const endpoint = '/stripe/checkout';
+ let user; let
+ group;
beforeEach(async () => {
user = await generateUser();
});
it('verifies credentials', async () => {
- await expect(user.post(endpoint, {id: 123})).to.eventually.be.rejected.and.include({
+ await expect(user.post(endpoint, { id: 123 })).to.eventually.be.rejected.and.include({
code: 401,
error: 'Error',
message: 'Invalid API Key provided: aaaabbbb********************1111',
diff --git a/test/api/v3/integration/payments/stripe/POST-payments_stripe_subscribe_edit.test.js b/test/api/v3/integration/payments/stripe/POST-payments_stripe_subscribe_edit.test.js
index a071580ae6..640182f168 100644
--- a/test/api/v3/integration/payments/stripe/POST-payments_stripe_subscribe_edit.test.js
+++ b/test/api/v3/integration/payments/stripe/POST-payments_stripe_subscribe_edit.test.js
@@ -6,8 +6,9 @@ import {
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
describe('payments - stripe - #subscribeEdit', () => {
- let endpoint = '/stripe/subscribe/edit';
- let user, group;
+ const endpoint = '/stripe/subscribe/edit';
+ let user; let
+ group;
beforeEach(async () => {
user = await generateUser();
diff --git a/test/api/v3/integration/qrcodes/GET-qrcodes_user.test.js b/test/api/v3/integration/qrcodes/GET-qrcodes_user.test.js
index df5df6604b..796494cecd 100644
--- a/test/api/v3/integration/qrcodes/GET-qrcodes_user.test.js
+++ b/test/api/v3/integration/qrcodes/GET-qrcodes_user.test.js
@@ -1,9 +1,9 @@
+import superagent from 'superagent';
+import nconf from 'nconf';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import superagent from 'superagent';
-import nconf from 'nconf';
const API_TEST_SERVER_PORT = nconf.get('PORT');
xdescribe('GET /qr-code/user/:memberId', () => {
@@ -22,8 +22,8 @@ xdescribe('GET /qr-code/user/:memberId', () => {
});
it('redirects to profile page', async () => {
- let url = `http://localhost:${API_TEST_SERVER_PORT}/qr-code/user/${user._id}`;
- let response = await superagent.get(url).end(function (err, res) {
+ const url = `http://localhost:${API_TEST_SERVER_PORT}/qr-code/user/${user._id}`;
+ const response = await superagent.get(url).end((err, res) => {
expect(err).to.be(undefined);
return res;
});
diff --git a/test/api/v3/integration/quests/POST-groups_groupId_quests_accept.test.js b/test/api/v3/integration/quests/POST-groups_groupId_quests_accept.test.js
index bd2579c351..940d660232 100644
--- a/test/api/v3/integration/quests/POST-groups_groupId_quests_accept.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupId_quests_accept.test.js
@@ -17,7 +17,7 @@ describe('POST /groups/:groupId/quests/accept', () => {
beforeEach(async () => {
user = await generateUser();
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -51,7 +51,7 @@ describe('POST /groups/:groupId/quests/accept', () => {
});
it('does not accept quest for a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -134,7 +134,7 @@ describe('POST /groups/:groupId/quests/accept', () => {
});
it('cleans up user quest data for non-quest members when last member accepts', async () => {
- let rejectingMember = partyMembers[0];
+ const rejectingMember = partyMembers[0];
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await rejectingMember.post(`/groups/${questingGroup._id}/quests/reject`);
@@ -162,7 +162,7 @@ describe('POST /groups/:groupId/quests/accept', () => {
expect(groupChat[0]._meta).to.exist;
expect(groupChat[0]._meta).to.have.all.keys(['participatingMembers']);
- let returnedGroup = await leader.get(`/groups/${questingGroup._id}`);
+ const returnedGroup = await leader.get(`/groups/${questingGroup._id}`);
expect(returnedGroup.chat[0]._meta).to.be.undefined;
});
});
diff --git a/test/api/v3/integration/quests/POST-groups_groupId_quests_force-start.test.js b/test/api/v3/integration/quests/POST-groups_groupId_quests_force-start.test.js
index 025643cd93..0eb4745f1c 100644
--- a/test/api/v3/integration/quests/POST-groups_groupId_quests_force-start.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupId_quests_force-start.test.js
@@ -14,7 +14,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
let partyMembers;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 3,
});
@@ -30,7 +30,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
context('failure conditions', () => {
it('does not force start a quest for a group in which user is not a member', async () => {
- let nonMember = await generateUser();
+ const nonMember = await generateUser();
await expect(nonMember.post(`/groups/${questingGroup._id}/quests/force-start`))
.to.eventually.be.rejected.and.eql({
@@ -41,7 +41,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('does not force start quest for a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -91,8 +91,8 @@ describe('POST /groups/:groupId/quests/force-start', () => {
context('successfully force starting a quest', () => {
it('allows quest leader to force start quest', async () => {
- let questLeader = partyMembers[0];
- await questLeader.update({[`items.quests.${PET_QUEST}`]: 1});
+ const questLeader = partyMembers[0];
+ await questLeader.update({ [`items.quests.${PET_QUEST}`]: 1 });
await questLeader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await questLeader.post(`/groups/${questingGroup._id}/quests/force-start`);
@@ -103,8 +103,8 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('allows group leader to force start quest', async () => {
- let questLeader = partyMembers[0];
- await questLeader.update({[`items.quests.${PET_QUEST}`]: 1});
+ const questLeader = partyMembers[0];
+ await questLeader.update({ [`items.quests.${PET_QUEST}`]: 1 });
await questLeader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
@@ -117,7 +117,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
it('sends back the quest object', async () => {
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
- let quest = await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
+ const quest = await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
expect(quest.active).to.eql(true);
expect(quest.key).to.eql(PET_QUEST);
@@ -127,8 +127,8 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('cleans up user quest data for non-quest members', async () => {
- let partyMemberThatRejects = partyMembers[1];
- let partyMemberThatIgnores = partyMembers[2];
+ const partyMemberThatRejects = partyMembers[1];
+ const partyMemberThatIgnores = partyMembers[2];
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await partyMembers[0].post(`/groups/${questingGroup._id}/quests/accept`);
@@ -152,9 +152,9 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('removes users who have not accepted the quest from quest.members', async () => {
- let partyMemberThatRejects = partyMembers[1];
- let partyMemberThatIgnores = partyMembers[2];
- let partyMemberThatAccepts = partyMembers[0];
+ const partyMemberThatRejects = partyMembers[1];
+ const partyMemberThatIgnores = partyMembers[2];
+ const partyMemberThatAccepts = partyMembers[0];
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await partyMemberThatAccepts.post(`/groups/${questingGroup._id}/quests/accept`);
@@ -174,7 +174,7 @@ describe('POST /groups/:groupId/quests/force-start', () => {
it('removes users who are not in the party from quest.members', async () => {
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
- let notInPartyUser = await generateUser();
+ const notInPartyUser = await generateUser();
await questingGroup.update({
[`quest.members.${notInPartyUser._id}`]: true,
@@ -210,8 +210,8 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('removes users who don\'t have true value in quest.members from quest.members', async () => {
- let partyMemberThatRejects = partyMembers[1];
- let partyMemberThatIgnores = partyMembers[2];
+ const partyMemberThatRejects = partyMembers[1];
+ const partyMemberThatIgnores = partyMembers[2];
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await partyMembers[0].post(`/groups/${questingGroup._id}/quests/accept`);
@@ -234,8 +234,8 @@ describe('POST /groups/:groupId/quests/force-start', () => {
});
it('allows group leader to force start quest and verifies chat', async () => {
- let questLeader = partyMembers[0];
- await questLeader.update({[`items.quests.${PET_QUEST}`]: 1});
+ const questLeader = partyMembers[0];
+ await questLeader.update({ [`items.quests.${PET_QUEST}`]: 1 });
await questLeader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await leader.post(`/groups/${questingGroup._id}/quests/force-start`);
diff --git a/test/api/v3/integration/quests/POST-groups_groupId_quests_invite.test.js b/test/api/v3/integration/quests/POST-groups_groupId_quests_invite.test.js
index a6a3b67e6f..3581663c6e 100644
--- a/test/api/v3/integration/quests/POST-groups_groupId_quests_invite.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupId_quests_invite.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
sleep,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import { quests as questScrolls } from '../../../../../website/common/script/content/quests';
import { chatModel as Chat } from '../../../../../website/server/models/message';
import apiError from '../../../../../website/server/libs/apiError';
@@ -15,14 +15,14 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
const PET_QUEST = 'whale';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
questingGroup = group;
leader = groupLeader;
- member = members[0];
+ member = members[0]; // eslint-disable-line prefer-destructuring
});
context('failure conditions', () => {
@@ -35,12 +35,12 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('does not issue invites for a group in which user is not a member', async () => {
- let { group } = await createAndPopulateGroup({
+ const { group } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- let alternateGroup = group;
+ const alternateGroup = group;
await expect(leader.post(`/groups/${alternateGroup._id}/quests/invite/${PET_QUEST}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -50,12 +50,12 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('does not issue invites for Guilds', async () => {
- let { group } = await createAndPopulateGroup({
+ const { group } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'public' },
members: 1,
});
- let alternateGroup = group;
+ const alternateGroup = group;
await expect(leader.post(`/groups/${alternateGroup._id}/quests/invite/${PET_QUEST}`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -70,7 +70,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
await expect(leader.post(`/groups/${questingGroup._id}/quests/invite/${FAKE_QUEST}`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('questNotFound', {key: FAKE_QUEST}),
+ message: apiError('questNotFound', { key: FAKE_QUEST }),
});
});
@@ -94,7 +94,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
await expect(leader.post(`/groups/${questingGroup._id}/quests/invite/${LEVELED_QUEST}`)).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('questLevelTooHigh', {level: LEVELED_QUEST_REQ}),
+ message: t('questLevelTooHigh', { level: LEVELED_QUEST_REQ }),
});
});
@@ -130,7 +130,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
await questingGroup.sync();
- let quest = questingGroup.quest;
+ const { quest } = questingGroup;
expect(quest.key).to.eql(PET_QUEST);
expect(quest.active).to.eql(false);
@@ -157,7 +157,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('sends back the quest object', async () => {
- let inviteResponse = await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
+ const inviteResponse = await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
expect(inviteResponse.key).to.eql(PET_QUEST);
expect(inviteResponse.active).to.eql(false);
@@ -168,7 +168,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('allows non-party-leader party members to send invites', async () => {
- let inviteResponse = await member.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
+ const inviteResponse = await member.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await questingGroup.sync();
@@ -177,9 +177,9 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('starts quest automatically if user is in a solo party', async () => {
- let leaderDetails = { balance: 10 };
+ const leaderDetails = { balance: 10 };
leaderDetails[`items.quests.${PET_QUEST}`] = 1;
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
leaderDetails,
});
@@ -192,9 +192,9 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
});
it('starts quest automatically if user is in a solo party and verifies chat', async () => {
- let leaderDetails = { balance: 10 };
+ const leaderDetails = { balance: 10 };
leaderDetails[`items.quests.${PET_QUEST}`] = 1;
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
leaderDetails,
});
@@ -207,7 +207,7 @@ describe('POST /groups/:groupId/quests/invite/:questKey', () => {
expect(groupChat[0]._meta).to.exist;
expect(groupChat[0]._meta).to.have.all.keys(['participatingMembers']);
- let returnedGroup = await groupLeader.get(`/groups/${group._id}`);
+ const returnedGroup = await groupLeader.get(`/groups/${group._id}`);
expect(returnedGroup.chat[0]._meta).to.be.undefined;
});
});
diff --git a/test/api/v3/integration/quests/POST-groups_groupid_quests_abort.test.js b/test/api/v3/integration/quests/POST-groups_groupid_quests_abort.test.js
index bbfb871a63..7a42166a2c 100644
--- a/test/api/v3/integration/quests/POST-groups_groupid_quests_abort.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupid_quests_abort.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
generateUser,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import { model as Group } from '../../../../../website/server/models/group';
describe('POST /groups/:groupId/quests/abort', () => {
@@ -15,7 +15,7 @@ describe('POST /groups/:groupId/quests/abort', () => {
const PET_QUEST = 'whale';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -50,7 +50,7 @@ describe('POST /groups/:groupId/quests/abort', () => {
});
it('returns an error when group is a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -90,9 +90,9 @@ describe('POST /groups/:groupId/quests/abort', () => {
await partyMembers[0].post(`/groups/${questingGroup._id}/quests/accept`);
await partyMembers[1].post(`/groups/${questingGroup._id}/quests/accept`);
- let stub = sandbox.spy(Group.prototype, 'sendChat');
+ const stub = sandbox.spy(Group.prototype, 'sendChat');
- let res = await leader.post(`/groups/${questingGroup._id}/quests/abort`);
+ const res = await leader.post(`/groups/${questingGroup._id}/quests/abort`);
await Promise.all([
leader.sync(),
questingGroup.sync(),
@@ -100,7 +100,7 @@ describe('POST /groups/:groupId/quests/abort', () => {
partyMembers[1].sync(),
]);
- let cleanUserQuestObj = {
+ const cleanUserQuestObj = {
key: null,
progress: {
up: 0,
diff --git a/test/api/v3/integration/quests/POST-groups_groupid_quests_cancel.test.js b/test/api/v3/integration/quests/POST-groups_groupid_quests_cancel.test.js
index 4032c36306..7df6dbd0f4 100644
--- a/test/api/v3/integration/quests/POST-groups_groupid_quests_cancel.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupid_quests_cancel.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
generateUser,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import { model as Group } from '../../../../../website/server/models/group';
describe('POST /groups/:groupId/quests/cancel', () => {
@@ -15,7 +15,7 @@ describe('POST /groups/:groupId/quests/cancel', () => {
const PET_QUEST = 'whale';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -50,7 +50,7 @@ describe('POST /groups/:groupId/quests/cancel', () => {
});
it('returns an error when group is a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -103,9 +103,9 @@ describe('POST /groups/:groupId/quests/cancel', () => {
// partyMembers[1] hasn't accepted the invitation, because if he accepts, invitation phase ends.
// The cancel command can be done only in the invitation phase.
- let stub = sandbox.spy(Group.prototype, 'sendChat');
+ const stub = sandbox.spy(Group.prototype, 'sendChat');
- let res = await leader.post(`/groups/${questingGroup._id}/quests/cancel`);
+ const res = await leader.post(`/groups/${questingGroup._id}/quests/cancel`);
await Promise.all([
leader.sync(),
@@ -114,7 +114,7 @@ describe('POST /groups/:groupId/quests/cancel', () => {
questingGroup.sync(),
]);
- let clean = {
+ const clean = {
key: null,
progress: {
up: 0,
diff --git a/test/api/v3/integration/quests/POST-groups_groupid_quests_leave.test.js b/test/api/v3/integration/quests/POST-groups_groupid_quests_leave.test.js
index 9475af23c5..d8e6e9c70b 100644
--- a/test/api/v3/integration/quests/POST-groups_groupid_quests_leave.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupid_quests_leave.test.js
@@ -1,9 +1,9 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
generateUser,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /groups/:groupId/quests/leave', () => {
let questingGroup;
@@ -14,7 +14,7 @@ describe('POST /groups/:groupId/quests/leave', () => {
const PET_QUEST = 'whale';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -49,7 +49,7 @@ describe('POST /groups/:groupId/quests/leave', () => {
});
it('returns an error when group is a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -102,7 +102,7 @@ describe('POST /groups/:groupId/quests/leave', () => {
await partyMembers[0].post(`/groups/${questingGroup._id}/quests/accept`);
await partyMembers[1].post(`/groups/${questingGroup._id}/quests/accept`);
- let leaveResult = await partyMembers[0].post(`/groups/${questingGroup._id}/quests/leave`);
+ const leaveResult = await partyMembers[0].post(`/groups/${questingGroup._id}/quests/leave`);
await Promise.all([
partyMembers[0].sync(),
questingGroup.sync(),
diff --git a/test/api/v3/integration/quests/POST-groups_groupid_quests_reject.test.js b/test/api/v3/integration/quests/POST-groups_groupid_quests_reject.test.js
index 8f6f4e6442..c36df1e6dc 100644
--- a/test/api/v3/integration/quests/POST-groups_groupid_quests_reject.test.js
+++ b/test/api/v3/integration/quests/POST-groups_groupid_quests_reject.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
generateUser,
sleep,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import { chatModel as Chat } from '../../../../../website/server/models/message';
describe('POST /groups/:groupId/quests/reject', () => {
@@ -16,7 +16,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
const PET_QUEST = 'whale';
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 2,
});
@@ -51,7 +51,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
});
it('returns an error when group is a guild', async () => {
- let { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
+ const { group: guild, groupLeader: guildLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
@@ -127,7 +127,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
});
context('successfully quest rejection', () => {
- let cleanUserQuestObj = {
+ const cleanUserQuestObj = {
key: null,
progress: {
up: 0,
@@ -142,7 +142,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
it('rejects a quest invitation', async () => {
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
- let res = await partyMembers[0].post(`/groups/${questingGroup._id}/quests/reject`);
+ const res = await partyMembers[0].post(`/groups/${questingGroup._id}/quests/reject`);
await partyMembers[0].sync();
await questingGroup.sync();
@@ -162,7 +162,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
});
it('cleans up user quest data for non-quest members when last member rejects', async () => {
- let rejectingMember = partyMembers[1];
+ const rejectingMember = partyMembers[1];
await leader.post(`/groups/${questingGroup._id}/quests/invite/${PET_QUEST}`);
await partyMembers[0].post(`/groups/${questingGroup._id}/quests/accept`);
@@ -193,7 +193,7 @@ describe('POST /groups/:groupId/quests/reject', () => {
expect(groupChat[0]._meta).to.exist;
expect(groupChat[0]._meta).to.have.all.keys(['participatingMembers']);
- let returnedGroup = await leader.get(`/groups/${questingGroup._id}`);
+ const returnedGroup = await leader.get(`/groups/${questingGroup._id}`);
expect(returnedGroup.chat[0]._meta).to.be.undefined;
});
});
diff --git a/test/api/v3/integration/shops/GET-shops_backgrounds.test.js b/test/api/v3/integration/shops/GET-shops_backgrounds.test.js
index 738b92dde3..ed9d65a429 100644
--- a/test/api/v3/integration/shops/GET-shops_backgrounds.test.js
+++ b/test/api/v3/integration/shops/GET-shops_backgrounds.test.js
@@ -11,15 +11,15 @@ describe('GET /shops/backgrounds', () => {
});
it('returns a valid shop object', async () => {
- let shop = await user.get('/shops/backgrounds');
+ const shop = await user.get('/shops/backgrounds');
expect(shop.identifier).to.equal('backgroundShop');
expect(shop.text).to.eql(t('backgroundShop'));
expect(shop.notes).to.eql(t('backgroundShopText'));
expect(shop.imageName).to.equal('background_shop');
expect(shop.sets).to.be.an('array');
- let sets = shop.sets.map(set => set.identifier);
+ const sets = shop.sets.map(set => set.identifier);
expect(sets).to.include('incentiveBackgrounds');
expect(sets).to.include('backgrounds062014');
});
-});
\ No newline at end of file
+});
diff --git a/test/api/v3/integration/shops/GET-shops_market.test.js b/test/api/v3/integration/shops/GET-shops_market.test.js
index 8c9c941fcc..8feadaa89e 100644
--- a/test/api/v3/integration/shops/GET-shops_market.test.js
+++ b/test/api/v3/integration/shops/GET-shops_market.test.js
@@ -11,7 +11,7 @@ describe('GET /shops/market', () => {
});
it('returns a valid shop object', async () => {
- let shop = await user.get('/shops/market');
+ const shop = await user.get('/shops/market');
expect(shop.identifier).to.equal('market');
expect(shop.text).to.eql(t('market'));
@@ -19,7 +19,7 @@ describe('GET /shops/market', () => {
expect(shop.imageName).to.be.a('string');
expect(shop.categories).to.be.an('array');
- let categories = shop.categories.map(cat => cat.identifier);
+ const categories = shop.categories.map(cat => cat.identifier);
expect(categories).to.include('eggs');
expect(categories).to.include('hatchingPotions');
@@ -32,22 +32,22 @@ describe('GET /shops/market', () => {
'stats.gp': 99999999,
});
- let shop = await user.get('/shops/market');
- let items = shop.categories.reduce((array, category) => {
- category.items.forEach((item) => {
+ const shop = await user.get('/shops/market');
+ const items = shop.categories.reduce((array, category) => {
+ category.items.forEach(item => {
array.push(item);
});
return array;
}, []);
- let results = await Promise.all(items.map((item) => {
- let { purchaseType, key } = item;
+ const results = await Promise.all(items.map(item => {
+ const { purchaseType, key } = item;
return user.post(`/user/purchase/${purchaseType}/${key}`);
}));
expect(results.length).to.be.greaterThan(0);
- items.forEach((item) => {
+ items.forEach(item => {
expect(item).to.include.keys('key', 'text', 'notes', 'class', 'value', 'currency');
});
});
diff --git a/test/api/v3/integration/shops/GET-shops_quests.test.js b/test/api/v3/integration/shops/GET-shops_quests.test.js
index e4546fb4b5..5412328c24 100644
--- a/test/api/v3/integration/shops/GET-shops_quests.test.js
+++ b/test/api/v3/integration/shops/GET-shops_quests.test.js
@@ -11,7 +11,7 @@ describe('GET /shops/quests', () => {
});
it('returns a valid shop object', async () => {
- let shop = await user.get('/shops/quests');
+ const shop = await user.get('/shops/quests');
expect(shop.identifier).to.equal('questShop');
expect(shop.text).to.eql(t('quests'));
@@ -19,7 +19,7 @@ describe('GET /shops/quests', () => {
expect(shop.imageName).to.be.a('string');
expect(shop.categories).to.be.an('array');
- let categories = shop.categories.map(cat => cat.identifier);
+ const categories = shop.categories.map(cat => cat.identifier);
expect(categories).to.include('unlockable');
expect(categories).to.include('gold');
diff --git a/test/api/v3/integration/shops/GET-shops_seasonal.test.js b/test/api/v3/integration/shops/GET-shops_seasonal.test.js
index 9b4ffc2be9..6f88812064 100644
--- a/test/api/v3/integration/shops/GET-shops_seasonal.test.js
+++ b/test/api/v3/integration/shops/GET-shops_seasonal.test.js
@@ -11,7 +11,7 @@ describe('GET /shops/seasonal', () => {
});
it('returns a valid shop object', async () => {
- let shop = await user.get('/shops/seasonal');
+ const shop = await user.get('/shops/seasonal');
expect(shop.identifier).to.equal('seasonalShop');
expect(shop.text).to.eql(t('seasonalShop'));
diff --git a/test/api/v3/integration/shops/GET-shops_time_travelers.test.js b/test/api/v3/integration/shops/GET-shops_time_travelers.test.js
index 5ae901f657..81e3c3c23e 100644
--- a/test/api/v3/integration/shops/GET-shops_time_travelers.test.js
+++ b/test/api/v3/integration/shops/GET-shops_time_travelers.test.js
@@ -11,7 +11,7 @@ describe('GET /shops/time-travelers', () => {
});
it('returns a valid shop object', async () => {
- let shop = await user.get('/shops/time-travelers');
+ const shop = await user.get('/shops/time-travelers');
expect(shop.identifier).to.equal('timeTravelersShop');
expect(shop.text).to.eql(t('timeTravelers'));
@@ -19,17 +19,17 @@ describe('GET /shops/time-travelers', () => {
expect(shop.imageName).to.be.a('string');
expect(shop.categories).to.be.an('array');
- let categories = shop.categories.map(cat => cat.identifier);
+ const categories = shop.categories.map(cat => cat.identifier);
expect(categories).to.include('pets');
expect(categories).to.include('mounts');
expect(categories).to.include('201606');
- let mammothPet = shop.categories
+ const mammothPet = shop.categories
.find(cat => cat.identifier === 'pets')
.items
.find(pet => pet.key === 'Mammoth-Base');
- let mantisShrimp = shop.categories
+ const mantisShrimp = shop.categories
.find(cat => cat.identifier === 'mounts')
.items
.find(pet => pet.key === 'MantisShrimp-Base');
@@ -43,14 +43,14 @@ describe('GET /shops/time-travelers', () => {
'purchased.plan.consecutive.trinkets': 1,
});
- let shop = await user.get('/shops/time-travelers');
+ const shop = await user.get('/shops/time-travelers');
expect(shop.notes).to.eql(t('timeTravelersPopover'));
expect(shop.imageName).to.eql('npc_timetravelers_active');
});
it('returns inactive shop notes and imageName if user has trinkets', async () => {
- let shop = await user.get('/shops/time-travelers');
+ const shop = await user.get('/shops/time-travelers');
expect(shop.notes).to.eql(t('timeTravelersPopoverNoSubMobile'));
expect(shop.imageName).to.eql('npc_timetravelers');
@@ -64,9 +64,9 @@ describe('GET /shops/time-travelers', () => {
},
});
- let shop = await user.get('/shops/time-travelers');
+ const shop = await user.get('/shops/time-travelers');
- let categories = shop.categories.map(cat => cat.identifier);
+ const categories = shop.categories.map(cat => cat.identifier);
expect(categories).to.not.include('201606');
});
@@ -81,13 +81,13 @@ describe('GET /shops/time-travelers', () => {
},
});
- let shop = await user.get('/shops/time-travelers');
+ const shop = await user.get('/shops/time-travelers');
- let mammothPet = shop.categories
+ const mammothPet = shop.categories
.find(cat => cat.identifier === 'pets')
.items
.find(pet => pet.key === 'Mammoth-Base');
- let mantisShrimp = shop.categories
+ const mantisShrimp = shop.categories
.find(cat => cat.identifier === 'mounts')
.items
.find(pet => pet.key === 'MantisShrimp-Base');
diff --git a/test/api/v3/integration/status/GET-status.test.js b/test/api/v3/integration/status/GET-status.test.js
index 38fbcb69dd..03c3eac4b5 100644
--- a/test/api/v3/integration/status/GET-status.test.js
+++ b/test/api/v3/integration/status/GET-status.test.js
@@ -4,7 +4,7 @@ import {
describe('GET /status', () => {
it('returns status: up', async () => {
- let res = await requester().get('/status');
+ const res = await requester().get('/status');
expect(res).to.eql({
status: 'up',
});
diff --git a/test/api/v3/integration/tags/DELETE-tags_id.test.js b/test/api/v3/integration/tags/DELETE-tags_id.test.js
index c03e8bb9e0..dc0f1be8ba 100644
--- a/test/api/v3/integration/tags/DELETE-tags_id.test.js
+++ b/test/api/v3/integration/tags/DELETE-tags_id.test.js
@@ -10,16 +10,14 @@ describe('DELETE /tags/:tagId', () => {
});
it('deletes a tag given it\'s id', async () => {
- let tagName = 'Tag 1';
- let tag = await user.post('/tags', {name: tagName});
- let numberOfTags = (await user.get('/tags')).length;
+ const tagName = 'Tag 1';
+ const tag = await user.post('/tags', { name: tagName });
+ const numberOfTags = (await user.get('/tags')).length;
await user.del(`/tags/${tag.id}`);
- let tags = await user.get('/tags');
- let tagNames = tags.map((t) => {
- return t.name;
- });
+ const tags = await user.get('/tags');
+ const tagNames = tags.map(t => t.name);
expect(tags.length).to.equal(numberOfTags - 1);
expect(tagNames).to.not.include(tagName);
diff --git a/test/api/v3/integration/tags/GET-tags.test.js b/test/api/v3/integration/tags/GET-tags.test.js
index ef080a2ee7..30d5ce5fec 100644
--- a/test/api/v3/integration/tags/GET-tags.test.js
+++ b/test/api/v3/integration/tags/GET-tags.test.js
@@ -12,10 +12,10 @@ describe('GET /tags', () => {
});
it('returns all user\'s tags', async () => {
- let tag1 = await user.post('/tags', {name: 'Tag 1'});
- let tag2 = await user.post('/tags', {name: 'Tag 2'});
+ const tag1 = await user.post('/tags', { name: 'Tag 1' });
+ const tag2 = await user.post('/tags', { name: 'Tag 2' });
- let tags = await user.get('/tags');
+ const tags = await user.get('/tags');
expect(tags.length).to.equal(2);
expect(tags[0].name).to.equal(tag1.name);
diff --git a/test/api/v3/integration/tags/GET-tags_id.test.js b/test/api/v3/integration/tags/GET-tags_id.test.js
index 4ab818593d..1b6e126e0a 100644
--- a/test/api/v3/integration/tags/GET-tags_id.test.js
+++ b/test/api/v3/integration/tags/GET-tags_id.test.js
@@ -10,8 +10,8 @@ describe('GET /tags/:tagId', () => {
});
it('returns a tag given it\'s id', async () => {
- let createdTag = await user.post('/tags', {name: 'Tag 1'});
- let tag = await user.get(`/tags/${createdTag.id}`);
+ const createdTag = await user.post('/tags', { name: 'Tag 1' });
+ const tag = await user.get(`/tags/${createdTag.id}`);
expect(tag).to.deep.equal(createdTag);
});
diff --git a/test/api/v3/integration/tags/POST-tag-reorder.test.js b/test/api/v3/integration/tags/POST-tag-reorder.test.js
index 5d12eb974f..bd5bb0daf7 100644
--- a/test/api/v3/integration/tags/POST-tag-reorder.test.js
+++ b/test/api/v3/integration/tags/POST-tag-reorder.test.js
@@ -22,7 +22,7 @@ describe('POST /reorder-tags', () => {
});
it('returns error when tag is not found', async () => {
- await expect(user.post('/reorder-tags', {tagId: 'fake-id', to: 3}))
+ await expect(user.post('/reorder-tags', { tagId: 'fake-id', to: 3 }))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
@@ -31,13 +31,13 @@ describe('POST /reorder-tags', () => {
});
it('updates tags', async () => {
- let tag1Name = 'Tag 1';
- let tag2Name = 'Tag 2';
- await user.post('/tags', {name: tag1Name});
- await user.post('/tags', {name: tag2Name});
+ const tag1Name = 'Tag 1';
+ const tag2Name = 'Tag 2';
+ await user.post('/tags', { name: tag1Name });
+ await user.post('/tags', { name: tag2Name });
await user.sync();
- await user.post('/reorder-tags', {tagId: user.tags[0].id, to: 1});
+ await user.post('/reorder-tags', { tagId: user.tags[0].id, to: 1 });
await user.sync();
expect(user.tags[0].name).to.equal(tag2Name);
diff --git a/test/api/v3/integration/tags/POST-tags.test.js b/test/api/v3/integration/tags/POST-tags.test.js
index 93f2dfdb60..5c9296fc7d 100644
--- a/test/api/v3/integration/tags/POST-tags.test.js
+++ b/test/api/v3/integration/tags/POST-tags.test.js
@@ -10,13 +10,13 @@ describe('POST /tags', () => {
});
it('creates a tag correctly', async () => {
- let tagName = 'Tag 1';
- let createdTag = await user.post('/tags', {
+ const tagName = 'Tag 1';
+ const createdTag = await user.post('/tags', {
name: tagName,
ignored: false,
});
- let tag = await user.get(`/tags/${createdTag.id}`);
+ const tag = await user.get(`/tags/${createdTag.id}`);
expect(tag.name).to.equal(tagName);
expect(tag.ignored).to.not.exist;
diff --git a/test/api/v3/integration/tags/PUT-tags_id.test.js b/test/api/v3/integration/tags/PUT-tags_id.test.js
index 4c16453ac3..409ae23318 100644
--- a/test/api/v3/integration/tags/PUT-tags_id.test.js
+++ b/test/api/v3/integration/tags/PUT-tags_id.test.js
@@ -10,9 +10,9 @@ describe('PUT /tags/:tagId', () => {
});
it('updates a tag given it\'s id', async () => {
- let updatedTagName = 'Tag updated';
- let createdTag = await user.post('/tags', {name: 'Tag 1'});
- let updatedTag = await user.put(`/tags/${createdTag.id}`, {
+ const updatedTagName = 'Tag updated';
+ let createdTag = await user.post('/tags', { name: 'Tag 1' });
+ const updatedTag = await user.put(`/tags/${createdTag.id}`, {
name: updatedTagName,
ignored: true,
});
diff --git a/test/api/v3/integration/tasks/DELETE-tasks_id.test.js b/test/api/v3/integration/tasks/DELETE-tasks_id.test.js
index fadf21973e..d1835ac022 100644
--- a/test/api/v3/integration/tasks/DELETE-tasks_id.test.js
+++ b/test/api/v3/integration/tasks/DELETE-tasks_id.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
@@ -6,7 +7,6 @@ import {
generateChallenge,
server,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:id', () => {
let user;
@@ -57,9 +57,9 @@ describe('DELETE /tasks/:id', () => {
});
it('sends task activity webhooks if task is user owned', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -78,20 +78,20 @@ describe('DELETE /tasks/:id', () => {
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('deleted');
expect(body.task).to.eql(task);
});
it('does not send task activity webhooks if task is not user owned', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.update({
balance: 10,
});
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post('/user/webhook', {
@@ -104,7 +104,7 @@ describe('DELETE /tasks/:id', () => {
},
});
- let challengeTask = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const challengeTask = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
});
@@ -113,7 +113,7 @@ describe('DELETE /tasks/:id', () => {
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body).to.not.exist;
});
@@ -129,8 +129,8 @@ describe('DELETE /tasks/:id', () => {
});
it('cannot delete a task owned by someone else', async () => {
- let anotherUser = await generateUser();
- let anotherUsersTask = await anotherUser.post('/tasks/user', {
+ const anotherUser = await generateUser();
+ const anotherUsersTask = await anotherUser.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -143,7 +143,7 @@ describe('DELETE /tasks/:id', () => {
});
it('removes a task from user.tasksOrder', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
diff --git a/test/api/v3/integration/tasks/GET-tasks_challenge_challengeId.test.js b/test/api/v3/integration/tasks/GET-tasks_challenge_challengeId.test.js
index b1865f8008..9a2a0eb40b 100644
--- a/test/api/v3/integration/tasks/GET-tasks_challenge_challengeId.test.js
+++ b/test/api/v3/integration/tasks/GET-tasks_challenge_challengeId.test.js
@@ -1,18 +1,18 @@
+import { each } from 'lodash';
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { each } from 'lodash';
-import { v4 as generateUUID } from 'uuid';
describe('GET /tasks/:taskId', () => {
let user;
let guild;
let challenge;
let task;
- let tasksToTest = {
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -58,12 +58,12 @@ describe('GET /tasks/:taskId', () => {
});
it('gets challenge task', async () => {
- let getTask = await user.get(`/tasks/${task._id}`);
+ const getTask = await user.get(`/tasks/${task._id}`);
expect(getTask).to.eql(task);
});
it('returns error when user is not a member of the challenge', async () => {
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/tasks/${task._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/tasks/GET-tasks_id.test.js b/test/api/v3/integration/tasks/GET-tasks_id.test.js
index 98c107d932..e46a08706c 100644
--- a/test/api/v3/integration/tasks/GET-tasks_id.test.js
+++ b/test/api/v3/integration/tasks/GET-tasks_id.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('GET /tasks/:id', () => {
let user;
@@ -23,13 +23,13 @@ describe('GET /tasks/:id', () => {
});
it('gets specified task', async () => {
- let getTask = await user.get(`/tasks/${task._id}`);
+ const getTask = await user.get(`/tasks/${task._id}`);
expect(getTask).to.eql(task);
});
it('can use alias to retrieve task', async () => {
- let getTask = await user.get(`/tasks/${task.alias}`);
+ const getTask = await user.get(`/tasks/${task.alias}`);
expect(getTask).to.eql(task);
});
@@ -40,7 +40,7 @@ describe('GET /tasks/:id', () => {
context('task cannot be accessed', () => {
it('cannot get a non-existant task', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/tasks/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -50,8 +50,8 @@ describe('GET /tasks/:id', () => {
});
it('cannot get a task owned by someone else', async () => {
- let anotherUser = await generateUser();
- let task = await user.post('/tasks/user', {
+ const anotherUser = await generateUser();
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
diff --git a/test/api/v3/integration/tasks/GET-tasks_user.test.js b/test/api/v3/integration/tasks/GET-tasks_user.test.js
index ea8f2a49d0..fa2cd94884 100644
--- a/test/api/v3/integration/tasks/GET-tasks_user.test.js
+++ b/test/api/v3/integration/tasks/GET-tasks_user.test.js
@@ -11,21 +11,21 @@ describe('GET /tasks/user', () => {
});
it('returns all user\'s tasks', async () => {
- let createdTasks = await user.post('/tasks/user', [{text: 'test habit', type: 'habit'}, {text: 'test todo', type: 'todo'}]);
- let tasks = await user.get('/tasks/user');
+ const createdTasks = await user.post('/tasks/user', [{ text: 'test habit', type: 'habit' }, { text: 'test todo', type: 'todo' }]);
+ const tasks = await user.get('/tasks/user');
expect(tasks.length).to.equal(createdTasks.length + 1); // Plus one for generated todo
});
it('returns only a type of user\'s tasks if req.query.type is specified', async () => {
- let createdTasks = await user.post('/tasks/user', [
- {text: 'test habit', type: 'habit'},
- {text: 'test daily', type: 'daily'},
- {text: 'test reward', type: 'reward'},
- {text: 'test todo', type: 'todo'},
+ const createdTasks = await user.post('/tasks/user', [
+ { text: 'test habit', type: 'habit' },
+ { text: 'test daily', type: 'daily' },
+ { text: 'test reward', type: 'reward' },
+ { text: 'test todo', type: 'todo' },
]);
- let habits = await user.get('/tasks/user?type=habits');
- let dailys = await user.get('/tasks/user?type=dailys');
- let rewards = await user.get('/tasks/user?type=rewards');
+ const habits = await user.get('/tasks/user?type=habits');
+ const dailys = await user.get('/tasks/user?type=dailys');
+ const rewards = await user.get('/tasks/user?type=rewards');
expect(habits.length).to.be.at.least(1);
expect(habits[0]._id).to.equal(createdTasks[0]._id);
@@ -36,28 +36,28 @@ describe('GET /tasks/user', () => {
});
it('returns uncompleted todos if req.query.type is "todos"', async () => {
- let existingTodos = await user.get('/tasks/user?type=todos');
+ const existingTodos = await user.get('/tasks/user?type=todos');
// populate user with other task types
await user.post('/tasks/user', [
- {text: 'daily', type: 'daily'},
- {text: 'reward', type: 'reward'},
- {text: 'habit', type: 'habit'},
+ { text: 'daily', type: 'daily' },
+ { text: 'reward', type: 'reward' },
+ { text: 'habit', type: 'habit' },
]);
- let newUncompletedTodos = await user.post('/tasks/user', [
- {text: 'test todo 1', type: 'todo'},
- {text: 'test todo 2', type: 'todo'},
+ const newUncompletedTodos = await user.post('/tasks/user', [
+ { text: 'test todo 1', type: 'todo' },
+ { text: 'test todo 2', type: 'todo' },
]);
- let todoToBeCompleted = await user.post('/tasks/user', {
+ const todoToBeCompleted = await user.post('/tasks/user', {
text: 'wll be completed todo', type: 'todo',
});
await user.post(`/tasks/${todoToBeCompleted._id}/score/up`);
- let uncompletedTodos = [...existingTodos, ...newUncompletedTodos];
+ const uncompletedTodos = [...existingTodos, ...newUncompletedTodos];
- let todos = await user.get('/tasks/user?type=todos');
+ const todos = await user.get('/tasks/user?type=todos');
expect(todos.length).to.be.gte(2);
expect(todos.length).to.eql(uncompletedTodos.length);
@@ -66,11 +66,11 @@ describe('GET /tasks/user', () => {
});
it('returns completed todos sorted by reverse completion date if req.query.type is "completedTodos"', async () => {
- let todo1 = await user.post('/tasks/user', {text: 'todo to complete 1', type: 'todo'});
- let todo2 = await user.post('/tasks/user', {text: 'todo to complete 2', type: 'todo'});
+ const todo1 = await user.post('/tasks/user', { text: 'todo to complete 1', type: 'todo' });
+ const todo2 = await user.post('/tasks/user', { text: 'todo to complete 2', type: 'todo' });
await user.sync();
- let initialTodoCount = user.tasksOrder.todos.length;
+ const initialTodoCount = user.tasksOrder.todos.length;
await user.post(`/tasks/${todo2._id}/score/up`);
await user.post(`/tasks/${todo1._id}/score/up`);
@@ -78,17 +78,17 @@ describe('GET /tasks/user', () => {
expect(user.tasksOrder.todos.length).to.equal(initialTodoCount - 2);
- let completedTodos = await user.get('/tasks/user?type=completedTodos');
+ const completedTodos = await user.get('/tasks/user?type=completedTodos');
expect(completedTodos.length).to.equal(2);
expect(completedTodos[completedTodos.length - 1].text).to.equal('todo to complete 2'); // last is the todo that was completed most recently
});
it('returns completed todos sorted by reverse completion date if req.query.type is "_allCompletedTodos"', async () => {
- let todo1 = await user.post('/tasks/user', {text: 'todo to complete 1', type: 'todo'});
- let todo2 = await user.post('/tasks/user', {text: 'todo to complete 2', type: 'todo'});
+ const todo1 = await user.post('/tasks/user', { text: 'todo to complete 1', type: 'todo' });
+ const todo2 = await user.post('/tasks/user', { text: 'todo to complete 2', type: 'todo' });
await user.sync();
- let initialTodoCount = user.tasksOrder.todos.length;
+ const initialTodoCount = user.tasksOrder.todos.length;
await user.post(`/tasks/${todo2._id}/score/up`);
await user.post(`/tasks/${todo1._id}/score/up`);
@@ -96,25 +96,25 @@ describe('GET /tasks/user', () => {
expect(user.tasksOrder.todos.length).to.equal(initialTodoCount - 2);
- let allCompletedTodos = await user.get('/tasks/user?type=_allCompletedTodos');
+ const allCompletedTodos = await user.get('/tasks/user?type=_allCompletedTodos');
expect(allCompletedTodos.length).to.equal(2);
expect(allCompletedTodos[allCompletedTodos.length - 1].text).to.equal('todo to complete 2');
});
it('returns only some completed todos if req.query.type is "completedTodos" or "_allCompletedTodos"', async () => {
const LIMIT = 30;
- let numberOfTodos = LIMIT + 1;
- let todosInput = [];
+ const numberOfTodos = LIMIT + 1;
+ const todosInput = [];
- for (let i = 0; i < numberOfTodos; i++) {
- todosInput[i] = {text: 'todo to complete ${i}', type: 'todo'};
+ for (let i = 0; i < numberOfTodos; i += 1) {
+ todosInput[i] = { text: `todo to complete ${i}`, type: 'todo' };
}
- let todos = await user.post('/tasks/user', todosInput);
+ const todos = await user.post('/tasks/user', todosInput);
await user.sync();
- let initialTodoCount = user.tasksOrder.todos.length;
+ const initialTodoCount = user.tasksOrder.todos.length;
- for (let i = 0; i < numberOfTodos; i++) {
- let id = todos[i]._id;
+ for (let i = 0; i < numberOfTodos; i += 1) {
+ const id = todos[i]._id;
await user.post(`/tasks/${id}/score/up`); // eslint-disable-line no-await-in-loop
}
@@ -122,17 +122,17 @@ describe('GET /tasks/user', () => {
expect(user.tasksOrder.todos.length).to.equal(initialTodoCount - numberOfTodos);
- let completedTodos = await user.get('/tasks/user?type=completedTodos');
+ const completedTodos = await user.get('/tasks/user?type=completedTodos');
expect(completedTodos.length).to.equal(LIMIT);
- let allCompletedTodos = await user.get('/tasks/user?type=_allCompletedTodos');
+ const allCompletedTodos = await user.get('/tasks/user?type=_allCompletedTodos');
expect(allCompletedTodos.length).to.equal(numberOfTodos);
});
it('returns dailies with isDue for the date specified', async () => {
// @TODO Add required format
- let startDate = moment().subtract('1', 'days').toISOString();
- let createdTasks = await user.post('/tasks/user', [
+ const startDate = moment().subtract('1', 'days').toISOString();
+ const createdTasks = await user.post('/tasks/user', [
{
text: 'test daily',
type: 'daily',
@@ -141,24 +141,25 @@ describe('GET /tasks/user', () => {
everyX: 2,
},
]);
- let dailys = await user.get('/tasks/user?type=dailys');
+ const dailys = await user.get('/tasks/user?type=dailys');
expect(dailys.length).to.be.at.least(1);
expect(dailys[0]._id).to.equal(createdTasks._id);
expect(dailys[0].isDue).to.be.false;
- let dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${startDate}`);
+ const dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${startDate}`);
expect(dailys2[0]._id).to.equal(createdTasks._id);
expect(dailys2[0].isDue).to.be.true;
});
xit('returns dailies with isDue for the date specified and will add CDS offset if time is not supplied and assumes timezones', async () => {
- let timezone = 420;
+ const timezone = 420;
await user.update({
'preferences.dayStart': 0,
'preferences.timezoneOffset': timezone,
});
- let startDate = moment().zone(timezone).subtract('4', 'days').startOf('day').toISOString();
+ const startDate = moment().zone(timezone).subtract('4', 'days').startOf('day')
+ .toISOString();
await user.post('/tasks/user', [
{
text: 'test daily',
@@ -169,23 +170,24 @@ describe('GET /tasks/user', () => {
},
]);
- let today = moment().format('YYYY-MM-DD');
- let dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
+ const today = moment().format('YYYY-MM-DD');
+ const dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
expect(dailys[0].isDue).to.be.true;
- let yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
- let dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
+ const yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
+ const dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
expect(dailys2[0].isDue).to.be.false;
});
xit('returns dailies with isDue for the date specified and will add CDS offset if time is not supplied and assumes timezones', async () => {
- let timezone = 240;
+ const timezone = 240;
await user.update({
'preferences.dayStart': 0,
'preferences.timezoneOffset': timezone,
});
- let startDate = moment().zone(timezone).subtract('4', 'days').startOf('day').toISOString();
+ const startDate = moment().zone(timezone).subtract('4', 'days').startOf('day')
+ .toISOString();
await user.post('/tasks/user', [
{
text: 'test daily',
@@ -196,22 +198,23 @@ describe('GET /tasks/user', () => {
},
]);
- let today = moment().format('YYYY-MM-DD');
- let dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
+ const today = moment().format('YYYY-MM-DD');
+ const dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
expect(dailys[0].isDue).to.be.true;
- let yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
- let dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
+ const yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
+ const dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
expect(dailys2[0].isDue).to.be.false;
});
xit('returns dailies with isDue for the date specified and will add CDS offset if time is not supplied and assumes timezones', async () => {
- let timezone = 540;
+ const timezone = 540;
await user.update({
'preferences.dayStart': 0,
'preferences.timezoneOffset': timezone,
});
- let startDate = moment().zone(timezone).subtract('4', 'days').startOf('day').toISOString();
+ const startDate = moment().zone(timezone).subtract('4', 'days').startOf('day')
+ .toISOString();
await user.post('/tasks/user', [
{
text: 'test daily',
@@ -222,12 +225,12 @@ describe('GET /tasks/user', () => {
},
]);
- let today = moment().format('YYYY-MM-DD');
- let dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
+ const today = moment().format('YYYY-MM-DD');
+ const dailys = await user.get(`/tasks/user?type=dailys&dueDate=${today}`);
expect(dailys[0].isDue).to.be.true;
- let yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
- let dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
+ const yesterday = moment().subtract('1', 'days').format('YYYY-MM-DD');
+ const dailys2 = await user.get(`/tasks/user?type=dailys&dueDate=${yesterday}`);
expect(dailys2[0].isDue).to.be.false;
});
});
diff --git a/test/api/v3/integration/tasks/POST-tasks_clearCompletedTodos.test.js b/test/api/v3/integration/tasks/POST-tasks_clearCompletedTodos.test.js
index 2014b1c65c..f3328fbb64 100644
--- a/test/api/v3/integration/tasks/POST-tasks_clearCompletedTodos.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_clearCompletedTodos.test.js
@@ -6,18 +6,18 @@ import {
describe('POST /tasks/clearCompletedTodos', () => {
it('deletes all completed todos except the ones from a challenge and group', async () => {
- let user = await generateUser({balance: 1});
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const user = await generateUser({ balance: 1 });
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
- let initialTodoCount = user.tasksOrder.todos.length;
+ const initialTodoCount = user.tasksOrder.todos.length;
await user.post('/tasks/user', [
- {text: 'todo 1', type: 'todo'},
- {text: 'todo 2', type: 'todo'},
- {text: 'todo 3', type: 'todo'},
- {text: 'todo 4', type: 'todo'},
- {text: 'todo 5', type: 'todo'},
+ { text: 'todo 1', type: 'todo' },
+ { text: 'todo 2', type: 'todo' },
+ { text: 'todo 3', type: 'todo' },
+ { text: 'todo 4', type: 'todo' },
+ { text: 'todo 5', type: 'todo' },
]);
await user.post(`/tasks/challenge/${challenge._id}`, {
@@ -25,26 +25,27 @@ describe('POST /tasks/clearCompletedTodos', () => {
type: 'todo',
});
- let groupTask = await user.post(`/tasks/group/${guild._id}`, {
+ const groupTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'todo 7',
type: 'todo',
});
await user.post(`/tasks/${groupTask._id}/assign/${user._id}`);
- let tasks = await user.get('/tasks/user?type=todos');
+ const tasks = await user.get('/tasks/user?type=todos');
expect(tasks.length).to.equal(initialTodoCount + 7);
- for (let task of tasks) {
+ for (const task of tasks) { // eslint-disable-line
if (['todo 2', 'todo 3', 'todo 6'].indexOf(task.text) !== -1) {
await user.post(`/tasks/${task._id}/score/up`); // eslint-disable-line no-await-in-loop
}
}
await user.post('/tasks/clearCompletedTodos');
- let completedTodos = await user.get('/tasks/user?type=completedTodos');
- let todos = await user.get('/tasks/user?type=todos');
- let allTodos = todos.concat(completedTodos);
- expect(allTodos.length).to.equal(initialTodoCount + 5); // + 7 - 3 completed (but one is from challenge)
+ const completedTodos = await user.get('/tasks/user?type=completedTodos');
+ const todos = await user.get('/tasks/user?type=todos');
+ const allTodos = todos.concat(completedTodos);
+ // + 7 - 3 completed (but one is from challenge)
+ expect(allTodos.length).to.equal(initialTodoCount + 5);
expect(allTodos[allTodos.length - 1].text).to.equal('todo 6'); // last completed todo
});
});
diff --git a/test/api/v3/integration/tasks/POST-tasks_id_score_direction.test.js b/test/api/v3/integration/tasks/POST-tasks_id_score_direction.test.js
index c34b94ed05..bdfc00fce0 100644
--- a/test/api/v3/integration/tasks/POST-tasks_id_score_direction.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_id_score_direction.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
sleep,
translate as t,
server,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:id/score/:direction', () => {
let user;
@@ -17,25 +17,25 @@ describe('POST /tasks/:id/score/:direction', () => {
context('all', () => {
it('can use an id to identify the task', async () => {
- let todo = await user.post('/tasks/user', {
+ const todo = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
alias: 'alias',
});
- let res = await user.post(`/tasks/${todo._id}/score/up`);
+ const res = await user.post(`/tasks/${todo._id}/score/up`);
expect(res).to.be.ok;
});
it('can use a alias in place of the id', async () => {
- let todo = await user.post('/tasks/user', {
+ const todo = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
alias: 'alias',
});
- let res = await user.post(`/tasks/${todo.alias}/score/up`);
+ const res = await user.post(`/tasks/${todo.alias}/score/up`);
expect(res).to.be.ok;
});
@@ -49,7 +49,7 @@ describe('POST /tasks/:id/score/:direction', () => {
});
it('sends task scored webhooks', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await server.start();
await user.post('/user/webhook', {
@@ -62,7 +62,7 @@ describe('POST /tasks/:id/score/:direction', () => {
},
});
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -73,7 +73,7 @@ describe('POST /tasks/:id/score/:direction', () => {
await server.close();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.user).to.have.all.keys('_id', '_tmp', 'stats');
expect(body.user.stats).to.have.all.keys('hp', 'mp', 'exp', 'gp', 'lvl', 'class', 'points', 'str', 'con', 'int', 'per', 'buffs', 'training', 'maxHealth', 'maxMP', 'toNextLevel');
@@ -92,7 +92,7 @@ describe('POST /tasks/:id/score/:direction', () => {
});
it('sends user activity webhook when the user levels up', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -108,7 +108,7 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.update({
'stats.exp': 3000,
});
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -117,7 +117,7 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.sync();
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('leveledUp');
expect(body.initialLvl).to.eql(initialLvl);
@@ -138,44 +138,45 @@ describe('POST /tasks/:id/score/:direction', () => {
it('completes todo when direction is up', async () => {
await user.post(`/tasks/${todo._id}/score/up`);
- let task = await user.get(`/tasks/${todo._id}`);
+ const task = await user.get(`/tasks/${todo._id}`);
expect(task.completed).to.equal(true);
expect(task.dateCompleted).to.be.a('string'); // date gets converted to a string as json doesn't have a Date type
});
it('moves completed todos out of user.tasksOrder.todos', async () => {
- let getUser = await user.get('/user');
+ const getUser = await user.get('/user');
expect(getUser.tasksOrder.todos.indexOf(todo._id)).to.not.equal(-1);
await user.post(`/tasks/${todo._id}/score/up`);
- let updatedTask = await user.get(`/tasks/${todo._id}`);
+ const updatedTask = await user.get(`/tasks/${todo._id}`);
expect(updatedTask.completed).to.equal(true);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.todos.indexOf(todo._id)).to.equal(-1);
});
it('moves un-completed todos back into user.tasksOrder.todos', async () => {
- let getUser = await user.get('/user');
+ const getUser = await user.get('/user');
expect(getUser.tasksOrder.todos.indexOf(todo._id)).to.not.equal(-1);
await user.post(`/tasks/${todo._id}/score/up`);
await user.post(`/tasks/${todo._id}/score/down`);
- let updatedTask = await user.get(`/tasks/${todo._id}`);
+ const updatedTask = await user.get(`/tasks/${todo._id}`);
expect(updatedTask.completed).to.equal(false);
- let updatedUser = await user.get('/user');
- let l = updatedUser.tasksOrder.todos.length;
+ const updatedUser = await user.get('/user');
+ const l = updatedUser.tasksOrder.todos.length;
expect(updatedUser.tasksOrder.todos.indexOf(todo._id)).not.to.equal(-1);
- expect(updatedUser.tasksOrder.todos.indexOf(todo._id)).to.equal(l - 1); // Check that it was pushed at the bottom
+ // Check that it was pushed at the bottom
+ expect(updatedUser.tasksOrder.todos.indexOf(todo._id)).to.equal(l - 1);
});
it('uncompletes todo when direction is down', async () => {
await user.post(`/tasks/${todo._id}/score/up`);
await user.post(`/tasks/${todo._id}/score/down`);
- let updatedTask = await user.get(`/tasks/${todo._id}`);
+ const updatedTask = await user.get(`/tasks/${todo._id}`);
expect(updatedTask.completed).to.equal(false);
expect(updatedTask.dateCompleted).to.be.a('undefined');
@@ -221,7 +222,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
context('user stats when direction is down', () => {
- let updatedUser, initialUser;
+ let updatedUser; let
+ initialUser;
beforeEach(async () => {
await user.post(`/tasks/${todo._id}/score/up`);
@@ -256,7 +258,7 @@ describe('POST /tasks/:id/score/:direction', () => {
it('completes daily when direction is up', async () => {
await user.post(`/tasks/${daily._id}/score/up`);
- let task = await user.get(`/tasks/${daily._id}`);
+ const task = await user.get(`/tasks/${daily._id}`);
expect(task.completed).to.equal(true);
});
@@ -264,21 +266,21 @@ describe('POST /tasks/:id/score/:direction', () => {
it('uncompletes daily when direction is down', async () => {
await user.post(`/tasks/${daily._id}/score/up`);
await user.post(`/tasks/${daily._id}/score/down`);
- let task = await user.get(`/tasks/${daily._id}`);
+ const task = await user.get(`/tasks/${daily._id}`);
expect(task.completed).to.equal(false);
});
it('computes isDue', async () => {
await user.post(`/tasks/${daily._id}/score/up`);
- let task = await user.get(`/tasks/${daily._id}`);
+ const task = await user.get(`/tasks/${daily._id}`);
expect(task.isDue).to.equal(true);
});
it('computes nextDue', async () => {
await user.post(`/tasks/${daily._id}/score/up`);
- let task = await user.get(`/tasks/${daily._id}`);
+ const task = await user.get(`/tasks/${daily._id}`);
expect(task.nextDue.length).to.eql(6);
});
@@ -322,7 +324,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
context('user stats when direction is down', () => {
- let updatedUser, initialUser;
+ let updatedUser; let
+ initialUser;
beforeEach(async () => {
await user.post(`/tasks/${daily._id}/score/up`);
@@ -346,7 +349,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
context('habits', () => {
- let habit, minusHabit, plusHabit, neitherHabit; // eslint-disable-line no-unused-vars
+ let habit; let
+ neitherHabit; // eslint-disable-line no-unused-vars
beforeEach(async () => {
habit = await user.post('/tasks/user', {
@@ -354,18 +358,6 @@ describe('POST /tasks/:id/score/:direction', () => {
type: 'habit',
});
- minusHabit = await user.post('/tasks/user', {
- text: 'test min habit',
- type: 'habit',
- up: false,
- });
-
- plusHabit = await user.post('/tasks/user', {
- text: 'test plus habit',
- type: 'habit',
- down: false,
- });
-
neitherHabit = await user.post('/tasks/user', {
text: 'test neither habit',
type: 'habit',
@@ -380,40 +372,40 @@ describe('POST /tasks/:id/score/:direction', () => {
it('increases user\'s mp when direction is up', async () => {
await user.post(`/tasks/${habit._id}/score/up`);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.stats.mp).to.be.greaterThan(user.stats.mp);
});
it('decreases user\'s mp when direction is down', async () => {
await user.post(`/tasks/${habit._id}/score/down`);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.stats.mp).to.be.lessThan(user.stats.mp);
});
it('increases user\'s exp when direction is up', async () => {
await user.post(`/tasks/${habit._id}/score/up`);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.stats.exp).to.be.greaterThan(user.stats.exp);
});
it('increases user\'s gold when direction is up', async () => {
await user.post(`/tasks/${habit._id}/score/up`);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.stats.gp).to.be.greaterThan(user.stats.gp);
});
// not supported anymore
it('does not add score notes to task', async () => {
- let scoreNotesString = 'test-notes';
+ const scoreNotesString = 'test-notes';
await user.post(`/tasks/${habit._id}/score/up`, {
scoreNotes: scoreNotesString,
});
- let updatedTask = await user.get(`/tasks/${habit._id}`);
+ const updatedTask = await user.get(`/tasks/${habit._id}`);
expect(updatedTask.history[0].scoreNotes).to.eql(undefined);
});
@@ -437,7 +429,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
context('reward', () => {
- let reward, updatedUser;
+ let reward; let
+ updatedUser;
beforeEach(async () => {
reward = await user.post('/tasks/user', {
diff --git a/test/api/v3/integration/tasks/POST-tasks_move_taskId_to_position.test.js b/test/api/v3/integration/tasks/POST-tasks_move_taskId_to_position.test.js
index 2b17cd3919..b14085fb75 100644
--- a/test/api/v3/integration/tasks/POST-tasks_move_taskId_to_position.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_move_taskId_to_position.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:taskId/move/to/:position', () => {
let user;
@@ -28,20 +28,20 @@ describe('POST /tasks/:taskId/move/to/:position', () => {
});
it('can move task to new position', async () => {
- let tasks = await user.post('/tasks/user', [
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2'},
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 3'},
- {type: 'habit', text: 'habit 4'},
- {type: 'todo', text: 'todo 1'},
- {type: 'habit', text: 'habit 5'},
+ const tasks = await user.post('/tasks/user', [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 3' },
+ { type: 'habit', text: 'habit 4' },
+ { type: 'todo', text: 'todo 1' },
+ { type: 'habit', text: 'habit 5' },
]);
- let taskToMove = tasks[1];
+ const taskToMove = tasks[1];
expect(taskToMove.text).to.equal('habit 2');
- let newOrder = await user.post(`/tasks/${tasks[1]._id}/move/to/3`);
+ const newOrder = await user.post(`/tasks/${tasks[1]._id}/move/to/3`);
await user.sync();
expect(newOrder[3]).to.equal(taskToMove._id);
@@ -50,25 +50,25 @@ describe('POST /tasks/:taskId/move/to/:position', () => {
});
it('can move task to new position using alias', async () => {
- let tasks = await user.post('/tasks/user', [
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2', alias: 'move'},
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 3'},
- {type: 'habit', text: 'habit 4'},
- {type: 'todo', text: 'todo 1'},
- {type: 'habit', text: 'habit 5'},
+ const tasks = await user.post('/tasks/user', [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2', alias: 'move' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 3' },
+ { type: 'habit', text: 'habit 4' },
+ { type: 'todo', text: 'todo 1' },
+ { type: 'habit', text: 'habit 5' },
]);
- let taskToMove = tasks[1];
+ const taskToMove = tasks[1];
expect(taskToMove.text).to.equal('habit 2');
- let newOrder = await user.post(`/tasks/${taskToMove.alias}/move/to/3`);
+ const newOrder = await user.post(`/tasks/${taskToMove.alias}/move/to/3`);
expect(newOrder[3]).to.equal(taskToMove._id);
expect(newOrder.length).to.equal(5);
});
it('can\'t move completed todo', async () => {
- let task = await user.post('/tasks/user', {type: 'todo', text: 'todo 1'});
+ const task = await user.post('/tasks/user', { type: 'todo', text: 'todo 1' });
await user.post(`/tasks/${task._id}/score/up`);
await expect(user.post(`/tasks/${task._id}/move/to/1`)).to.eventually.be.rejected.and.eql({
@@ -79,19 +79,19 @@ describe('POST /tasks/:taskId/move/to/:position', () => {
});
it('can push to bottom', async () => {
- let tasks = await user.post('/tasks/user', [
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2'},
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 3'},
- {type: 'habit', text: 'habit 4'},
- {type: 'todo', text: 'todo 1'},
- {type: 'habit', text: 'habit 5'},
+ const tasks = await user.post('/tasks/user', [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 3' },
+ { type: 'habit', text: 'habit 4' },
+ { type: 'todo', text: 'todo 1' },
+ { type: 'habit', text: 'habit 5' },
]);
- let taskToMove = tasks[1];
+ const taskToMove = tasks[1];
expect(taskToMove.text).to.equal('habit 2');
- let newOrder = await user.post(`/tasks/${tasks[1]._id}/move/to/-1`);
+ const newOrder = await user.post(`/tasks/${tasks[1]._id}/move/to/-1`);
expect(newOrder[4]).to.equal(taskToMove._id);
expect(newOrder.length).to.equal(5);
});
diff --git a/test/api/v3/integration/tasks/POST-tasks_unlink-all_challengeId.test.js b/test/api/v3/integration/tasks/POST-tasks_unlink-all_challengeId.test.js
index c1dfd6a522..86715bd6dc 100644
--- a/test/api/v3/integration/tasks/POST-tasks_unlink-all_challengeId.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_unlink-all_challengeId.test.js
@@ -9,7 +9,7 @@ describe('POST /tasks/unlink-all/:challengeId', () => {
let user;
let guild;
let challenge;
- let tasksToTest = {
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
diff --git a/test/api/v3/integration/tasks/POST-tasks_unlink-one_taskId.test.js b/test/api/v3/integration/tasks/POST-tasks_unlink-one_taskId.test.js
index aefc379865..e8ee1f2727 100644
--- a/test/api/v3/integration/tasks/POST-tasks_unlink-one_taskId.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_unlink-one_taskId.test.js
@@ -1,16 +1,16 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/unlink-one/:taskId', () => {
let user;
let guild;
let challenge;
- let tasksToTest = {
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -70,7 +70,7 @@ describe('POST /tasks/unlink-one/:taskId', () => {
});
it('fails on task unlinked to challenge', async () => {
- let daily = await user.post('/tasks/user', tasksToTest.daily);
+ const daily = await user.post('/tasks/user', tasksToTest.daily);
await expect(user.post(`/tasks/unlink-one/${daily._id}?keep=keep`))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -81,7 +81,7 @@ describe('POST /tasks/unlink-one/:taskId', () => {
it('fails on unbroken challenge', async () => {
await user.post(`/tasks/challenge/${challenge._id}`, tasksToTest.daily);
- let [daily] = await user.get('/tasks/user');
+ const [daily] = await user.get('/tasks/user');
await expect(user.post(`/tasks/unlink-one/${daily._id}?keep=keep`))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -101,11 +101,11 @@ describe('POST /tasks/unlink-one/:taskId', () => {
it('unlinks a task from a challenge and deletes it on keep=remove', async () => {
await user.post(`/tasks/challenge/${challenge._id}`, tasksToTest.daily);
- let [, daily] = await user.get('/tasks/user');
+ const [, daily] = await user.get('/tasks/user');
await user.del(`/challenges/${challenge._id}`);
await user.post(`/tasks/unlink-one/${daily._id}?keep=remove`);
const tasks = await user.get('/tasks/user');
// Only the default task should remain
expect(tasks.length).to.eql(1);
});
-});
\ No newline at end of file
+});
diff --git a/test/api/v3/integration/tasks/POST-tasks_user.test.js b/test/api/v3/integration/tasks/POST-tasks_user.test.js
index 22297da8ff..af08c21961 100644
--- a/test/api/v3/integration/tasks/POST-tasks_user.test.js
+++ b/test/api/v3/integration/tasks/POST-tasks_user.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
sleep,
translate as t,
server,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/user', () => {
let user;
@@ -36,8 +36,8 @@ describe('POST /tasks/user', () => {
it('returns an error if one object inside an array is invalid', async () => {
await expect(user.post('/tasks/user', [
- {type: 'habitF'},
- {type: 'habit'},
+ { type: 'habitF' },
+ { type: 'habit' },
])).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
@@ -56,7 +56,7 @@ describe('POST /tasks/user', () => {
});
it('does not update user.tasksOrder.{taskType} when the task is not saved because invalid', async () => {
- let originalHabitsOrder = (await user.get('/user')).tasksOrder.habits;
+ const originalHabitsOrder = (await user.get('/user')).tasksOrder.habits;
await expect(user.post('/tasks/user', {
type: 'habit',
})).to.eventually.be.rejected.and.eql({
@@ -65,43 +65,43 @@ describe('POST /tasks/user', () => {
message: 'habit validation failed',
});
- let updatedHabitsOrder = (await user.get('/user')).tasksOrder.habits;
+ const updatedHabitsOrder = (await user.get('/user')).tasksOrder.habits;
expect(updatedHabitsOrder).to.eql(originalHabitsOrder);
});
it('does not update user.tasksOrder.{taskType} when a task inside an array is not saved because invalid', async () => {
- let originalHabitsOrder = (await user.get('/user')).tasksOrder.habits;
+ const originalHabitsOrder = (await user.get('/user')).tasksOrder.habits;
await expect(user.post('/tasks/user', [
- {type: 'habit'}, // Missing text
- {type: 'habit', text: 'valid'}, // Valid
+ { type: 'habit' }, // Missing text
+ { type: 'habit', text: 'valid' }, // Valid
])).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'habit validation failed',
});
- let updatedHabitsOrder = (await user.get('/user')).tasksOrder.habits;
+ const updatedHabitsOrder = (await user.get('/user')).tasksOrder.habits;
expect(updatedHabitsOrder).to.eql(originalHabitsOrder);
});
it('does not save any task sent in an array when 1 is invalid', async () => {
- let originalTasks = await user.get('/tasks/user');
+ const originalTasks = await user.get('/tasks/user');
await expect(user.post('/tasks/user', [
- {type: 'habit'}, // Missing text
- {type: 'habit', text: 'valid'}, // Valid
+ { type: 'habit' }, // Missing text
+ { type: 'habit', text: 'valid' }, // Valid
])).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'habit validation failed',
}).then(async () => {
- let updatedTasks = await user.get('/tasks/user');
+ const updatedTasks = await user.get('/tasks/user');
expect(updatedTasks).to.eql(originalTasks);
});
});
it('automatically sets "task.userId" to user\'s uuid', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -112,7 +112,7 @@ describe('POST /tasks/user', () => {
it(`ignores setting userId, history, createdAt,
updatedAt, challenge, completed,
dateCompleted fields`, async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
userId: 123,
@@ -137,7 +137,7 @@ describe('POST /tasks/user', () => {
});
it('ignores invalid fields', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
notValid: true,
@@ -218,7 +218,7 @@ describe('POST /tasks/user', () => {
});
it('sends task activity webhooks', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -229,20 +229,20 @@ describe('POST /tasks/user', () => {
},
});
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.task).to.eql(task);
});
it('sends a task activity webhook for each task', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -253,7 +253,7 @@ describe('POST /tasks/user', () => {
},
});
- let tasks = await user.post('/tasks/user', [{
+ const tasks = await user.post('/tasks/user', [{
text: 'test habit',
type: 'habit',
}, {
@@ -263,7 +263,7 @@ describe('POST /tasks/user', () => {
await sleep();
- let taskBodies = [
+ const taskBodies = [
server.getWebhookData(uuid),
server.getWebhookData(uuid),
];
@@ -275,13 +275,13 @@ describe('POST /tasks/user', () => {
context('all types', () => {
it('can create reminders', async () => {
- let id1 = generateUUID();
+ const id1 = generateUUID();
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
reminders: [
- {id: id1, startDate: new Date(), time: new Date()},
+ { id: id1, startDate: new Date(), time: new Date() },
],
});
@@ -294,7 +294,7 @@ describe('POST /tasks/user', () => {
});
it('can create a task with a alias', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
alias: 'a_alias012',
@@ -305,7 +305,7 @@ describe('POST /tasks/user', () => {
// This is a special case for iOS requests
it('will round a priority (difficulty)', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
priority: 0.10000000000005,
@@ -317,7 +317,7 @@ describe('POST /tasks/user', () => {
context('habits', () => {
it('creates a habit', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
up: false,
@@ -334,20 +334,20 @@ describe('POST /tasks/user', () => {
});
it('updates user.tasksOrder.habits when a new habit is created', async () => {
- let originalHabitsOrderLen = (await user.get('/user')).tasksOrder.habits.length;
- let task = await user.post('/tasks/user', {
+ const originalHabitsOrderLen = (await user.get('/user')).tasksOrder.habits.length;
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'an habit',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.habits[0]).to.eql(task._id);
expect(updatedUser.tasksOrder.habits.length).to.eql(originalHabitsOrderLen + 1);
});
it('updates user.tasksOrder.habits when multiple habits are created', async () => {
- let originalHabitsOrderLen = (await user.get('/user')).tasksOrder.habits.length;
- let [task, task2] = await user.post('/tasks/user', [{
+ const originalHabitsOrderLen = (await user.get('/user')).tasksOrder.habits.length;
+ const [task, task2] = await user.post('/tasks/user', [{
type: 'habit',
text: 'an habit',
}, {
@@ -355,14 +355,14 @@ describe('POST /tasks/user', () => {
text: 'another habit',
}]);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.habits[0]).to.eql(task2._id);
expect(updatedUser.tasksOrder.habits[1]).to.eql(task._id);
expect(updatedUser.tasksOrder.habits.length).to.eql(originalHabitsOrderLen + 2);
});
it('creates multiple habits', async () => {
- let [task, task2] = await user.post('/tasks/user', [{
+ const [task, task2] = await user.post('/tasks/user', [{
text: 'test habit',
type: 'habit',
up: false,
@@ -392,7 +392,7 @@ describe('POST /tasks/user', () => {
});
it('defaults to setting up and down to true', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
notes: 1976,
@@ -403,11 +403,11 @@ describe('POST /tasks/user', () => {
});
it('cannot create checklists', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
checklist: [
- {_id: 123, completed: false, text: 'checklist'},
+ { _id: 123, completed: false, text: 'checklist' },
],
});
@@ -417,7 +417,7 @@ describe('POST /tasks/user', () => {
context('todos', () => {
it('creates a todo', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
notes: 1976,
@@ -430,7 +430,7 @@ describe('POST /tasks/user', () => {
});
it('creates multiple todos', async () => {
- let [task, task2] = await user.post('/tasks/user', [{
+ const [task, task2] = await user.post('/tasks/user', [{
text: 'test todo',
type: 'todo',
notes: 1976,
@@ -452,20 +452,20 @@ describe('POST /tasks/user', () => {
});
it('updates user.tasksOrder.todos when a new todo is created', async () => {
- let originalTodosOrderLen = (await user.get('/user')).tasksOrder.todos.length;
- let task = await user.post('/tasks/user', {
+ const originalTodosOrderLen = (await user.get('/user')).tasksOrder.todos.length;
+ const task = await user.post('/tasks/user', {
type: 'todo',
text: 'a todo',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.todos[0]).to.eql(task._id);
expect(updatedUser.tasksOrder.todos.length).to.eql(originalTodosOrderLen + 1);
});
it('updates user.tasksOrder.todos when multiple todos are created', async () => {
- let originalTodosOrderLen = (await user.get('/user')).tasksOrder.todos.length;
- let [task, task2] = await user.post('/tasks/user', [{
+ const originalTodosOrderLen = (await user.get('/user')).tasksOrder.todos.length;
+ const [task, task2] = await user.post('/tasks/user', [{
type: 'todo',
text: 'a todo',
}, {
@@ -473,18 +473,18 @@ describe('POST /tasks/user', () => {
text: 'another todo',
}]);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.todos[0]).to.eql(task2._id);
expect(updatedUser.tasksOrder.todos[1]).to.eql(task._id);
expect(updatedUser.tasksOrder.todos.length).to.eql(originalTodosOrderLen + 2);
});
it('can create checklists', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
checklist: [
- {completed: false, text: 'checklist'},
+ { completed: false, text: 'checklist' },
],
});
@@ -499,9 +499,9 @@ describe('POST /tasks/user', () => {
context('dailys', () => {
it('creates a daily', async () => {
- let now = new Date();
+ const now = new Date();
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
notes: 1976,
@@ -526,7 +526,7 @@ describe('POST /tasks/user', () => {
});
it('creates multiple dailys', async () => {
- let [task, task2] = await user.post('/tasks/user', [{
+ const [task, task2] = await user.post('/tasks/user', [{
text: 'test daily',
type: 'daily',
notes: 1976,
@@ -548,20 +548,20 @@ describe('POST /tasks/user', () => {
});
it('updates user.tasksOrder.dailys when a new daily is created', async () => {
- let originalDailysOrderLen = (await user.get('/user')).tasksOrder.dailys.length;
- let task = await user.post('/tasks/user', {
+ const originalDailysOrderLen = (await user.get('/user')).tasksOrder.dailys.length;
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'a daily',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.dailys[0]).to.eql(task._id);
expect(updatedUser.tasksOrder.dailys.length).to.eql(originalDailysOrderLen + 1);
});
it('updates user.tasksOrder.dailys when multiple dailys are created', async () => {
- let originalDailysOrderLen = (await user.get('/user')).tasksOrder.dailys.length;
- let [task, task2] = await user.post('/tasks/user', [{
+ const originalDailysOrderLen = (await user.get('/user')).tasksOrder.dailys.length;
+ const [task, task2] = await user.post('/tasks/user', [{
type: 'daily',
text: 'a daily',
}, {
@@ -569,14 +569,14 @@ describe('POST /tasks/user', () => {
text: 'another daily',
}]);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.dailys[0]).to.eql(task2._id);
expect(updatedUser.tasksOrder.dailys[1]).to.eql(task._id);
expect(updatedUser.tasksOrder.dailys.length).to.eql(originalDailysOrderLen + 2);
});
it('defaults to a weekly frequency, with every day set', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
});
@@ -595,7 +595,7 @@ describe('POST /tasks/user', () => {
});
it('allows repeat field to be configured', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
repeat: {
@@ -617,9 +617,9 @@ describe('POST /tasks/user', () => {
});
it('defaults startDate to today', async () => {
- let today = (new Date()).getDay();
+ const today = (new Date()).getDay();
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
});
@@ -677,11 +677,11 @@ describe('POST /tasks/user', () => {
it('can create checklists', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
checklist: [
- {completed: false, text: 'checklist'},
+ { completed: false, text: 'checklist' },
],
});
@@ -696,7 +696,7 @@ describe('POST /tasks/user', () => {
context('rewards', () => {
it('creates a reward', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
notes: 1976,
@@ -711,7 +711,7 @@ describe('POST /tasks/user', () => {
});
it('creates multiple rewards', async () => {
- let [task, task2] = await user.post('/tasks/user', [{
+ const [task, task2] = await user.post('/tasks/user', [{
text: 'test reward',
type: 'reward',
notes: 1976,
@@ -737,20 +737,20 @@ describe('POST /tasks/user', () => {
});
it('updates user.tasksOrder.rewards when a new reward is created', async () => {
- let originalRewardsOrderLen = (await user.get('/user')).tasksOrder.rewards.length;
- let task = await user.post('/tasks/user', {
+ const originalRewardsOrderLen = (await user.get('/user')).tasksOrder.rewards.length;
+ const task = await user.post('/tasks/user', {
type: 'reward',
text: 'a reward',
});
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.rewards[0]).to.eql(task._id);
expect(updatedUser.tasksOrder.rewards.length).to.eql(originalRewardsOrderLen + 1);
});
it('updates user.tasksOrder.dreward when multiple rewards are created', async () => {
- let originalRewardsOrderLen = (await user.get('/user')).tasksOrder.rewards.length;
- let [task, task2] = await user.post('/tasks/user', [{
+ const originalRewardsOrderLen = (await user.get('/user')).tasksOrder.rewards.length;
+ const [task, task2] = await user.post('/tasks/user', [{
type: 'reward',
text: 'a reward',
}, {
@@ -758,14 +758,14 @@ describe('POST /tasks/user', () => {
text: 'another reward',
}]);
- let updatedUser = await user.get('/user');
+ const updatedUser = await user.get('/user');
expect(updatedUser.tasksOrder.rewards[0]).to.eql(task2._id);
expect(updatedUser.tasksOrder.rewards[1]).to.eql(task._id);
expect(updatedUser.tasksOrder.rewards.length).to.eql(originalRewardsOrderLen + 2);
});
it('defaults to a 0 value', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
});
@@ -774,7 +774,7 @@ describe('POST /tasks/user', () => {
});
it('requires value to be coerced into a number', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
value: '10',
@@ -784,11 +784,11 @@ describe('POST /tasks/user', () => {
});
it('cannot create checklists', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
checklist: [
- {_id: 123, completed: false, text: 'checklist'},
+ { _id: 123, completed: false, text: 'checklist' },
],
});
diff --git a/test/api/v3/integration/tasks/PUT-tasks_id.test.js b/test/api/v3/integration/tasks/PUT-tasks_id.test.js
index ad1555237c..1ad083e50e 100644
--- a/test/api/v3/integration/tasks/PUT-tasks_id.test.js
+++ b/test/api/v3/integration/tasks/PUT-tasks_id.test.js
@@ -1,4 +1,5 @@
import moment from 'moment';
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
@@ -6,7 +7,6 @@ import {
generateChallenge,
server,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT /tasks/:id', () => {
let user;
@@ -28,7 +28,7 @@ describe('PUT /tasks/:id', () => {
it(`ignores setting _id, type, userId, history, createdAt,
updatedAt, challenge, completed, streak,
dateCompleted fields`, async () => {
- let savedTask = await user.put(`/tasks/${task._id}`, {
+ const savedTask = await user.put(`/tasks/${task._id}`, {
_id: 123,
type: 'daily',
userId: 123,
@@ -54,7 +54,7 @@ describe('PUT /tasks/:id', () => {
});
it('ignores invalid fields', async () => {
- let savedTask = await user.put(`/tasks/${task._id}`, {
+ const savedTask = await user.put(`/tasks/${task._id}`, {
notValid: true,
});
@@ -63,18 +63,18 @@ describe('PUT /tasks/:id', () => {
it(`only allows setting streak, alias, reminders, checklist, notes, attribute, tags
fields for challenge tasks owned by a user`, async () => {
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
- let challengeTask = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const challengeTask = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily in challenge',
reminders: [
- {time: new Date(), startDate: new Date()},
+ { time: new Date(), startDate: new Date() },
],
checklist: [
- {text: 123, completed: false},
+ { text: 123, completed: false },
],
collapseChecklist: false,
});
@@ -83,11 +83,11 @@ describe('PUT /tasks/:id', () => {
await user.sync();
// Pick challenge task
- let challengeUserTaskId = user.tasksOrder.dailys[user.tasksOrder.dailys.length - 1];
+ const challengeUserTaskId = user.tasksOrder.dailys[user.tasksOrder.dailys.length - 1];
- let challengeUserTask = await user.get(`/tasks/${challengeUserTaskId}`);
+ const challengeUserTask = await user.get(`/tasks/${challengeUserTaskId}`);
- let savedChallengeUserTask = await user.put(`/tasks/${challengeUserTaskId}`, {
+ const savedChallengeUserTask = await user.put(`/tasks/${challengeUserTaskId}`, {
_id: 123,
type: 'daily',
userId: 123,
@@ -107,12 +107,12 @@ describe('PUT /tasks/:id', () => {
text: 'new text',
dateCompleted: 'never',
reminders: [
- {time: new Date(), startDate: new Date()},
- {time: new Date(), startDate: new Date()},
+ { time: new Date(), startDate: new Date() },
+ { time: new Date(), startDate: new Date() },
],
checklist: [
- {text: 123, completed: false},
- {text: 456, completed: true},
+ { text: 123, completed: false },
+ { text: 456, completed: true },
],
collapseChecklist: true,
notes: 'new notes',
@@ -121,7 +121,7 @@ describe('PUT /tasks/:id', () => {
});
// original task is not touched
- let updatedChallengeTask = await user.get(`/tasks/${challengeTask._id}`);
+ const updatedChallengeTask = await user.get(`/tasks/${challengeTask._id}`);
expect(updatedChallengeTask).to.eql(challengeTask);
// ignored
@@ -134,7 +134,8 @@ describe('PUT /tasks/:id', () => {
expect(savedChallengeUserTask.text).to.equal(challengeUserTask.text);
expect(savedChallengeUserTask.history).to.eql(challengeUserTask.history);
expect(savedChallengeUserTask.createdAt).to.equal(challengeUserTask.createdAt);
- expect(new Date(savedChallengeUserTask.updatedAt)).to.be.greaterThan(new Date(challengeUserTask.updatedAt));
+ expect(new Date(savedChallengeUserTask.updatedAt))
+ .to.be.greaterThan(new Date(challengeUserTask.updatedAt));
expect(savedChallengeUserTask.challenge).to.eql(challengeUserTask.challenge);
expect(savedChallengeUserTask.completed).to.equal(challengeUserTask.completed);
expect(savedChallengeUserTask.dateCompleted).to.equal(challengeUserTask.dateCompleted);
@@ -162,7 +163,7 @@ describe('PUT /tasks/:id', () => {
});
it('sends task activity webhooks if task is user owned', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -174,31 +175,31 @@ describe('PUT /tasks/:id', () => {
},
});
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
- let updatedTask = await user.put(`/tasks/${task.id}`, {
+ const updatedTask = await user.put(`/tasks/${task.id}`, {
text: 'updated text',
});
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('updated');
expect(body.task).to.eql(updatedTask);
});
it('does not send task activity webhooks if task is not user owned', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.update({
balance: 10,
});
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post('/user/webhook', {
@@ -211,7 +212,7 @@ describe('PUT /tasks/:id', () => {
},
});
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
});
@@ -222,7 +223,7 @@ describe('PUT /tasks/:id', () => {
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body).to.not.exist;
});
@@ -242,17 +243,17 @@ describe('PUT /tasks/:id', () => {
it('can update reminders (replace them)', async () => {
await user.put(`/tasks/${daily._id}`, {
reminders: [
- {time: new Date(), startDate: new Date()},
+ { time: new Date(), startDate: new Date() },
],
});
- let id1 = generateUUID();
- let id2 = generateUUID();
+ const id1 = generateUUID();
+ const id2 = generateUUID();
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
reminders: [
- {id: id1, time: new Date(), startDate: new Date()},
- {id: id2, time: new Date(), startDate: new Date()},
+ { id: id1, time: new Date(), startDate: new Date() },
+ { id: id2, time: new Date(), startDate: new Date() },
],
});
@@ -262,7 +263,7 @@ describe('PUT /tasks/:id', () => {
});
it('can set a alias if no other task has that alias', async () => {
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
alias: 'alias',
});
@@ -294,7 +295,7 @@ describe('PUT /tasks/:id', () => {
text: 'saved',
});
- let fetchedDaily = await user.get(`/tasks/${daily._id}`);
+ const fetchedDaily = await user.get(`/tasks/${daily._id}`);
expect(fetchedDaily.text).to.eql('saved');
});
@@ -322,7 +323,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a habit', async () => {
- let savedHabit = await user.put(`/tasks/${habit._id}`, {
+ const savedHabit = await user.put(`/tasks/${habit._id}`, {
text: 'some new text',
up: false,
down: false,
@@ -348,7 +349,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a todo', async () => {
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
text: 'some new text',
notes: 'some new notes',
});
@@ -360,14 +361,14 @@ describe('PUT /tasks/:id', () => {
it('can update checklists (replace it)', async () => {
await user.put(`/tasks/${todo._id}`, {
checklist: [
- {text: 123, completed: false},
- {text: 456, completed: true},
+ { text: 123, completed: false },
+ { text: 456, completed: true },
],
});
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
checklist: [
- {text: 789, completed: false},
+ { text: 789, completed: false },
],
});
@@ -377,12 +378,12 @@ describe('PUT /tasks/:id', () => {
});
it('can update tags (replace them)', async () => {
- let finalUUID = generateUUID();
+ const finalUUID = generateUUID();
await user.put(`/tasks/${todo._id}`, {
tags: [generateUUID(), generateUUID()],
});
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
tags: [finalUUID],
});
@@ -403,7 +404,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a daily', async () => {
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
text: 'some new text',
notes: 'some new notes',
frequency: 'daily',
@@ -424,14 +425,14 @@ describe('PUT /tasks/:id', () => {
it('can update checklists (replace it)', async () => {
await user.put(`/tasks/${daily._id}`, {
checklist: [
- {text: 123, completed: false},
- {text: 456, completed: true},
+ { text: 123, completed: false },
+ { text: 456, completed: true },
],
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
checklist: [
- {text: 789, completed: false},
+ { text: 789, completed: false },
],
});
@@ -441,12 +442,12 @@ describe('PUT /tasks/:id', () => {
});
it('can update tags (replace them)', async () => {
- let finalUUID = generateUUID();
+ const finalUUID = generateUUID();
await user.put(`/tasks/${daily._id}`, {
tags: [generateUUID(), generateUUID()],
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
tags: [finalUUID],
});
@@ -459,7 +460,7 @@ describe('PUT /tasks/:id', () => {
frequency: 'daily',
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
repeat: {
m: false,
su: false,
@@ -482,7 +483,7 @@ describe('PUT /tasks/:id', () => {
frequency: 'weekly',
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
everyX: 5,
});
@@ -490,7 +491,7 @@ describe('PUT /tasks/:id', () => {
});
it('defaults startDate to today if none date object is passed in', async () => {
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
frequency: 'weekly',
});
@@ -511,7 +512,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a reward', async () => {
- let savedReward = await user.put(`/tasks/${reward._id}`, {
+ const savedReward = await user.put(`/tasks/${reward._id}`, {
text: 'some new text',
notes: 'some new notes',
value: 10,
@@ -523,7 +524,7 @@ describe('PUT /tasks/:id', () => {
});
it('requires value to be coerced into a number', async () => {
- let savedReward = await user.put(`/tasks/${reward._id}`, {
+ const savedReward = await user.put(`/tasks/${reward._id}`, {
value: '100',
});
diff --git a/test/api/v3/integration/tasks/challenges/DELETE-tasks_challenge_challengeId_checklist_itemId.test.js b/test/api/v3/integration/tasks/challenges/DELETE-tasks_challenge_challengeId_checklist_itemId.test.js
index 5cdbce319b..02c66a0139 100644
--- a/test/api/v3/integration/tasks/challenges/DELETE-tasks_challenge_challengeId_checklist_itemId.test.js
+++ b/test/api/v3/integration/tasks/challenges/DELETE-tasks_challenge_challengeId_checklist_itemId.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
let user;
@@ -27,7 +27,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const createdTask = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'daily with checklist',
});
@@ -40,17 +40,17 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('returns error when user is not a member of the challenge', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
completed: false,
});
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.del(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`))
.to.eventually.be.rejected.and.eql({
@@ -61,12 +61,12 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('deletes a checklist item from a daily', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {text: 'Checklist Item 1', completed: false});
+ let savedTask = await user.post(`/tasks/${task._id}/checklist`, { text: 'Checklist Item 1', completed: false });
await user.del(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`);
savedTask = await user.get(`/tasks/${task._id}`);
@@ -75,12 +75,12 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('deletes a checklist item from a todo', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'todo',
text: 'Todo with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {text: 'Checklist Item 1', completed: false});
+ let savedTask = await user.post(`/tasks/${task._id}/checklist`, { text: 'Checklist Item 1', completed: false });
await user.del(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`);
savedTask = await user.get(`/tasks/${task._id}`);
@@ -89,7 +89,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with habits', async () => {
- let habit = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const habit = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'habit',
text: 'habit with checklist',
});
@@ -102,7 +102,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with rewards', async () => {
- let reward = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const reward = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'reward',
text: 'reward with checklist',
});
diff --git a/test/api/v3/integration/tasks/challenges/DELETE-tasks_id_challenge_challengeId.test.js b/test/api/v3/integration/tasks/challenges/DELETE-tasks_id_challenge_challengeId.test.js
index 44478e67b6..14245c3e54 100644
--- a/test/api/v3/integration/tasks/challenges/DELETE-tasks_id_challenge_challengeId.test.js
+++ b/test/api/v3/integration/tasks/challenges/DELETE-tasks_id_challenge_challengeId.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
@@ -5,7 +6,6 @@ import {
sleep,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:id', () => {
let user;
@@ -36,7 +36,7 @@ describe('DELETE /tasks/:id', () => {
});
it('returns error when user is not leader of the challenge', async () => {
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.del(`/tasks/${task._id}`)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -71,8 +71,9 @@ describe('DELETE /tasks/:id', () => {
type: 'habit',
});
- let anotherUserWithNewChallengeTask = await anotherUser.get('/user');
- anotherUsersNewChallengeTaskID = anotherUserWithNewChallengeTask.tasksOrder.habits[0];
+ const anotherUserWithNewChallengeTask = await anotherUser.get('/user');
+ anotherUsersNewChallengeTaskID = anotherUserWithNewChallengeTask // eslint-disable-line prefer-destructuring, max-len
+ .tasksOrder.habits[0];
});
it('returns error when user attempts to delete an active challenge task', async () => {
@@ -96,7 +97,8 @@ describe('DELETE /tasks/:id', () => {
});
});
- // TODO for some reason this test fails on TravisCI, review after mongodb indexes have been added
+ // TODO for some reason this test fails on TravisCI,
+ // review after mongodb indexes have been added
xit('allows user to delete challenge task after challenge task is broken', async () => {
await expect(user.del(`/tasks/${newChallengeTask._id}`));
diff --git a/test/api/v3/integration/tasks/challenges/GET_tasks_challenge.id.test.js b/test/api/v3/integration/tasks/challenges/GET_tasks_challenge.id.test.js
index 8947db4929..9765ec05a3 100644
--- a/test/api/v3/integration/tasks/challenges/GET_tasks_challenge.id.test.js
+++ b/test/api/v3/integration/tasks/challenges/GET_tasks_challenge.id.test.js
@@ -1,20 +1,20 @@
+import { v4 as generateUUID } from 'uuid';
+import { each } from 'lodash';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import { each } from 'lodash';
describe('GET /tasks/challenge/:challengeId', () => {
let user;
let guild;
let challenge;
let task;
- let tasks = [];
+ const tasks = [];
let challengeWithTask;
- let tasksToTest = {
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -46,7 +46,7 @@ describe('GET /tasks/challenge/:challengeId', () => {
});
it('returns error when challenge is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/tasks/challenge/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -64,17 +64,17 @@ describe('GET /tasks/challenge/:challengeId', () => {
});
it('gets challenge tasks', async () => {
- let getTask = await user.get(`/tasks/challenge/${challengeWithTask._id}`);
+ const getTask = await user.get(`/tasks/challenge/${challengeWithTask._id}`);
expect(getTask).to.eql(tasks);
});
it('gets challenge tasks filtered by type', async () => {
- let challengeTasks = await user.get(`/tasks/challenge/${challengeWithTask._id}?type=${task.type}s`);
+ const challengeTasks = await user.get(`/tasks/challenge/${challengeWithTask._id}?type=${task.type}s`);
expect(challengeTasks).to.eql([task]);
});
it('cannot get a task owned by someone else', async () => {
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/tasks/challenge/${challengeWithTask._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_challengeId_taskId_checklist.test.js b/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_challengeId_taskId_checklist.test.js
index fcf4323f8f..a8e249d4cc 100644
--- a/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_challengeId_taskId_checklist.test.js
+++ b/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_challengeId_taskId_checklist.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:taskId/checklist/', () => {
let user;
@@ -29,12 +29,12 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('returns error when user is not a member of the challenge', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily with checklist',
});
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
@@ -49,12 +49,12 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('adds a checklist item to a daily', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
ignored: false,
_id: 123,
@@ -69,12 +69,12 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('adds a checklist item to a todo', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'todo',
text: 'Todo with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
ignored: false,
_id: 123,
@@ -89,7 +89,7 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to habits', async () => {
- let habit = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const habit = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'habit',
text: 'habit with checklist',
});
@@ -104,7 +104,7 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to rewards', async () => {
- let reward = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const reward = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'reward',
text: 'reward with checklist',
});
diff --git a/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_id.test.js b/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_id.test.js
index 54c99ac964..f458d97e46 100644
--- a/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_id.test.js
+++ b/test/api/v3/integration/tasks/challenges/POST-tasks_challenge_id.test.js
@@ -1,11 +1,11 @@
+import { v4 as generateUUID } from 'uuid';
+import { find } from 'lodash';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import { find } from 'lodash';
describe('POST /tasks/challenge/:challengeId', () => {
let user;
@@ -17,14 +17,14 @@ describe('POST /tasks/challenge/:challengeId', () => {
}
beforeEach(async () => {
- user = await generateUser({balance: 1});
+ user = await generateUser({ balance: 1 });
guild = await generateGroup(user);
challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
});
it('returns error when challenge is not found', async () => {
- let fakeChallengeId = generateUUID();
+ const fakeChallengeId = generateUUID();
await expect(user.post(`/tasks/challenge/${fakeChallengeId}`, {
text: 'test habit',
@@ -41,7 +41,7 @@ describe('POST /tasks/challenge/:challengeId', () => {
it('allows leader to add tasks to a challenge when not a member', async () => {
await user.post(`/challenges/${challenge._id}/leave`);
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
up: false,
@@ -49,14 +49,14 @@ describe('POST /tasks/challenge/:challengeId', () => {
notes: 1976,
});
- let {tasksOrder} = await user.get(`/challenges/${challenge._id}`);
+ const { tasksOrder } = await user.get(`/challenges/${challenge._id}`);
expect(tasksOrder.habits).to.include(task.id);
});
it('allows non-leader admin to add tasks to a challenge when not a member', async () => {
- const admin = await generateUser({'contributor.admin': true});
- let task = await admin.post(`/tasks/challenge/${challenge._id}`, {
+ const admin = await generateUser({ 'contributor.admin': true });
+ const task = await admin.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit from admin',
type: 'habit',
up: false,
@@ -64,7 +64,7 @@ describe('POST /tasks/challenge/:challengeId', () => {
notes: 1976,
});
- let {tasksOrder} = await user.get(`/challenges/${challenge._id}`);
+ const { tasksOrder } = await user.get(`/challenges/${challenge._id}`);
expect(tasksOrder.habits).to.include(task.id);
});
@@ -82,7 +82,7 @@ describe('POST /tasks/challenge/:challengeId', () => {
});
it('returns error when non leader tries to edit challenge', async () => {
- let userThatIsNotLeaderOfChallenge = await generateUser({
+ const userThatIsNotLeaderOfChallenge = await generateUser({
challenges: [challenge._id],
});
@@ -100,17 +100,17 @@ describe('POST /tasks/challenge/:challengeId', () => {
});
it('creates a habit', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
up: false,
down: true,
notes: 1976,
});
- let challengeWithTask = await user.get(`/challenges/${challenge._id}`);
+ const challengeWithTask = await user.get(`/challenges/${challenge._id}`);
- let memberTasks = await user.get('/tasks/user');
- let userChallengeTask = find(memberTasks, findUserChallengeTask);
+ const memberTasks = await user.get('/tasks/user');
+ const userChallengeTask = find(memberTasks, findUserChallengeTask);
expect(challengeWithTask.tasksOrder.habits.indexOf(task._id)).to.be.above(-1);
expect(task.challenge.id).to.equal(challenge._id);
@@ -124,15 +124,15 @@ describe('POST /tasks/challenge/:challengeId', () => {
});
it('creates a todo', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test todo',
type: 'todo',
notes: 1976,
});
- let challengeWithTask = await user.get(`/challenges/${challenge._id}`);
+ const challengeWithTask = await user.get(`/challenges/${challenge._id}`);
- let memberTasks = await user.get('/tasks/user');
- let userChallengeTask = find(memberTasks, findUserChallengeTask);
+ const memberTasks = await user.get('/tasks/user');
+ const userChallengeTask = find(memberTasks, findUserChallengeTask);
expect(challengeWithTask.tasksOrder.todos.indexOf(task._id)).to.be.above(-1);
expect(task.challenge.id).to.equal(challenge._id);
@@ -144,8 +144,8 @@ describe('POST /tasks/challenge/:challengeId', () => {
});
it('creates a daily', async () => {
- let now = new Date();
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const now = new Date();
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test daily',
type: 'daily',
notes: 1976,
@@ -153,10 +153,10 @@ describe('POST /tasks/challenge/:challengeId', () => {
everyX: 5,
startDate: now,
});
- let challengeWithTask = await user.get(`/challenges/${challenge._id}`);
+ const challengeWithTask = await user.get(`/challenges/${challenge._id}`);
- let memberTasks = await user.get('/tasks/user');
- let userChallengeTask = find(memberTasks, findUserChallengeTask);
+ const memberTasks = await user.get('/tasks/user');
+ const userChallengeTask = find(memberTasks, findUserChallengeTask);
expect(challengeWithTask.tasksOrder.dailys.indexOf(task._id)).to.be.above(-1);
expect(task.challenge.id).to.equal(challenge._id);
diff --git a/test/api/v3/integration/tasks/challenges/POST-tasks_challenges_challengeId_tasks_id_score_direction.test.js b/test/api/v3/integration/tasks/challenges/POST-tasks_challenges_challengeId_tasks_id_score_direction.test.js
index d65b931056..59b37f2b50 100644
--- a/test/api/v3/integration/tasks/challenges/POST-tasks_challenges_challengeId_tasks_id_score_direction.test.js
+++ b/test/api/v3/integration/tasks/challenges/POST-tasks_challenges_challengeId_tasks_id_score_direction.test.js
@@ -1,10 +1,10 @@
+import { find } from 'lodash';
import {
generateUser,
generateGroup,
generateChallenge,
sleep,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /tasks/:id/score/:direction', () => {
let user;
@@ -29,16 +29,16 @@ describe('POST /tasks/:id/score/:direction', () => {
type: 'habit',
});
await sleep(1);
- let updatedUser = await user.get('/user');
- usersChallengeTaskId = updatedUser.tasksOrder.habits[0];
+ const updatedUser = await user.get('/user');
+ usersChallengeTaskId = updatedUser.tasksOrder.habits[0]; // eslint-disable-line prefer-destructuring, max-len
});
it('scores and adds history', async () => {
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: habit._id});
- previousTaskHistory = task.history[0];
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: habit._id });
+ previousTaskHistory = task.history[0]; // eslint-disable-line prefer-destructuring, max-len
expect(task.value).to.equal(1);
expect(task.history).to.have.lengthOf(1);
@@ -47,8 +47,8 @@ describe('POST /tasks/:id/score/:direction', () => {
it('should update the history', async () => {
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: habit._id});
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: habit._id });
expect(task.history).to.have.lengthOf(1);
expect(task.history[0].date).to.not.equal(previousTaskHistory.date);
@@ -67,23 +67,23 @@ describe('POST /tasks/:id/score/:direction', () => {
type: 'daily',
});
await sleep(1);
- let updatedUser = await user.get('/user');
- usersChallengeTaskId = updatedUser.tasksOrder.dailys[0];
+ const updatedUser = await user.get('/user');
+ usersChallengeTaskId = updatedUser.tasksOrder.dailys[0]; // eslint-disable-line prefer-destructuring, max-len
});
it('it scores and adds history', async () => {
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: daily._id});
- previousTaskHistory = task.history[0];
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: daily._id });
+ previousTaskHistory = task.history[0]; // eslint-disable-line prefer-destructuring
expect(task.history).to.have.lengthOf(1);
expect(task.value).to.equal(1);
});
it('should update the history', async () => {
- let newCron = new Date(2015, 11, 20);
+ const newCron = new Date(2015, 11, 20);
await user.post('/debug/set-cron', {
lastCron: newCron,
@@ -92,8 +92,8 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post('/cron');
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: daily._id});
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: daily._id });
expect(task.history).to.have.lengthOf(1);
expect(task.history[0].date).to.not.equal(previousTaskHistory.date);
@@ -111,15 +111,15 @@ describe('POST /tasks/:id/score/:direction', () => {
type: 'todo',
});
await sleep(1);
- let updatedUser = await user.get('/user');
- usersChallengeTaskId = updatedUser.tasksOrder.todos[0];
+ const updatedUser = await user.get('/user');
+ usersChallengeTaskId = updatedUser.tasksOrder.todos[0]; // eslint-disable-line prefer-destructuring, max-len
});
it('scores but does not add history', async () => {
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: todo._id});
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: todo._id });
expect(task.history).to.not.exist;
expect(task.value).to.equal(1);
@@ -136,15 +136,15 @@ describe('POST /tasks/:id/score/:direction', () => {
type: 'reward',
});
await sleep(1);
- let updatedUser = await user.get('/user');
- usersChallengeTaskId = updatedUser.tasksOrder.todos[0];
+ const updatedUser = await user.get('/user');
+ usersChallengeTaskId = updatedUser.tasksOrder.todos[0]; // eslint-disable-line prefer-destructuring, max-len
});
it('does not score', async () => {
await user.post(`/tasks/${usersChallengeTaskId}/score/up`);
- let tasks = await user.get(`/tasks/challenge/${challenge._id}`);
- let task = find(tasks, {_id: reward._id});
+ const tasks = await user.get(`/tasks/challenge/${challenge._id}`);
+ const task = find(tasks, { _id: reward._id });
expect(task.history).to.not.exist;
expect(task.value).to.equal(0);
diff --git a/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId.test.js b/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId.test.js
index 2a5fe64d25..d7ee94728c 100644
--- a/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId.test.js
+++ b/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT /tasks/:id', () => {
let user;
@@ -42,7 +42,7 @@ describe('PUT /tasks/:id', () => {
});
it('returns error when user is not a member of the challenge', async () => {
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.put(`/tasks/${task._id}`, {
text: 'some new text',
@@ -80,7 +80,7 @@ describe('PUT /tasks/:id', () => {
it(`ignores setting _id, type, userId, history, createdAt,
updatedAt, challenge, completed, streak,
dateCompleted fields`, async () => {
- let savedTask = await user.put(`/tasks/${task._id}`, {
+ const savedTask = await user.put(`/tasks/${task._id}`, {
_id: 123,
type: 'daily',
userId: 123,
@@ -108,7 +108,7 @@ describe('PUT /tasks/:id', () => {
});
it('ignores invalid fields', async () => {
- let savedTask = await user.put(`/tasks/${task._id}`, {
+ const savedTask = await user.put(`/tasks/${task._id}`, {
notValid: true,
});
@@ -128,7 +128,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a habit', async () => {
- let savedHabit = await user.put(`/tasks/${habit._id}`, {
+ const savedHabit = await user.put(`/tasks/${habit._id}`, {
text: 'some new text',
up: false,
down: false,
@@ -171,7 +171,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a todo', async () => {
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
text: 'some new text',
notes: 'some new notes',
});
@@ -183,14 +183,14 @@ describe('PUT /tasks/:id', () => {
it('can update checklists (replace it)', async () => {
await user.put(`/tasks/${todo._id}`, {
checklist: [
- {text: 123, completed: false},
- {text: 456, completed: true},
+ { text: 123, completed: false },
+ { text: 456, completed: true },
],
});
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
checklist: [
- {text: 789, completed: false},
+ { text: 789, completed: false },
],
});
@@ -200,12 +200,12 @@ describe('PUT /tasks/:id', () => {
});
it('can update tags (replace them)', async () => {
- let finalUUID = generateUUID();
+ const finalUUID = generateUUID();
await user.put(`/tasks/${todo._id}`, {
tags: [generateUUID(), generateUUID()],
});
- let savedTodo = await user.put(`/tasks/${todo._id}`, {
+ const savedTodo = await user.put(`/tasks/${todo._id}`, {
tags: [finalUUID],
});
@@ -226,7 +226,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a daily', async () => {
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
text: 'some new text',
notes: 'some new notes',
frequency: 'daily',
@@ -242,14 +242,14 @@ describe('PUT /tasks/:id', () => {
it('can update checklists (replace it)', async () => {
await user.put(`/tasks/${daily._id}`, {
checklist: [
- {text: 123, completed: false},
- {text: 456, completed: true},
+ { text: 123, completed: false },
+ { text: 456, completed: true },
],
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
checklist: [
- {text: 789, completed: false},
+ { text: 789, completed: false },
],
});
@@ -259,12 +259,12 @@ describe('PUT /tasks/:id', () => {
});
it('can update tags (replace them)', async () => {
- let finalUUID = generateUUID();
+ const finalUUID = generateUUID();
await user.put(`/tasks/${daily._id}`, {
tags: [generateUUID(), generateUUID()],
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
tags: [finalUUID],
});
@@ -277,7 +277,7 @@ describe('PUT /tasks/:id', () => {
frequency: 'daily',
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
repeat: {
m: false,
su: false,
@@ -300,7 +300,7 @@ describe('PUT /tasks/:id', () => {
frequency: 'weekly',
});
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
everyX: 5,
});
@@ -308,7 +308,7 @@ describe('PUT /tasks/:id', () => {
});
it('defaults startDate to today if none date object is passed in', async () => {
- let savedDaily = await user.put(`/tasks/${daily._id}`, {
+ const savedDaily = await user.put(`/tasks/${daily._id}`, {
frequency: 'weekly',
});
@@ -329,7 +329,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a reward', async () => {
- let savedReward = await user.put(`/tasks/${reward._id}`, {
+ const savedReward = await user.put(`/tasks/${reward._id}`, {
text: 'some new text',
notes: 'some new notes',
value: 11,
@@ -341,7 +341,7 @@ describe('PUT /tasks/:id', () => {
});
it('requires value to be coerced into a number', async () => {
- let savedReward = await user.put(`/tasks/${reward._id}`, {
+ const savedReward = await user.put(`/tasks/${reward._id}`, {
value: '100',
});
diff --git a/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId_tasksId_checklist_itemId.test.js b/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId_tasksId_checklist_itemId.test.js
index 19e72e9617..5e8a45dc9f 100644
--- a/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId_tasksId_checklist_itemId.test.js
+++ b/test/api/v3/integration/tasks/challenges/PUT-tasks_challenge_challengeId_tasksId_checklist_itemId.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT /tasks/:taskId/checklist/:itemId', () => {
let user;
@@ -19,7 +19,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on task not found', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'todo',
text: 'Todo with checklist',
});
@@ -37,17 +37,17 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('returns error when user is not a member of the challenge', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'todo',
text: 'Todo with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
completed: false,
});
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.put(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`, {
text: 'updated',
@@ -62,7 +62,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('updates a checklist item on dailies', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'daily',
text: 'Daily with checklist',
});
@@ -85,7 +85,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('updates a checklist item on todos', async () => {
- let task = await user.post(`/tasks/challenge/${challenge._id}`, {
+ const task = await user.post(`/tasks/challenge/${challenge._id}`, {
type: 'todo',
text: 'Todo with checklist',
});
@@ -108,7 +108,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on habits', async () => {
- let habit = await user.post('/tasks/user', {
+ const habit = await user.post('/tasks/user', {
type: 'habit',
text: 'habit with checklist',
});
@@ -121,7 +121,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on rewards', async () => {
- let reward = await user.post('/tasks/user', {
+ const reward = await user.post('/tasks/user', {
type: 'reward',
text: 'reward with checklist',
});
@@ -142,7 +142,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post('/tasks/user', {
+ const createdTask = await user.post('/tasks/user', {
type: 'daily',
text: 'daily with checklist',
});
diff --git a/test/api/v3/integration/tasks/checklists/DELETE-tasks_taskId_checklist_itemId.test.js b/test/api/v3/integration/tasks/checklists/DELETE-tasks_taskId_checklist_itemId.test.js
index 940a3479b1..2016454178 100644
--- a/test/api/v3/integration/tasks/checklists/DELETE-tasks_taskId_checklist_itemId.test.js
+++ b/test/api/v3/integration/tasks/checklists/DELETE-tasks_taskId_checklist_itemId.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
let user;
@@ -12,12 +12,12 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('deletes a checklist item', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {text: 'Checklist Item 1', completed: false});
+ let savedTask = await user.post(`/tasks/${task._id}/checklist`, { text: 'Checklist Item 1', completed: false });
await user.del(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`);
savedTask = await user.get(`/tasks/${task._id}`);
@@ -26,13 +26,13 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('deletes a checklist item using task alias', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
alias: 'daily-with-alias',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {text: 'Checklist Item 1', completed: false});
+ let savedTask = await user.post(`/tasks/${task._id}/checklist`, { text: 'Checklist Item 1', completed: false });
await user.del(`/tasks/${task.alias}/checklist/${savedTask.checklist[0].id}`);
savedTask = await user.get(`/tasks/${task._id}`);
@@ -41,7 +41,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with habits', async () => {
- let habit = await user.post('/tasks/user', {
+ const habit = await user.post('/tasks/user', {
type: 'habit',
text: 'habit with checklist',
});
@@ -54,7 +54,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with rewards', async () => {
- let reward = await user.post('/tasks/user', {
+ const reward = await user.post('/tasks/user', {
type: 'reward',
text: 'reward with checklist',
});
@@ -75,7 +75,7 @@ describe('DELETE /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post('/tasks/user', {
+ const createdTask = await user.post('/tasks/user', {
type: 'daily',
text: 'daily with checklist',
});
diff --git a/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist.test.js b/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist.test.js
index 488e0005d9..80bb5377e4 100644
--- a/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist.test.js
+++ b/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:taskId/checklist/', () => {
let user;
@@ -12,12 +12,12 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('adds a checklist item to a task', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task._id}/checklist`, {
text: 'Checklist Item 1',
ignored: false,
_id: 123,
@@ -32,13 +32,13 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('can use a alias to add checklist', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
alias: 'task-with-shortname',
});
- let savedTask = await user.post(`/tasks/${task.alias}/checklist`, {
+ const savedTask = await user.post(`/tasks/${task.alias}/checklist`, {
text: 'Checklist Item 1',
ignored: false,
_id: 123,
@@ -53,7 +53,7 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to habits', async () => {
- let habit = await user.post('/tasks/user', {
+ const habit = await user.post('/tasks/user', {
type: 'habit',
text: 'habit with checklist',
});
@@ -68,7 +68,7 @@ describe('POST /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to rewards', async () => {
- let reward = await user.post('/tasks/user', {
+ const reward = await user.post('/tasks/user', {
type: 'reward',
text: 'reward with checklist',
});
diff --git a/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist_itemId_score.test.js b/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist_itemId_score.test.js
index 00c238208a..b54b860ebe 100644
--- a/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist_itemId_score.test.js
+++ b/test/api/v3/integration/tasks/checklists/POST-tasks_taskId_checklist_itemId_score.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
server,
sleep,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
let user;
@@ -14,7 +14,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('scores a checklist item', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
});
@@ -31,7 +31,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('can use a alias to score a checklist item', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
alias: 'daily-with-shortname',
@@ -49,7 +49,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('fails on habits', async () => {
- let habit = await user.post('/tasks/user', {
+ const habit = await user.post('/tasks/user', {
type: 'habit',
text: 'habit with checklist',
});
@@ -64,7 +64,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('fails on rewards', async () => {
- let reward = await user.post('/tasks/user', {
+ const reward = await user.post('/tasks/user', {
type: 'reward',
text: 'reward with checklist',
});
@@ -85,7 +85,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post('/tasks/user', {
+ const createdTask = await user.post('/tasks/user', {
type: 'daily',
text: 'daily with checklist',
});
@@ -107,7 +107,7 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
});
it('sends task activity webhooks', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -119,22 +119,22 @@ describe('POST /tasks/:taskId/checklist/:itemId/score', () => {
},
});
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
});
- let updatedTask = await user.post(`/tasks/${task.id}/checklist`, {
+ const updatedTask = await user.post(`/tasks/${task.id}/checklist`, {
text: 'checklist item text',
});
- let checklistItem = updatedTask.checklist[0];
+ const checklistItem = updatedTask.checklist[0];
- let scoredItemTask = await user.post(`/tasks/${task.id}/checklist/${checklistItem.id}/score`);
+ const scoredItemTask = await user.post(`/tasks/${task.id}/checklist/${checklistItem.id}/score`);
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('checklistScored');
expect(body.task).to.eql(scoredItemTask);
diff --git a/test/api/v3/integration/tasks/checklists/PUT-tasks_taskId_checklist_itemId.test.js b/test/api/v3/integration/tasks/checklists/PUT-tasks_taskId_checklist_itemId.test.js
index 2c4b259ee5..cef2cbaac4 100644
--- a/test/api/v3/integration/tasks/checklists/PUT-tasks_taskId_checklist_itemId.test.js
+++ b/test/api/v3/integration/tasks/checklists/PUT-tasks_taskId_checklist_itemId.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT /tasks/:taskId/checklist/:itemId', () => {
let user;
@@ -12,7 +12,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('updates a checklist item', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
});
@@ -35,7 +35,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('updates a checklist item using task alias', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'daily',
text: 'Daily with checklist',
alias: 'daily-with-shortname',
@@ -59,7 +59,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on habits', async () => {
- let habit = await user.post('/tasks/user', {
+ const habit = await user.post('/tasks/user', {
type: 'habit',
text: 'habit with checklist',
});
@@ -72,7 +72,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on rewards', async () => {
- let reward = await user.post('/tasks/user', {
+ const reward = await user.post('/tasks/user', {
type: 'reward',
text: 'reward with checklist',
});
@@ -93,7 +93,7 @@ describe('PUT /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post('/tasks/user', {
+ const createdTask = await user.post('/tasks/user', {
type: 'daily',
text: 'daily with checklist',
});
diff --git a/test/api/v3/integration/tasks/groups/DELETE-group_tasks_id.test.js b/test/api/v3/integration/tasks/groups/DELETE-group_tasks_id.test.js
index 0364869af9..59dba9f5ed 100644
--- a/test/api/v3/integration/tasks/groups/DELETE-group_tasks_id.test.js
+++ b/test/api/v3/integration/tasks/groups/DELETE-group_tasks_id.test.js
@@ -1,18 +1,19 @@
+import { find } from 'lodash';
import {
translate as t,
createAndPopulateGroup,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('Groups DELETE /tasks/:id', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -22,8 +23,8 @@ describe('Groups DELETE /tasks/:id', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
@@ -70,8 +71,8 @@ describe('Groups DELETE /tasks/:id', () => {
await user.put(`/tasks/${task._id}/`, {
requiresApproval: true,
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -98,8 +99,8 @@ describe('Groups DELETE /tasks/:id', () => {
it('unlinks assigned user', async () => {
await user.del(`/tasks/${task._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(syncedTask.group.broken).to.equal('TASK_DELETED');
});
@@ -107,19 +108,19 @@ describe('Groups DELETE /tasks/:id', () => {
it('unlinks all assigned users', async () => {
await user.del(`/tasks/${task._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
- let member2Tasks = await member2.get('/tasks/user');
- let member2SyncedTask = find(member2Tasks, findAssignedTask);
+ const member2Tasks = await member2.get('/tasks/user');
+ const member2SyncedTask = find(member2Tasks, findAssignedTask);
expect(syncedTask.group.broken).to.equal('TASK_DELETED');
expect(member2SyncedTask.group.broken).to.equal('TASK_DELETED');
});
it('prevents a user from deleting a task they are assigned to', async () => {
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.del(`/tasks/${syncedTask._id}`))
.to.eventually.be.rejected.and.eql({
@@ -130,8 +131,8 @@ describe('Groups DELETE /tasks/:id', () => {
});
it('allows a user to delete a broken task', async () => {
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await user.del(`/tasks/${task._id}`);
@@ -146,8 +147,8 @@ describe('Groups DELETE /tasks/:id', () => {
});
it('allows a user to delete a task after leaving a group', async () => {
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await member.post(`/groups/${guild._id}/leave`);
diff --git a/test/api/v3/integration/tasks/groups/GET-approvals_group_id.test.js b/test/api/v3/integration/tasks/groups/GET-approvals_group_id.test.js
index fe831b4452..a80b33ed5f 100644
--- a/test/api/v3/integration/tasks/groups/GET-approvals_group_id.test.js
+++ b/test/api/v3/integration/tasks/groups/GET-approvals_group_id.test.js
@@ -1,17 +1,18 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('GET /approvals/group/:groupId', () => {
- let user, guild, member, addlMember, task, syncedTask, addlSyncedTask;
+ let user; let guild; let member; let addlMember; let task; let syncedTask; let
+ addlSyncedTask;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -21,8 +22,8 @@ describe('GET /approvals/group/:groupId', () => {
guild = group;
user = groupLeader;
- member = members[0];
- addlMember = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ addlMember = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test todo',
@@ -33,10 +34,10 @@ describe('GET /approvals/group/:groupId', () => {
await user.post(`/tasks/${task._id}/assign/${member._id}`);
await user.post(`/tasks/${task._id}/assign/${addlMember._id}`);
- let memberTasks = await member.get('/tasks/user');
+ const memberTasks = await member.get('/tasks/user');
syncedTask = find(memberTasks, findAssignedTask);
- let addlMemberTasks = await addlMember.get('/tasks/user');
+ const addlMemberTasks = await addlMember.get('/tasks/user');
addlSyncedTask = find(addlMemberTasks, findAssignedTask);
try {
@@ -53,13 +54,13 @@ describe('GET /approvals/group/:groupId', () => {
});
it('provides only user\'s own tasks when user is not the group leader', async () => {
- let approvals = await member.get(`/approvals/group/${guild._id}`);
+ const approvals = await member.get(`/approvals/group/${guild._id}`);
expect(approvals[0]._id).to.equal(syncedTask._id);
expect(approvals[1]).to.not.exist;
});
it('allows group leaders to get a list of tasks that need approval', async () => {
- let approvals = await user.get(`/approvals/group/${guild._id}`);
+ const approvals = await user.get(`/approvals/group/${guild._id}`);
expect(approvals[0]._id).to.equal(syncedTask._id);
expect(approvals[1]._id).to.equal(addlSyncedTask._id);
});
@@ -69,7 +70,7 @@ describe('GET /approvals/group/:groupId', () => {
managerId: member._id,
});
- let approvals = await member.get(`/approvals/group/${guild._id}`);
+ const approvals = await member.get(`/approvals/group/${guild._id}`);
expect(approvals[0]._id).to.equal(syncedTask._id);
expect(approvals[1]._id).to.equal(addlSyncedTask._id);
});
diff --git a/test/api/v3/integration/tasks/groups/GET-tasks_group_id.test.js b/test/api/v3/integration/tasks/groups/GET-tasks_group_id.test.js
index e81eef76e6..87988bb78a 100644
--- a/test/api/v3/integration/tasks/groups/GET-tasks_group_id.test.js
+++ b/test/api/v3/integration/tasks/groups/GET-tasks_group_id.test.js
@@ -1,15 +1,16 @@
+import { v4 as generateUUID } from 'uuid';
+import { each } from 'lodash';
import {
generateUser,
generateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import { each } from 'lodash';
describe('GET /tasks/group/:groupId', () => {
- let user, group, task, groupWithTask;
- let tasks = [];
- let tasksToTest = {
+ let user; let group; let task; let
+ groupWithTask;
+ const tasks = [];
+ const tasksToTest = {
habit: {
text: 'test habit',
type: 'habit',
@@ -39,7 +40,7 @@ describe('GET /tasks/group/:groupId', () => {
});
it('returns error when group is not found', async () => {
- let dummyId = generateUUID();
+ const dummyId = generateUUID();
await expect(user.get(`/tasks/group/${dummyId}`)).to.eventually.be.rejected.and.eql({
code: 404,
@@ -57,17 +58,17 @@ describe('GET /tasks/group/:groupId', () => {
});
it('gets group tasks', async () => {
- let getTask = await user.get(`/tasks/group/${groupWithTask._id}`);
+ const getTask = await user.get(`/tasks/group/${groupWithTask._id}`);
expect(getTask).to.eql(tasks);
});
it('gets group tasks filtered by type', async () => {
- let groupTasks = await user.get(`/tasks/group/${groupWithTask._id}?type=${task.type}s`);
+ const groupTasks = await user.get(`/tasks/group/${groupWithTask._id}?type=${task.type}s`);
expect(groupTasks).to.eql([task]);
});
it('cannot get a task owned by someone else', async () => {
- let anotherUser = await generateUser();
+ const anotherUser = await generateUser();
await expect(anotherUser.get(`/tasks/group/${groupWithTask._id}`)).to.eventually.be.rejected.and.eql({
code: 404,
diff --git a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_approve_userId.test.js b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_approve_userId.test.js
index a483eaa7fa..599086e463 100644
--- a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_approve_userId.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_approve_userId.test.js
@@ -1,18 +1,19 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /tasks/:id/approve/:userId', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -22,8 +23,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test todo',
@@ -70,9 +71,9 @@ describe('POST /tasks/:id/approve/:userId', () => {
expect(member.notifications.length).to.equal(3);
expect(member.notifications[1].type).to.equal('GROUP_TASK_APPROVED');
- expect(member.notifications[1].data.message).to.equal(t('yourTaskHasBeenApproved', {taskText: task.text}));
+ expect(member.notifications[1].data.message).to.equal(t('yourTaskHasBeenApproved', { taskText: task.text }));
expect(member.notifications[2].type).to.equal('SCORED_TASK');
- expect(member.notifications[2].data.message).to.equal(t('yourTaskHasBeenApproved', {taskText: task.text}));
+ expect(member.notifications[2].data.message).to.equal(t('yourTaskHasBeenApproved', { taskText: task.text }));
memberTasks = await member.get('/tasks/user');
syncedTask = find(memberTasks, findAssignedTask);
@@ -104,9 +105,9 @@ describe('POST /tasks/:id/approve/:userId', () => {
expect(member.notifications.length).to.equal(3);
expect(member.notifications[1].type).to.equal('GROUP_TASK_APPROVED');
- expect(member.notifications[1].data.message).to.equal(t('yourTaskHasBeenApproved', {taskText: task.text}));
+ expect(member.notifications[1].data.message).to.equal(t('yourTaskHasBeenApproved', { taskText: task.text }));
expect(member.notifications[2].type).to.equal('SCORED_TASK');
- expect(member.notifications[2].data.message).to.equal(t('yourTaskHasBeenApproved', {taskText: task.text}));
+ expect(member.notifications[2].data.message).to.equal(t('yourTaskHasBeenApproved', { taskText: task.text }));
memberTasks = await member.get('/tasks/user');
syncedTask = find(memberTasks, findAssignedTask);
@@ -122,8 +123,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
});
await member2.post(`/tasks/${task._id}/assign/${member._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -154,8 +155,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
await member2.post(`/tasks/${task._id}/assign/${member._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -184,7 +185,7 @@ describe('POST /tasks/:id/approve/:userId', () => {
});
it('completes master task when single-completion task is approved', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: true,
@@ -194,8 +195,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -205,17 +206,15 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/approve/${member._id}`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
+ const groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(true);
});
it('deletes other assigned user tasks when single-completion task is approved', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: true,
@@ -225,8 +224,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -236,17 +235,18 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/approve/${member._id}`);
- let member2Tasks = await member2.get('/tasks/user');
+ const member2Tasks = await member2.get('/tasks/user');
- let syncedTask2 = find(member2Tasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const syncedTask2 = find(
+ member2Tasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
expect(syncedTask2).to.equal(undefined);
});
it('does not complete master task when not all user tasks are approved if all assigned must complete', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: true,
@@ -256,8 +256,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -267,17 +267,15 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/approve/${member._id}`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}`);
+ const groupTasks = await user.get(`/tasks/group/${guild._id}`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(false);
});
it('completes master task when all user tasks are approved if all assigned must complete', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: true,
@@ -287,8 +285,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -296,8 +294,8 @@ describe('POST /tasks/:id/approve/:userId', () => {
message: t('taskApprovalHasBeenRequested'),
});
- let member2Tasks = await member2.get('/tasks/user');
- let member2SyncedTask = find(member2Tasks, findAssignedTask);
+ const member2Tasks = await member2.get('/tasks/user');
+ const member2SyncedTask = find(member2Tasks, findAssignedTask);
await expect(member2.post(`/tasks/${member2SyncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
code: 401,
@@ -308,11 +306,9 @@ describe('POST /tasks/:id/approve/:userId', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/approve/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/approve/${member2._id}`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
+ const groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(true);
});
diff --git a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_needs-work_userId.test.js b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_needs-work_userId.test.js
index a474e97732..91026baeae 100644
--- a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_needs-work_userId.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_needs-work_userId.test.js
@@ -1,18 +1,19 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /tasks/:id/needs-work/:userId', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -22,8 +23,8 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test todo',
@@ -84,7 +85,7 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
const taskText = syncedTask.text;
const managerName = user.profile.name;
- expect(notification.data.message).to.equal(t('taskNeedsWork', {taskText, managerName}));
+ expect(notification.data.message).to.equal(t('taskNeedsWork', { taskText, managerName }));
expect(notification.data.task.id).to.equal(syncedTask._id);
expect(notification.data.task.text).to.equal(taskText);
@@ -98,8 +99,8 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
// Check that the managers' GROUP_TASK_APPROVAL notifications have been removed
await user.sync();
- expect(user.notifications.find(n => {
- n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
+ expect(user.notifications.find(n => { // eslint-disable-line arrow-body-style
+ return n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
})).to.equal(undefined);
});
@@ -138,7 +139,7 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
const taskText = syncedTask.text;
const managerName = member2.profile.name;
- expect(notification.data.message).to.equal(t('taskNeedsWork', {taskText, managerName}));
+ expect(notification.data.message).to.equal(t('taskNeedsWork', { taskText, managerName }));
expect(notification.data.task.id).to.equal(syncedTask._id);
expect(notification.data.task.text).to.equal(taskText);
@@ -152,12 +153,12 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
// Check that the managers' GROUP_TASK_APPROVAL notifications have been removed
await Promise.all([user.sync(), member2.sync()]);
- expect(user.notifications.find(n => {
- n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
+ expect(user.notifications.find(n => { // eslint-disable-line arrow-body-style
+ return n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
})).to.equal(undefined);
- expect(member2.notifications.find(n => {
- n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
+ expect(member2.notifications.find(n => { // eslint-disable-line arrow-body-style
+ return n.data.taskId === syncedTask._id && n.type === 'GROUP_TASK_APPROVAL';
})).to.equal(undefined);
});
@@ -168,8 +169,8 @@ describe('POST /tasks/:id/needs-work/:userId', () => {
await member2.post(`/tasks/${task._id}/assign/${member._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
diff --git a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_score_direction.test.js b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_score_direction.test.js
index 43380b64dc..80710c701b 100644
--- a/test/api/v3/integration/tasks/groups/POST-group_tasks_id_score_direction.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-group_tasks_id_score_direction.test.js
@@ -1,18 +1,19 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /tasks/:id/score/:direction', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -22,8 +23,8 @@ describe('POST /tasks/:id/score/:direction', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test todo',
@@ -39,8 +40,8 @@ describe('POST /tasks/:id/score/:direction', () => {
'preferences.language': 'cs',
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
const direction = 'up';
await expect(member.post(`/tasks/${syncedTask._id}/score/${direction}`))
@@ -49,7 +50,7 @@ describe('POST /tasks/:id/score/:direction', () => {
error: 'NotAuthorized',
message: t('taskApprovalHasBeenRequested'),
});
- let updatedTask = await member.get(`/tasks/${syncedTask._id}`);
+ const updatedTask = await member.get(`/tasks/${syncedTask._id}`);
await user.sync();
@@ -71,8 +72,8 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post(`/groups/${guild._id}/add-manager`, {
managerId: member2._id,
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
const direction = 'up';
await expect(member.post(`/tasks/${syncedTask._id}/score/${direction}`))
@@ -81,7 +82,7 @@ describe('POST /tasks/:id/score/:direction', () => {
error: 'NotAuthorized',
message: t('taskApprovalHasBeenRequested'),
});
- let updatedTask = await member.get(`/tasks/${syncedTask._id}`);
+ const updatedTask = await member.get(`/tasks/${syncedTask._id}`);
await user.sync();
await member2.sync();
@@ -107,8 +108,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
it('errors when approval has already been requested', async () => {
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
@@ -126,8 +127,8 @@ describe('POST /tasks/:id/score/:direction', () => {
});
it('allows a user to score an approved task', async () => {
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
await expect(member.post(`/tasks/${syncedTask._id}/score/up`))
.to.eventually.be.rejected.and.to.eql({
@@ -139,14 +140,14 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post(`/tasks/${task._id}/approve/${member._id}`);
await member.post(`/tasks/${syncedTask._id}/score/up`);
- let updatedTask = await member.get(`/tasks/${syncedTask._id}`);
+ const updatedTask = await member.get(`/tasks/${syncedTask._id}`);
expect(updatedTask.completed).to.equal(true);
expect(updatedTask.dateCompleted).to.be.a('string'); // date gets converted to a string as json doesn't have a Date type
});
it('completes master task when single-completion task is completed', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: false,
@@ -154,24 +155,23 @@ describe('POST /tasks/:id/score/:direction', () => {
});
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
- let memberTasks = await member.get('/tasks/user');
+ const memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const syncedTask = find(
+ memberTasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
await member.post(`/tasks/${syncedTask._id}/score/up`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(true);
});
it('deletes other assigned user tasks when single-completion task is completed', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: false,
@@ -180,25 +180,27 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
+ const memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const syncedTask = find(
+ memberTasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
await member.post(`/tasks/${syncedTask._id}/score/up`);
- let member2Tasks = await member2.get('/tasks/user');
+ const member2Tasks = await member2.get('/tasks/user');
- let syncedTask2 = find(member2Tasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const syncedTask2 = find(
+ member2Tasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
expect(syncedTask2).to.equal(undefined);
});
it('does not complete master task when not all user tasks are completed if all assigned must complete', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: false,
@@ -207,24 +209,23 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
+ const memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const syncedTask = find(
+ memberTasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
await member.post(`/tasks/${syncedTask._id}/score/up`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const groupTasks = await user.get(`/tasks/group/${guild._id}`);
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(false);
});
it('completes master task when all user tasks are completed if all assigned must complete', async () => {
- let sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
+ const sharedCompletionTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'shared completion todo',
type: 'todo',
requiresApproval: false,
@@ -233,22 +234,22 @@ describe('POST /tasks/:id/score/:direction', () => {
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member._id}`);
await user.post(`/tasks/${sharedCompletionTask._id}/assign/${member2._id}`);
- let memberTasks = await member.get('/tasks/user');
- let member2Tasks = await member2.get('/tasks/user');
- let syncedTask = find(memberTasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
- let syncedTask2 = find(member2Tasks, (memberTask) => {
- return memberTask.group.taskId === sharedCompletionTask._id;
- });
+ const memberTasks = await member.get('/tasks/user');
+ const member2Tasks = await member2.get('/tasks/user');
+ const syncedTask = find(
+ memberTasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
+ const syncedTask2 = find(
+ member2Tasks,
+ memberTask => memberTask.group.taskId === sharedCompletionTask._id,
+ );
await member.post(`/tasks/${syncedTask._id}/score/up`);
await member2.post(`/tasks/${syncedTask2._id}/score/up`);
- let groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
- let masterTask = find(groupTasks, (groupTask) => {
- return groupTask._id === sharedCompletionTask._id;
- });
+ const groupTasks = await user.get(`/tasks/group/${guild._id}?type=completedTodos`);
+ const masterTask = find(groupTasks, groupTask => groupTask._id === sharedCompletionTask._id);
expect(masterTask.completed).to.equal(true);
});
diff --git a/test/api/v3/integration/tasks/groups/POST-tasks_group_id.test.js b/test/api/v3/integration/tasks/groups/POST-tasks_group_id.test.js
index b14f32eb91..85d9dcc3f6 100644
--- a/test/api/v3/integration/tasks/groups/POST-tasks_group_id.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-tasks_group_id.test.js
@@ -1,18 +1,19 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/group/:groupid', () => {
- let user, guild, manager;
- let groupName = 'Test Public Guild';
- let groupType = 'guild';
+ let user; let guild; let
+ manager;
+ const groupName = 'Test Public Guild';
+ const groupType = 'guild';
beforeEach(async () => {
- user = await generateUser({balance: 1});
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ user = await generateUser({ balance: 1 });
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
name: groupName,
type: groupType,
@@ -23,7 +24,7 @@ describe('POST /tasks/group/:groupid', () => {
guild = group;
user = groupLeader;
- manager = members[0];
+ manager = members[0]; // eslint-disable-line prefer-destructuring
});
it('returns error when group is not found', async () => {
@@ -41,7 +42,7 @@ describe('POST /tasks/group/:groupid', () => {
});
it('returns error when user is not a member of the group', async () => {
- let userWithoutChallenge = await generateUser();
+ const userWithoutChallenge = await generateUser();
await expect(userWithoutChallenge.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
@@ -57,7 +58,7 @@ describe('POST /tasks/group/:groupid', () => {
});
it('returns error when non leader tries to create a task', async () => {
- let userThatIsNotLeaderOfGroup = await generateUser({
+ const userThatIsNotLeaderOfGroup = await generateUser({
guilds: [guild._id],
});
@@ -75,7 +76,7 @@ describe('POST /tasks/group/:groupid', () => {
});
it('creates a habit', async () => {
- let task = await user.post(`/tasks/group/${guild._id}`, {
+ const task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
type: 'habit',
up: false,
@@ -83,7 +84,7 @@ describe('POST /tasks/group/:groupid', () => {
notes: 1976,
});
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
expect(groupTask[0].group.id).to.equal(guild._id);
expect(task.text).to.eql('test habit');
@@ -94,13 +95,13 @@ describe('POST /tasks/group/:groupid', () => {
});
it('creates a todo', async () => {
- let task = await user.post(`/tasks/group/${guild._id}`, {
+ const task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test todo',
type: 'todo',
notes: 1976,
});
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
expect(groupTask[0].group.id).to.equal(guild._id);
expect(task.text).to.eql('test todo');
@@ -109,8 +110,8 @@ describe('POST /tasks/group/:groupid', () => {
});
it('creates a daily', async () => {
- let now = new Date();
- let task = await user.post(`/tasks/group/${guild._id}`, {
+ const now = new Date();
+ const task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test daily',
type: 'daily',
notes: 1976,
@@ -119,7 +120,7 @@ describe('POST /tasks/group/:groupid', () => {
startDate: now,
});
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
expect(groupTask[0].group.id).to.equal(guild._id);
expect(task.text).to.eql('test daily');
@@ -135,7 +136,7 @@ describe('POST /tasks/group/:groupid', () => {
managerId: manager._id,
});
- let task = await manager.post(`/tasks/group/${guild._id}`, {
+ const task = await manager.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
type: 'habit',
up: false,
@@ -143,7 +144,7 @@ describe('POST /tasks/group/:groupid', () => {
notes: 1976,
});
- let groupTask = await manager.get(`/tasks/group/${guild._id}`);
+ const groupTask = await manager.get(`/tasks/group/${guild._id}`);
expect(groupTask[0].group.id).to.equal(guild._id);
expect(task.text).to.eql('test habit');
diff --git a/test/api/v3/integration/tasks/groups/POST-tasks_group_id_assign_user_id.test.js b/test/api/v3/integration/tasks/groups/POST-tasks_group_id_assign_user_id.test.js
index 9364ea11d8..214a50fc03 100644
--- a/test/api/v3/integration/tasks/groups/POST-tasks_group_id_assign_user_id.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-tasks_group_id_assign_user_id.test.js
@@ -1,20 +1,21 @@
+import { v4 as generateUUID } from 'uuid';
+import { find } from 'lodash';
import {
generateUser,
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import { find } from 'lodash';
describe('POST /tasks/:taskId/assign/:memberId', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -24,8 +25,8 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
@@ -46,7 +47,7 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
});
it('returns error when task is not a group task', async () => {
- let nonGroupTask = await user.post('/tasks/user', {
+ const nonGroupTask = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
up: false,
@@ -63,7 +64,7 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
});
it('returns error when user is not a member of the group', async () => {
- let nonUser = await generateUser();
+ const nonUser = await generateUser();
await expect(nonUser.post(`/tasks/${task._id}/assign/${member._id}`))
.to.eventually.be.rejected.and.eql({
@@ -85,9 +86,9 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
it('allows user to assign themselves (claim)', async () => {
await member.post(`/tasks/${task._id}/assign/${member._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.contain(member._id);
expect(syncedTask).to.exist;
@@ -100,7 +101,7 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
await member.post(`/tasks/${task._id}/assign/${member._id}`);
await user.sync();
await member2.sync();
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
expect(user.notifications.length).to.equal(2); // includes Guild Joined achievement
expect(user.notifications[1].type).to.equal('GROUP_TASK_CLAIMED');
@@ -115,9 +116,9 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
it('assigns a task to a user', async () => {
await user.post(`/tasks/${task._id}/assign/${member._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.contain(member._id);
expect(syncedTask).to.exist;
@@ -127,7 +128,7 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
await user.post(`/tasks/${task._id}/assign/${member._id}`);
await member.sync();
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
expect(member.notifications.length).to.equal(1);
expect(member.notifications[0].type).to.equal('GROUP_TASK_ASSIGNED');
@@ -138,13 +139,13 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
await user.post(`/tasks/${task._id}/assign/${member._id}`);
await user.post(`/tasks/${task._id}/assign/${member2._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let member1SyncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const member1SyncedTask = find(memberTasks, findAssignedTask);
- let member2Tasks = await member2.get('/tasks/user');
- let member2SyncedTask = find(member2Tasks, findAssignedTask);
+ const member2Tasks = await member2.get('/tasks/user');
+ const member2SyncedTask = find(member2Tasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.contain(member._id);
expect(groupTask[0].group.assignedUsers).to.contain(member2._id);
@@ -159,9 +160,9 @@ describe('POST /tasks/:taskId/assign/:memberId', () => {
await member2.post(`/tasks/${task._id}/assign/${member._id}`);
- let groupTask = await member2.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await member2.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.contain(member._id);
expect(syncedTask).to.exist;
diff --git a/test/api/v3/integration/tasks/groups/POST-tasks_move_taskId_to_position.test.js b/test/api/v3/integration/tasks/groups/POST-tasks_move_taskId_to_position.test.js
index cefef5c832..9dcc956e1b 100644
--- a/test/api/v3/integration/tasks/groups/POST-tasks_move_taskId_to_position.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-tasks_move_taskId_to_position.test.js
@@ -4,45 +4,46 @@ import {
} from '../../../../../helpers/api-integration/v3';
describe('POST group-tasks/:taskId/move/to/:position', () => {
- let user, guild;
+ let user; let
+ guild;
beforeEach(async () => {
- user = await generateUser({balance: 1});
- guild = await generateGroup(user, {type: 'guild'});
+ user = await generateUser({ balance: 1 });
+ guild = await generateGroup(user, { type: 'guild' });
});
it('can move task to new position', async () => {
- let tasks = await user.post(`/tasks/group/${guild._id}`, [
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2'},
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 3'},
- {type: 'habit', text: 'habit 4'},
- {type: 'todo', text: 'todo 1'},
- {type: 'habit', text: 'habit 5'},
+ const tasks = await user.post(`/tasks/group/${guild._id}`, [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 3' },
+ { type: 'habit', text: 'habit 4' },
+ { type: 'todo', text: 'todo 1' },
+ { type: 'habit', text: 'habit 5' },
]);
- let taskToMove = tasks[1];
+ const taskToMove = tasks[1];
expect(taskToMove.text).to.equal('habit 2');
- let newOrder = await user.post(`/group-tasks/${tasks[1]._id}/move/to/3`);
+ const newOrder = await user.post(`/group-tasks/${tasks[1]._id}/move/to/3`);
expect(newOrder[3]).to.equal(taskToMove._id);
expect(newOrder.length).to.equal(5);
});
it('can push to bottom', async () => {
- let tasks = await user.post(`/tasks/group/${guild._id}`, [
- {type: 'habit', text: 'habit 1'},
- {type: 'habit', text: 'habit 2'},
- {type: 'daily', text: 'daily 1'},
- {type: 'habit', text: 'habit 3'},
- {type: 'habit', text: 'habit 4'},
- {type: 'todo', text: 'todo 1'},
- {type: 'habit', text: 'habit 5'},
+ const tasks = await user.post(`/tasks/group/${guild._id}`, [
+ { type: 'habit', text: 'habit 1' },
+ { type: 'habit', text: 'habit 2' },
+ { type: 'daily', text: 'daily 1' },
+ { type: 'habit', text: 'habit 3' },
+ { type: 'habit', text: 'habit 4' },
+ { type: 'todo', text: 'todo 1' },
+ { type: 'habit', text: 'habit 5' },
]);
- let taskToMove = tasks[1];
+ const taskToMove = tasks[1];
expect(taskToMove.text).to.equal('habit 2');
- let newOrder = await user.post(`/group-tasks/${tasks[1]._id}/move/to/-1`);
+ const newOrder = await user.post(`/group-tasks/${tasks[1]._id}/move/to/-1`);
expect(newOrder[4]).to.equal(taskToMove._id);
expect(newOrder.length).to.equal(5);
});
diff --git a/test/api/v3/integration/tasks/groups/POST-tasks_task_id_unassign.test.js b/test/api/v3/integration/tasks/groups/POST-tasks_task_id_unassign.test.js
index a3fbd3c8bb..c1981b3061 100644
--- a/test/api/v3/integration/tasks/groups/POST-tasks_task_id_unassign.test.js
+++ b/test/api/v3/integration/tasks/groups/POST-tasks_task_id_unassign.test.js
@@ -1,20 +1,21 @@
+import { v4 as generateUUID } from 'uuid';
+import { find } from 'lodash';
import {
generateUser,
createAndPopulateGroup,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-import { find } from 'lodash';
describe('POST /tasks/:taskId/unassign/:memberId', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -24,8 +25,8 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
@@ -48,7 +49,7 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
});
it('returns error when task is not a group task', async () => {
- let nonGroupTask = await user.post('/tasks/user', {
+ const nonGroupTask = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
up: false,
@@ -65,7 +66,7 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
});
it('returns error when user is not a member of the group', async () => {
- let nonUser = await generateUser();
+ const nonUser = await generateUser();
await expect(nonUser.post(`/tasks/${task._id}/unassign/${member._id}`))
.to.eventually.be.rejected.and.eql({
@@ -78,9 +79,9 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
it('unassigns a user from a task', async () => {
await user.post(`/tasks/${task._id}/unassign/${member._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.not.contain(member._id);
expect(syncedTask).to.not.exist;
@@ -98,13 +99,13 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
await user.post(`/tasks/${task._id}/unassign/${member._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let member1SyncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const member1SyncedTask = find(memberTasks, findAssignedTask);
- let member2Tasks = await member2.get('/tasks/user');
- let member2SyncedTask = find(member2Tasks, findAssignedTask);
+ const member2Tasks = await member2.get('/tasks/user');
+ const member2SyncedTask = find(member2Tasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.not.contain(member._id);
expect(member1SyncedTask).to.not.exist;
@@ -120,9 +121,9 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
await member2.post(`/tasks/${task._id}/unassign/${member._id}`);
- let groupTask = await member2.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await member2.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.not.contain(member._id);
expect(syncedTask).to.not.exist;
@@ -131,9 +132,9 @@ describe('POST /tasks/:taskId/unassign/:memberId', () => {
it('allows a user to unassign themselves', async () => {
await member.post(`/tasks/${task._id}/unassign/${member._id}`);
- let groupTask = await user.get(`/tasks/group/${guild._id}`);
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const groupTask = await user.get(`/tasks/group/${guild._id}`);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(groupTask[0].group.assignedUsers).to.not.contain(member._id);
expect(syncedTask).to.not.exist;
diff --git a/test/api/v3/integration/tasks/groups/PUT-group_task_id.test.js b/test/api/v3/integration/tasks/groups/PUT-group_task_id.test.js
index aa2b3876a6..d7a193c025 100644
--- a/test/api/v3/integration/tasks/groups/PUT-group_task_id.test.js
+++ b/test/api/v3/integration/tasks/groups/PUT-group_task_id.test.js
@@ -1,17 +1,18 @@
+import { find } from 'lodash';
import {
createAndPopulateGroup, translate as t,
} from '../../../../../helpers/api-integration/v3';
-import {find} from 'lodash';
describe('PUT /tasks/:id', () => {
- let user, guild, member, member2, task;
+ let user; let guild; let member; let member2; let
+ task;
function findAssignedTask (memberTask) {
return memberTask.group.id === guild._id;
}
beforeEach(async () => {
- let {group, members, groupLeader} = await createAndPopulateGroup({
+ const { group, members, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -21,8 +22,8 @@ describe('PUT /tasks/:id', () => {
guild = group;
user = groupLeader;
- member = members[0];
- member2 = members[1];
+ member = members[0]; // eslint-disable-line prefer-destructuring
+ member2 = members[1]; // eslint-disable-line prefer-destructuring
task = await user.post(`/tasks/group/${guild._id}`, {
text: 'test habit',
@@ -37,7 +38,7 @@ describe('PUT /tasks/:id', () => {
});
it('updates a group task', async () => {
- let savedHabit = await user.put(`/tasks/${task._id}`, {
+ const savedHabit = await user.put(`/tasks/${task._id}`, {
notes: 'some new notes',
});
@@ -56,8 +57,8 @@ describe('PUT /tasks/:id', () => {
requiresApproval: true,
});
- let memberTasks = await member2.get('/tasks/user');
- let syncedTask = find(memberTasks, (memberTask) => memberTask.group.taskId === task._id);
+ const memberTasks = await member2.get('/tasks/user');
+ const syncedTask = find(memberTasks, memberTask => memberTask.group.taskId === task._id);
// score up to trigger approval
await expect(member2.post(`/tasks/${syncedTask._id}/score/up`))
@@ -107,8 +108,8 @@ describe('PUT /tasks/:id', () => {
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(syncedTask.text).to.eql('some new text');
expect(syncedTask.up).to.eql(false);
@@ -123,11 +124,11 @@ describe('PUT /tasks/:id', () => {
notes: 'some new notes',
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
- let member2Tasks = await member2.get('/tasks/user');
- let member2SyncedTask = find(member2Tasks, findAssignedTask);
+ const member2Tasks = await member2.get('/tasks/user');
+ const member2SyncedTask = find(member2Tasks, findAssignedTask);
expect(syncedTask.text).to.eql('some new text');
expect(syncedTask.up).to.eql(false);
@@ -151,8 +152,8 @@ describe('PUT /tasks/:id', () => {
});
- let memberTasks = await member.get('/tasks/user');
- let syncedTask = find(memberTasks, findAssignedTask);
+ const memberTasks = await member.get('/tasks/user');
+ const syncedTask = find(memberTasks, findAssignedTask);
expect(syncedTask.text).to.eql('some new text');
expect(syncedTask.up).to.eql(false);
diff --git a/test/api/v3/integration/tasks/groups/checklists/DELETE-group_tasks_taskId_checklist_item.test.js b/test/api/v3/integration/tasks/groups/checklists/DELETE-group_tasks_taskId_checklist_item.test.js
index ace15b6039..1830faa9f0 100644
--- a/test/api/v3/integration/tasks/groups/checklists/DELETE-group_tasks_taskId_checklist_item.test.js
+++ b/test/api/v3/integration/tasks/groups/checklists/DELETE-group_tasks_taskId_checklist_item.test.js
@@ -1,14 +1,15 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE group /tasks/:taskId/checklist/:itemId', () => {
- let user, guild, task;
+ let user; let guild; let
+ task;
before(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -26,7 +27,7 @@ describe('DELETE group /tasks/:taskId/checklist/:itemId', () => {
text: 'Daily with checklist',
});
- let savedTask = await user.post(`/tasks/${task._id}/checklist`, {text: 'Checklist Item 1', completed: false});
+ let savedTask = await user.post(`/tasks/${task._id}/checklist`, { text: 'Checklist Item 1', completed: false });
await user.del(`/tasks/${task._id}/checklist/${savedTask.checklist[0].id}`);
savedTask = await user.get(`/tasks/group/${guild._id}`);
@@ -35,7 +36,7 @@ describe('DELETE group /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with habits', async () => {
- let habit = await user.post(`/tasks/group/${guild._id}`, {
+ const habit = await user.post(`/tasks/group/${guild._id}`, {
type: 'habit',
text: 'habit with checklist',
});
@@ -48,7 +49,7 @@ describe('DELETE group /tasks/:taskId/checklist/:itemId', () => {
});
it('does not work with rewards', async () => {
- let reward = await user.post(`/tasks/group/${guild._id}`, {
+ const reward = await user.post(`/tasks/group/${guild._id}`, {
type: 'reward',
text: 'reward with checklist',
});
@@ -69,7 +70,7 @@ describe('DELETE group /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post(`/tasks/group/${guild._id}`, {
+ const createdTask = await user.post(`/tasks/group/${guild._id}`, {
type: 'daily',
text: 'daily with checklist',
});
diff --git a/test/api/v3/integration/tasks/groups/checklists/POST-group_tasks_taskId_checklist.test.js b/test/api/v3/integration/tasks/groups/checklists/POST-group_tasks_taskId_checklist.test.js
index f6e18027a7..f1e553984d 100644
--- a/test/api/v3/integration/tasks/groups/checklists/POST-group_tasks_taskId_checklist.test.js
+++ b/test/api/v3/integration/tasks/groups/checklists/POST-group_tasks_taskId_checklist.test.js
@@ -1,14 +1,15 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST group /tasks/:taskId/checklist/', () => {
- let user, guild, task;
+ let user; let guild; let
+ task;
before(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -32,8 +33,8 @@ describe('POST group /tasks/:taskId/checklist/', () => {
_id: 123,
});
- let updatedTasks = await user.get(`/tasks/group/${guild._id}`);
- let updatedTask = updatedTasks[0];
+ const updatedTasks = await user.get(`/tasks/group/${guild._id}`);
+ const updatedTask = updatedTasks[0];
expect(updatedTask.checklist.length).to.equal(1);
expect(updatedTask.checklist[0].text).to.equal('Checklist Item 1');
@@ -44,7 +45,7 @@ describe('POST group /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to habits', async () => {
- let habit = await user.post(`/tasks/group/${guild._id}`, {
+ const habit = await user.post(`/tasks/group/${guild._id}`, {
type: 'habit',
text: 'habit with checklist',
});
@@ -59,7 +60,7 @@ describe('POST group /tasks/:taskId/checklist/', () => {
});
it('does not add a checklist to rewards', async () => {
- let reward = await user.post(`/tasks/group/${guild._id}`, {
+ const reward = await user.post(`/tasks/group/${guild._id}`, {
type: 'reward',
text: 'reward with checklist',
});
diff --git a/test/api/v3/integration/tasks/groups/checklists/PUT-group_tasks_taskId_checklist_itemId.test.js b/test/api/v3/integration/tasks/groups/checklists/PUT-group_tasks_taskId_checklist_itemId.test.js
index 27b3e19b11..06c612f71b 100644
--- a/test/api/v3/integration/tasks/groups/checklists/PUT-group_tasks_taskId_checklist_itemId.test.js
+++ b/test/api/v3/integration/tasks/groups/checklists/PUT-group_tasks_taskId_checklist_itemId.test.js
@@ -1,14 +1,15 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('PUT group /tasks/:taskId/checklist/:itemId', () => {
- let user, guild, task;
+ let user; let guild; let
+ task;
before(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -44,7 +45,7 @@ describe('PUT group /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on habits', async () => {
- let habit = await user.post(`/tasks/group/${guild._id}`, {
+ const habit = await user.post(`/tasks/group/${guild._id}`, {
type: 'habit',
text: 'habit with checklist',
});
@@ -57,7 +58,7 @@ describe('PUT group /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on rewards', async () => {
- let reward = await user.post(`/tasks/group/${guild._id}`, {
+ const reward = await user.post(`/tasks/group/${guild._id}`, {
type: 'reward',
text: 'reward with checklist',
});
@@ -78,7 +79,7 @@ describe('PUT group /tasks/:taskId/checklist/:itemId', () => {
});
it('fails on checklist item not found', async () => {
- let createdTask = await user.post(`/tasks/group/${guild._id}`, {
+ const createdTask = await user.post(`/tasks/group/${guild._id}`, {
type: 'daily',
text: 'daily with checklist',
});
diff --git a/test/api/v3/integration/tasks/groups/tags/DELETE-group_tasks_taskId_tags_tagId.test.js b/test/api/v3/integration/tasks/groups/tags/DELETE-group_tasks_taskId_tags_tagId.test.js
index 05a792dee5..9c97c2860c 100644
--- a/test/api/v3/integration/tasks/groups/tags/DELETE-group_tasks_taskId_tags_tagId.test.js
+++ b/test/api/v3/integration/tasks/groups/tags/DELETE-group_tasks_taskId_tags_tagId.test.js
@@ -1,14 +1,17 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-// Currently we do not support adding tags to group original tasks, but if we do in the future, these tests will check
+
+// Currently we do not support adding tags to group original tasks,
+// but if we do in the future, these tests will check
xdescribe('DELETE group /tasks/:taskId/tags/:tagId', () => {
- let user, guild, task;
+ let user; let guild; let
+ task;
before(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -26,18 +29,18 @@ xdescribe('DELETE group /tasks/:taskId/tags/:tagId', () => {
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
+ const tag = await user.post('/tags', { name: 'Tag 1' });
await user.post(`/tasks/${task._id}/tags/${tag.id}`);
await user.del(`/tasks/${task._id}/tags/${tag.id}`);
- let updatedTask = await user.get(`/tasks/group/${guild._id}`);
+ const updatedTask = await user.get(`/tasks/group/${guild._id}`);
expect(updatedTask[0].tags.length).to.equal(0);
});
it('only deletes existing tags', async () => {
- let createdTask = await user.post(`/tasks/group/${guild._id}`, {
+ const createdTask = await user.post(`/tasks/group/${guild._id}`, {
type: 'habit',
text: 'Task with tag',
});
diff --git a/test/api/v3/integration/tasks/groups/tags/POST-tasks_taskId_tags.test.js b/test/api/v3/integration/tasks/groups/tags/POST-tasks_taskId_tags.test.js
index ead583d122..615f87ba47 100644
--- a/test/api/v3/integration/tasks/groups/tags/POST-tasks_taskId_tags.test.js
+++ b/test/api/v3/integration/tasks/groups/tags/POST-tasks_taskId_tags.test.js
@@ -1,15 +1,17 @@
+import { v4 as generateUUID } from 'uuid';
import {
createAndPopulateGroup,
translate as t,
} from '../../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
-// Currently we do not support adding tags to group original tasks, but if we do in the future, these tests will check
+// Currently we do not support adding tags to group original tasks,
+// but if we do in the future, these tests will check
xdescribe('POST group /tasks/:taskId/tags/:tagId', () => {
- let user, guild, task;
+ let user; let guild; let
+ task;
before(async () => {
- let {group, groupLeader} = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'Test Guild',
type: 'guild',
@@ -27,8 +29,8 @@ xdescribe('POST group /tasks/:taskId/tags/:tagId', () => {
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
- let savedTask = await user.post(`/tasks/${task._id}/tags/${tag.id}`);
+ const tag = await user.post('/tags', { name: 'Tag 1' });
+ const savedTask = await user.post(`/tasks/${task._id}/tags/${tag.id}`);
expect(savedTask.tags[0]).to.equal(tag.id);
});
@@ -39,7 +41,7 @@ xdescribe('POST group /tasks/:taskId/tags/:tagId', () => {
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
+ const tag = await user.post('/tags', { name: 'Tag 1' });
await user.post(`/tasks/${task._id}/tags/${tag.id}`);
diff --git a/test/api/v3/integration/tasks/tags/DELETE-tasks_taskId_tags_tagId.test.js b/test/api/v3/integration/tasks/tags/DELETE-tasks_taskId_tags_tagId.test.js
index 0a39cfbac7..f1269050c5 100644
--- a/test/api/v3/integration/tasks/tags/DELETE-tasks_taskId_tags_tagId.test.js
+++ b/test/api/v3/integration/tasks/tags/DELETE-tasks_taskId_tags_tagId.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:taskId/tags/:tagId', () => {
let user;
@@ -12,40 +12,40 @@ describe('DELETE /tasks/:taskId/tags/:tagId', () => {
});
it('removes a tag from a task', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
+ const tag = await user.post('/tags', { name: 'Tag 1' });
await user.post(`/tasks/${task._id}/tags/${tag.id}`);
await user.del(`/tasks/${task._id}/tags/${tag.id}`);
- let updatedTask = await user.get(`/tasks/${task._id}`);
+ const updatedTask = await user.get(`/tasks/${task._id}`);
expect(updatedTask.tags.length).to.equal(0);
});
it('removes a tag from a task using task short name', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
alias: 'habit-with-alias',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
+ const tag = await user.post('/tags', { name: 'Tag 1' });
await user.post(`/tasks/${task._id}/tags/${tag.id}`);
await user.del(`/tasks/${task.alias}/tags/${tag.id}`);
- let updatedTask = await user.get(`/tasks/${task._id}`);
+ const updatedTask = await user.get(`/tasks/${task._id}`);
expect(updatedTask.tags.length).to.equal(0);
});
it('only deletes existing tags', async () => {
- let createdTask = await user.post('/tasks/user', {
+ const createdTask = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
});
diff --git a/test/api/v3/integration/tasks/tags/POST-tasks_taskId_tags_tagId.test.js b/test/api/v3/integration/tasks/tags/POST-tasks_taskId_tags_tagId.test.js
index 66fb002c69..3e48f7e2bc 100644
--- a/test/api/v3/integration/tasks/tags/POST-tasks_taskId_tags_tagId.test.js
+++ b/test/api/v3/integration/tasks/tags/POST-tasks_taskId_tags_tagId.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/:taskId/tags/:tagId', () => {
let user;
@@ -12,37 +12,37 @@ describe('POST /tasks/:taskId/tags/:tagId', () => {
});
it('adds a tag to a task', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
- let savedTask = await user.post(`/tasks/${task._id}/tags/${tag.id}`);
+ const tag = await user.post('/tags', { name: 'Tag 1' });
+ const savedTask = await user.post(`/tasks/${task._id}/tags/${tag.id}`);
expect(savedTask.tags[0]).to.equal(tag.id);
});
it('adds a tag to a task with alias', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
alias: 'habit-with-alias',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
- let savedTask = await user.post(`/tasks/${task.alias}/tags/${tag.id}`);
+ const tag = await user.post('/tags', { name: 'Tag 1' });
+ const savedTask = await user.post(`/tasks/${task.alias}/tags/${tag.id}`);
expect(savedTask.tags[0]).to.equal(tag.id);
});
it('does not add a tag to a task twice', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
});
- let tag = await user.post('/tags', {name: 'Tag 1'});
+ const tag = await user.post('/tags', { name: 'Tag 1' });
await user.post(`/tasks/${task._id}/tags/${tag.id}`);
@@ -54,7 +54,7 @@ describe('POST /tasks/:taskId/tags/:tagId', () => {
});
it('does not add a non existing tag to a task', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
type: 'habit',
text: 'Task with tag',
});
diff --git a/test/api/v3/integration/user/DELETE-user.test.js b/test/api/v3/integration/user/DELETE-user.test.js
index 2fbe493d43..644a2d57ba 100644
--- a/test/api/v3/integration/user/DELETE-user.test.js
+++ b/test/api/v3/integration/user/DELETE-user.test.js
@@ -1,3 +1,8 @@
+import {
+ find,
+ each,
+ map,
+} from 'lodash';
import {
checkExistence,
createAndPopulateGroup,
@@ -6,11 +11,6 @@ import {
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import {
- find,
- each,
- map,
-} from 'lodash';
import {
sha1MakeSalt,
sha1Encrypt as sha1EncryptPassword,
@@ -21,11 +21,11 @@ const DELETE_CONFIRMATION = 'DELETE';
describe('DELETE /user', () => {
let user;
- let password = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
+ const password = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
context('user with local auth', async () => {
beforeEach(async () => {
- user = await generateUser({balance: 10});
+ user = await generateUser({ balance: 10 });
});
it('returns an error if password is wrong', async () => {
@@ -56,10 +56,10 @@ describe('DELETE /user', () => {
});
it('returns an error if excessive feedback is supplied', async () => {
- let feedbackText = 'spam feedback ';
+ const feedbackText = 'spam feedback ';
let feedback = feedbackText;
while (feedback.length < 10000) {
- feedback = feedback + feedbackText;
+ feedback += feedbackText;
}
await expect(user.del('/user', {
@@ -73,7 +73,7 @@ describe('DELETE /user', () => {
});
it('returns an error if user has active subscription', async () => {
- let userWithSubscription = await generateUser({'purchased.plan.customerId': 'fake-customer-id'});
+ const userWithSubscription = await generateUser({ 'purchased.plan.customerId': 'fake-customer-id' });
await expect(userWithSubscription.del('/user', {
password,
@@ -92,8 +92,8 @@ describe('DELETE /user', () => {
await user.sync();
// gets the user's tasks ids
- let ids = [];
- each(user.tasksOrder, (idsForOrder) => {
+ const ids = [];
+ each(user.tasksOrder, idsForOrder => {
ids.push(...idsForOrder);
});
@@ -103,20 +103,18 @@ describe('DELETE /user', () => {
password,
});
- await Promise.all(map(ids, id => {
- return expect(checkExistence('tasks', id)).to.eventually.eql(false);
- }));
+ await Promise.all(map(ids, id => expect(checkExistence('tasks', id)).to.eventually.eql(false)));
});
it('reduces memberCount in challenges user is linked to', async () => {
- let populatedGroup = await createAndPopulateGroup({
+ const populatedGroup = await createAndPopulateGroup({
members: 2,
});
- let group = populatedGroup.group;
- let authorizedUser = populatedGroup.members[1];
+ const { group } = populatedGroup;
+ const authorizedUser = populatedGroup.members[1];
- let challenge = await generateChallenge(populatedGroup.groupLeader, group);
+ const challenge = await generateChallenge(populatedGroup.groupLeader, group);
await populatedGroup.groupLeader.post(`/challenges/${challenge._id}/join`);
await authorizedUser.post(`/challenges/${challenge._id}/join`);
@@ -136,7 +134,7 @@ describe('DELETE /user', () => {
it('sends feedback to the admin email', async () => {
sandbox.spy(email, 'sendTxn');
- let feedback = 'Reasons for Deletion';
+ const feedback = 'Reasons for Deletion';
await user.del('/user', {
password,
feedback,
@@ -160,9 +158,9 @@ describe('DELETE /user', () => {
});
it('deletes the user with a legacy sha1 password', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -220,10 +218,11 @@ describe('DELETE /user', () => {
});
context('groups user is leader of', () => {
- let guild, oldLeader, newLeader;
+ let guild; let oldLeader; let
+ newLeader;
beforeEach(async () => {
- let { group, groupLeader, members } = await createAndPopulateGroup({
+ const { group, groupLeader, members } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -232,7 +231,7 @@ describe('DELETE /user', () => {
});
guild = group;
- newLeader = members[0];
+ newLeader = members[0]; // eslint-disable-line prefer-destructuring
oldLeader = groupLeader;
});
@@ -241,7 +240,7 @@ describe('DELETE /user', () => {
password,
});
- let updatedGuild = await newLeader.get(`/groups/${guild._id}`);
+ const updatedGuild = await newLeader.get(`/groups/${guild._id}`);
expect(updatedGuild.leader).to.exist;
expect(updatedGuild.leader._id).to.not.eql(oldLeader._id);
@@ -249,17 +248,18 @@ describe('DELETE /user', () => {
});
context('groups user is a part of', () => {
- let group1, group2, userToDelete, otherUser;
+ let group1; let group2; let userToDelete; let
+ otherUser;
beforeEach(async () => {
- userToDelete = await generateUser({balance: 10});
+ userToDelete = await generateUser({ balance: 10 });
group1 = await generateGroup(userToDelete, {
type: 'guild',
privacy: 'public',
});
- let {group, members} = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
type: 'guild',
privacy: 'public',
@@ -268,7 +268,7 @@ describe('DELETE /user', () => {
});
group2 = group;
- otherUser = members[0];
+ otherUser = members[0]; // eslint-disable-line prefer-destructuring
await userToDelete.post(`/groups/${group2._id}/join`);
});
@@ -278,11 +278,9 @@ describe('DELETE /user', () => {
password,
});
- let updatedGroup1Members = await otherUser.get(`/groups/${group1._id}/members`);
- let updatedGroup2Members = await otherUser.get(`/groups/${group2._id}/members`);
- let userInGroup = find(updatedGroup2Members, (member) => {
- return member._id === userToDelete._id;
- });
+ const updatedGroup1Members = await otherUser.get(`/groups/${group1._id}/members`);
+ const updatedGroup2Members = await otherUser.get(`/groups/${group2._id}/members`);
+ const userInGroup = find(updatedGroup2Members, member => member._id === userToDelete._id);
expect(updatedGroup1Members).to.be.empty;
expect(updatedGroup2Members).to.not.be.empty;
@@ -308,7 +306,7 @@ describe('DELETE /user', () => {
})).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('incorrectDeletePhrase', {magicWord: 'DELETE'}),
+ message: t('incorrectDeletePhrase', { magicWord: 'DELETE' }),
});
});
diff --git a/test/api/v3/integration/user/DELETE-user_messages.test.js b/test/api/v3/integration/user/DELETE-user_messages.test.js
index 079550b136..f71fc89b95 100644
--- a/test/api/v3/integration/user/DELETE-user_messages.test.js
+++ b/test/api/v3/integration/user/DELETE-user_messages.test.js
@@ -3,7 +3,8 @@ import {
} from '../../../../helpers/api-integration/v3';
describe('DELETE user message', () => {
- let user, messagesId, otherUser;
+ let user; let messagesId; let
+ otherUser;
before(async () => {
[user, otherUser] = await Promise.all([generateUser(), generateUser()]);
@@ -16,7 +17,7 @@ describe('DELETE user message', () => {
message: 'second',
});
- let userRes = await user.get('/user');
+ const userRes = await user.get('/user');
messagesId = Object.keys(userRes.inbox.messages);
expect(messagesId.length).to.eql(2);
@@ -25,18 +26,18 @@ describe('DELETE user message', () => {
});
it('one message', async () => {
- let result = await user.del(`/user/messages/${messagesId[0]}`);
+ const result = await user.del(`/user/messages/${messagesId[0]}`);
messagesId = Object.keys(result);
expect(messagesId.length).to.eql(1);
- let userRes = await user.get('/user');
+ const userRes = await user.get('/user');
expect(Object.keys(userRes.inbox.messages).length).to.eql(1);
expect(userRes.inbox.messages[messagesId[0]].text).to.eql('first');
});
it('clear all', async () => {
- let result = await user.del('/user/messages');
- let userRes = await user.get('/user');
+ const result = await user.del('/user/messages');
+ const userRes = await user.get('/user');
expect(userRes.inbox.messages).to.eql({});
expect(result).to.eql({});
});
diff --git a/test/api/v3/integration/user/DELETE-user_push_device.test.js b/test/api/v3/integration/user/DELETE-user_push_device.test.js
index 129df28d87..665968bd42 100644
--- a/test/api/v3/integration/user/DELETE-user_push_device.test.js
+++ b/test/api/v3/integration/user/DELETE-user_push_device.test.js
@@ -5,8 +5,8 @@ import {
describe('DELETE /user/push-devices', () => {
let user;
- let regId = '10';
- let type = 'ios';
+ const regId = '10';
+ const type = 'ios';
beforeEach(async () => {
user = await generateUser();
@@ -22,8 +22,8 @@ describe('DELETE /user/push-devices', () => {
});
it('removes a push device from the user', async () => {
- await user.post('/user/push-devices', {type, regId});
- let response = await user.del(`/user/push-devices/${regId}`);
+ await user.post('/user/push-devices', { type, regId });
+ const response = await user.del(`/user/push-devices/${regId}`);
await user.sync();
expect(response.message).to.equal(t('pushDeviceRemoved'));
diff --git a/test/api/v3/integration/user/GET-user.test.js b/test/api/v3/integration/user/GET-user.test.js
index fc86e779db..437cc70cb3 100644
--- a/test/api/v3/integration/user/GET-user.test.js
+++ b/test/api/v3/integration/user/GET-user.test.js
@@ -11,7 +11,7 @@ describe('GET /user', () => {
});
it('returns the authenticated user with computed stats', async () => {
- let returnedUser = await user.get('/user');
+ const returnedUser = await user.get('/user');
expect(returnedUser._id).to.equal(user._id);
expect(returnedUser.stats.maxMP).to.exist;
@@ -20,7 +20,7 @@ describe('GET /user', () => {
});
it('does not return private paths (and apiToken)', async () => {
- let returnedUser = await user.get('/user');
+ const returnedUser = await user.get('/user');
expect(returnedUser.auth.local.hashed_password).to.not.exist;
expect(returnedUser.auth.local.passwordHashMethod).to.not.exist;
@@ -29,7 +29,7 @@ describe('GET /user', () => {
});
it('returns only user properties requested', async () => {
- let returnedUser = await user.get('/user?userFields=achievements,items.mounts');
+ const returnedUser = await user.get('/user?userFields=achievements,items.mounts');
expect(returnedUser._id).to.equal(user._id);
expect(returnedUser.achievements).to.exist;
diff --git a/test/api/v3/integration/user/GET-user_anonymized.test.js b/test/api/v3/integration/user/GET-user_anonymized.test.js
index 65c99f104e..b9c8207de5 100644
--- a/test/api/v3/integration/user/GET-user_anonymized.test.js
+++ b/test/api/v3/integration/user/GET-user_anonymized.test.js
@@ -1,3 +1,4 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
generateHabit,
@@ -5,11 +6,10 @@ import {
generateReward,
} from '../../../../helpers/api-integration/v3';
import common from '../../../../../website/common';
-import { v4 as generateUUID } from 'uuid';
describe('GET /user/anonymized', () => {
let user;
- let endpoint = '/user/anonymized';
+ const endpoint = '/user/anonymized';
before(async () => {
user = await generateUser();
@@ -26,7 +26,7 @@ describe('GET /user/anonymized', () => {
},
'items.special.nyeReceived': 'some',
'items.special.valentineReceived': 'some',
- webhooks: [{url: 'https://somurl.com'}],
+ webhooks: [{ url: 'https://somurl.com' }],
'achievements.challenges': 'some',
'inbox.messages': [{ text: 'some text' }],
tags: [{ name: 'some name', challenge: 'some challenge' }],
@@ -35,7 +35,7 @@ describe('GET /user/anonymized', () => {
await generateHabit({ userId: user._id });
await generateHabit({ userId: user._id, text: generateUUID() });
- let daily = await generateDaily({ userId: user._id, checklist: [{ completed: false, text: 'this-text' }] });
+ const daily = await generateDaily({ userId: user._id, checklist: [{ completed: false, text: 'this-text' }] });
expect(daily.checklist[0].text.substr(0, 5)).to.not.eql('item ');
await generateReward({ userId: user._id, text: 'some text 4' });
@@ -63,7 +63,7 @@ describe('GET /user/anonymized', () => {
it('does not return private paths (and apiToken)', async () => {
let returnedUser = await user.get(endpoint);
- let tasks2 = returnedUser.tasks;
+ const tasks2 = returnedUser.tasks;
returnedUser = returnedUser.user;
expect(returnedUser.auth.local).to.not.exist;
expect(returnedUser.apiToken).to.not.exist;
@@ -80,10 +80,10 @@ describe('GET /user/anonymized', () => {
expect(returnedUser.items.special.valentineReceived).to.not.exist;
expect(returnedUser.webhooks).to.not.exist;
expect(returnedUser.achievements.challenges).to.not.exist;
- _.forEach(returnedUser.inbox.messages, (msg) => {
+ _.forEach(returnedUser.inbox.messages, msg => {
expect(msg.text).to.eql('inbox message text');
});
- _.forEach(returnedUser.tags, (tag) => {
+ _.forEach(returnedUser.tags, tag => {
expect(tag.name).to.eql('tag');
expect(tag.challenge).to.eql('challenge');
});
@@ -91,11 +91,11 @@ describe('GET /user/anonymized', () => {
expect(tasks2).to.exist;
expect(tasks2.length).to.eql(5);
expect(tasks2[0].checklist).to.exist;
- _.forEach(tasks2, (task) => {
+ _.forEach(tasks2, task => {
expect(task.text).to.eql('task text');
expect(task.notes).to.eql('task notes');
if (task.checklist) {
- _.forEach(task.checklist, (c) => {
+ _.forEach(task.checklist, c => {
expect(c.text.substr(0, 5)).to.eql('item ');
});
}
diff --git a/test/api/v3/integration/user/GET-user_inAppRewards.test.js b/test/api/v3/integration/user/GET-user_inAppRewards.test.js
index a2583dc43f..9a498861cf 100644
--- a/test/api/v3/integration/user/GET-user_inAppRewards.test.js
+++ b/test/api/v3/integration/user/GET-user_inAppRewards.test.js
@@ -11,14 +11,10 @@ describe('GET /user/in-app-rewards', () => {
});
it('returns the reward items available for purchase', async () => {
- let buyList = await user.get('/user/in-app-rewards');
+ const buyList = await user.get('/user/in-app-rewards');
- expect(_.find(buyList, item => {
- return item.text === t('armorWarrior1Text');
- })).to.exist;
+ expect(_.find(buyList, item => item.text === t('armorWarrior1Text'))).to.exist;
- expect(_.find(buyList, item => {
- return item.text === t('armorWarrior2Text');
- })).to.not.exist;
+ expect(_.find(buyList, item => item.text === t('armorWarrior2Text'))).to.not.exist;
});
});
diff --git a/test/api/v3/integration/user/GET-user_inventory_buy.test.js b/test/api/v3/integration/user/GET-user_inventory_buy.test.js
index fd2a25b4ee..ea663142ec 100644
--- a/test/api/v3/integration/user/GET-user_inventory_buy.test.js
+++ b/test/api/v3/integration/user/GET-user_inventory_buy.test.js
@@ -13,14 +13,10 @@ describe('GET /user/inventory/buy', () => {
// More tests in common code unit tests
it('returns the gear items available for purchase', async () => {
- let buyList = await user.get('/user/inventory/buy');
+ const buyList = await user.get('/user/inventory/buy');
- expect(_.find(buyList, item => {
- return item.text === t('armorWarrior1Text');
- })).to.exist;
+ expect(_.find(buyList, item => item.text === t('armorWarrior1Text'))).to.exist;
- expect(_.find(buyList, item => {
- return item.text === t('armorWarrior2Text');
- })).to.not.exist;
+ expect(_.find(buyList, item => item.text === t('armorWarrior2Text'))).to.not.exist;
});
});
diff --git a/test/api/v3/integration/user/GET-user_toggle-pinned-item.test.js b/test/api/v3/integration/user/GET-user_toggle-pinned-item.test.js
index c958c4f979..548c1d45d9 100644
--- a/test/api/v3/integration/user/GET-user_toggle-pinned-item.test.js
+++ b/test/api/v3/integration/user/GET-user_toggle-pinned-item.test.js
@@ -20,7 +20,7 @@ describe('GET /user/toggle-pinned-item', () => {
});
it('can pin shield_rogue_5', async () => {
- let result = await user.get('/user/toggle-pinned-item/marketGear/gear.flat.shield_rogue_5');
+ const result = await user.get('/user/toggle-pinned-item/marketGear/gear.flat.shield_rogue_5');
expect(result.pinnedItems.length).to.be.eql(user.pinnedItems.length + 1);
});
diff --git a/test/api/v3/integration/user/POST-move-pinned-item.js b/test/api/v3/integration/user/POST-move-pinned-item.js
index 010e09d722..f7de9c65b2 100644
--- a/test/api/v3/integration/user/POST-move-pinned-item.js
+++ b/test/api/v3/integration/user/POST-move-pinned-item.js
@@ -2,7 +2,7 @@ import {
generateUser,
} from '../../../../helpers/api-integration/v3';
-import getOfficialPinnedItems from '../../../../../website/common/script/libs/getOfficialPinnedItems.js';
+import getOfficialPinnedItems from '../../../../../website/common/script/libs/getOfficialPinnedItems';
describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
let user;
@@ -14,14 +14,15 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
officialPinnedItems = getOfficialPinnedItems(user);
officialPinnedItemPaths = [];
- // officialPinnedItems are returned in { type: ..., path:... } format but we just need the paths for testPinnedItemsOrder
+ // officialPinnedItems are returned in { type: ..., path:... } format
+ // but we just need the paths for testPinnedItemsOrder
if (officialPinnedItems.length > 0) {
officialPinnedItemPaths = officialPinnedItems.map(item => item.path);
}
});
it('adjusts the order of pinned items with no order mismatch', async () => {
- let testPinnedItems = [
+ const testPinnedItems = [
{ type: 'armoire', path: 'armoire' },
{ type: 'potion', path: 'potion' },
{ type: 'marketGear', path: 'gear.flat.weapon_warrior_1' },
@@ -56,7 +57,7 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
pinnedItemsOrder: testPinnedItemsOrder,
});
- let res = await user.post('/user/move-pinned-item/armoire/move/to/5');
+ const res = await user.post('/user/move-pinned-item/armoire/move/to/5');
await user.sync();
expect(user.pinnedItemsOrder[5]).to.equal('armoire');
@@ -83,14 +84,14 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
});
it('adjusts the order of pinned items with order mismatch', async () => {
- let testPinnedItems = [
+ const testPinnedItems = [
{ type: 'card', path: 'cardTypes.thankyou' },
{ type: 'card', path: 'cardTypes.greeting' },
{ type: 'potion', path: 'potion' },
{ type: 'armoire', path: 'armoire' },
];
- let testPinnedItemsOrder = [
+ const testPinnedItemsOrder = [
'armoire',
'potion',
];
@@ -100,7 +101,7 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
pinnedItemsOrder: testPinnedItemsOrder,
});
- let res = await user.post('/user/move-pinned-item/armoire/move/to/1');
+ const res = await user.post('/user/move-pinned-item/armoire/move/to/1');
await user.sync();
// The basic test
@@ -115,7 +116,8 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
'cardTypes.greeting',
'potion',
];
- // inAppRewards is used here and will by default put these seasonal items in the front like this:
+ // inAppRewards is used here and will by default
+ // put these seasonal items in the front like this:
expectedResponse = officialPinnedItemPaths.concat(expectedResponse);
// now put "armoire" in where we moved it:
expectedResponse.splice(1, 0, 'armoire');
@@ -124,12 +126,12 @@ describe('POST /user/move-pinned-item/:path/move/to/:position', () => {
});
it('cannot move pinned item that you do not have pinned', async () => {
- let testPinnedItems = [
+ const testPinnedItems = [
{ type: 'potion', path: 'potion' },
{ type: 'armoire', path: 'armoire' },
];
- let testPinnedItemsOrder = [
+ const testPinnedItemsOrder = [
'armoire',
'potion',
];
diff --git a/test/api/v3/integration/user/POST-user_block.test.js b/test/api/v3/integration/user/POST-user_block.test.js
index 51766eb51e..92fdacfb5e 100644
--- a/test/api/v3/integration/user/POST-user_block.test.js
+++ b/test/api/v3/integration/user/POST-user_block.test.js
@@ -25,7 +25,7 @@ describe('block user', () => {
});
it('successfully', async () => {
- let response = await user.post(`/user/block/${blockedUser2._id}`);
+ const response = await user.post(`/user/block/${blockedUser2._id}`);
await user.sync();
expect(response).to.eql([blockedUser._id, blockedUser2._id]);
expect(user.inbox.blocks.length).to.eql(2);
diff --git a/test/api/v3/integration/user/POST-user_change-class.test.js b/test/api/v3/integration/user/POST-user_change-class.test.js
index d4b4192f23..928cb77979 100644
--- a/test/api/v3/integration/user/POST-user_change-class.test.js
+++ b/test/api/v3/integration/user/POST-user_change-class.test.js
@@ -15,7 +15,7 @@ describe('POST /user/change-class', () => {
// More tests in common code unit tests
it('changes class', async () => {
- let res = await user.post('/user/change-class?class=rogue');
+ const res = await user.post('/user/change-class?class=rogue');
await user.sync();
expect(res).to.eql(JSON.parse(
@@ -24,7 +24,7 @@ describe('POST /user/change-class', () => {
stats: user.stats,
flags: user.flags,
items: user.items,
- })
+ }),
));
});
});
diff --git a/test/api/v3/integration/user/POST-user_class_cast_spellId.test.js b/test/api/v3/integration/user/POST-user_class_cast_spellId.test.js
index 379d04a9ec..fdd30bac68 100644
--- a/test/api/v3/integration/user/POST-user_class_cast_spellId.test.js
+++ b/test/api/v3/integration/user/POST-user_class_cast_spellId.test.js
@@ -1,3 +1,6 @@
+
+import { v4 as generateUUID } from 'uuid';
+import { find } from 'lodash';
import {
generateUser,
translate as t,
@@ -6,9 +9,6 @@ import {
generateChallenge,
sleep,
} from '../../../../helpers/api-integration/v3';
-
-import { v4 as generateUUID } from 'uuid';
-import { find } from 'lodash';
import apiError from '../../../../../website/server/libs/apiError';
describe('POST /user/class/cast/:spellId', () => {
@@ -19,28 +19,28 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if spell does not exist', async () => {
- await user.update({'stats.class': 'rogue'});
- let spellId = 'invalidSpell';
+ await user.update({ 'stats.class': 'rogue' });
+ const spellId = 'invalidSpell';
await expect(user.post(`/user/class/cast/${spellId}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('spellNotFound', {spellId}),
+ message: apiError('spellNotFound', { spellId }),
});
});
it('returns an error if spell does not exist in user\'s class', async () => {
- let spellId = 'pickPocket';
+ const spellId = 'pickPocket';
await expect(user.post(`/user/class/cast/${spellId}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('spellNotFound', {spellId}),
+ message: apiError('spellNotFound', { spellId }),
});
});
it('returns an error if spell.mana > user.mana', async () => {
- await user.update({'stats.class': 'rogue'});
+ await user.update({ 'stats.class': 'rogue' });
await expect(user.post('/user/class/cast/backStab'))
.to.eventually.be.rejected.and.eql({
code: 401,
@@ -74,12 +74,12 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if spell.lvl > user.level', async () => {
- await user.update({'stats.mp': 200, 'stats.class': 'wizard'});
+ await user.update({ 'stats.mp': 200, 'stats.class': 'wizard' });
await expect(user.post('/user/class/cast/earth'))
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('spellLevelTooHigh', {level: 13}),
+ message: t('spellLevelTooHigh', { level: 13 }),
});
});
@@ -102,7 +102,7 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targetId is required but missing', async () => {
- await user.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await expect(user.post('/user/class/cast/pickPocket'))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -112,7 +112,7 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targeted task doesn\'t exist', async () => {
- await user.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await expect(user.post(`/user/class/cast/pickPocket?targetId=${generateUUID()}`))
.to.eventually.be.rejected.and.eql({
code: 404,
@@ -122,13 +122,13 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if a challenge task was targeted', async () => {
- let {group, groupLeader} = await createAndPopulateGroup();
- let challenge = await generateChallenge(groupLeader, group);
+ const { group, groupLeader } = await createAndPopulateGroup();
+ const challenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: 'task text'},
+ { type: 'habit', text: 'task text' },
]);
- await groupLeader.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await groupLeader.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await sleep(0.5);
await groupLeader.sync();
await expect(groupLeader.post(`/user/class/cast/pickPocket?targetId=${groupLeader.tasksOrder.habits[0]}`))
@@ -140,19 +140,17 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if a group task was targeted', async () => {
- let {group, groupLeader} = await createAndPopulateGroup();
+ const { group, groupLeader } = await createAndPopulateGroup();
- let groupTask = await groupLeader.post(`/tasks/group/${group._id}`, {
+ const groupTask = await groupLeader.post(`/tasks/group/${group._id}`, {
text: 'todo group',
type: 'todo',
});
await groupLeader.post(`/tasks/${groupTask._id}/assign/${groupLeader._id}`);
- let memberTasks = await groupLeader.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === group._id;
- });
+ const memberTasks = await groupLeader.get('/tasks/user');
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === group._id);
- await groupLeader.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await groupLeader.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await sleep(0.5);
await groupLeader.sync();
@@ -165,23 +163,23 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targeted party member doesn\'t exist', async () => {
- let {groupLeader} = await createAndPopulateGroup({
+ const { groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'items.special.snowball': 3});
+ await groupLeader.update({ 'items.special.snowball': 3 });
- let target = generateUUID();
+ const target = generateUUID();
await expect(groupLeader.post(`/user/class/cast/snowball?targetId=${target}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: target}),
+ message: t('userWithIDNotFound', { userId: target }),
});
});
it('returns an error if party does not exists', async () => {
- await user.update({'items.special.snowball': 3});
+ await user.update({ 'items.special.snowball': 3 });
await expect(user.post(`/user/class/cast/snowball?targetId=${generateUUID()}`))
.to.eventually.be.rejected.and.eql({
@@ -192,11 +190,11 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('send message in party chat if party && !spell.silent', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13});
+ await groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13 });
await groupLeader.post('/user/class/cast/earth');
await sleep(1);
@@ -207,17 +205,17 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('Ethereal Surge does not recover mp of other mages', async () => {
- let group = await createAndPopulateGroup({
+ const group = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 4,
});
let promises = [];
- promises.push(group.groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 20}));
- promises.push(group.members[0].update({'stats.mp': 0, 'stats.class': 'warrior', 'stats.lvl': 20}));
- promises.push(group.members[1].update({'stats.mp': 0, 'stats.class': 'wizard', 'stats.lvl': 20}));
- promises.push(group.members[2].update({'stats.mp': 0, 'stats.class': 'rogue', 'stats.lvl': 20}));
- promises.push(group.members[3].update({'stats.mp': 0, 'stats.class': 'healer', 'stats.lvl': 20}));
+ promises.push(group.groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 20 }));
+ promises.push(group.members[0].update({ 'stats.mp': 0, 'stats.class': 'warrior', 'stats.lvl': 20 }));
+ promises.push(group.members[1].update({ 'stats.mp': 0, 'stats.class': 'wizard', 'stats.lvl': 20 }));
+ promises.push(group.members[2].update({ 'stats.mp': 0, 'stats.class': 'rogue', 'stats.lvl': 20 }));
+ promises.push(group.members[3].update({ 'stats.mp': 0, 'stats.class': 'healer', 'stats.lvl': 20 }));
await Promise.all(promises);
await group.groupLeader.post('/user/class/cast/mpheal');
@@ -236,13 +234,13 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('cast bulk', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ let { group, groupLeader } = await createAndPopulateGroup({ // eslint-disable-line prefer-const
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13});
- await groupLeader.post('/user/class/cast/earth', {quantity: 2});
+ await groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13 });
+ await groupLeader.post('/user/class/cast/earth', { quantity: 2 });
await sleep(1);
group = await groupLeader.get(`/groups/${group._id}`);
@@ -252,33 +250,32 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('searing brightness does not affect challenge or group tasks', async () => {
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test challenge habit',
type: 'habit',
});
- let groupTask = await user.post(`/tasks/group/${guild._id}`, {
+ const groupTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'todo group',
type: 'todo',
});
- await user.update({'stats.class': 'healer', 'stats.mp': 200, 'stats.lvl': 15});
+ await user.update({ 'stats.class': 'healer', 'stats.mp': 200, 'stats.lvl': 15 });
await user.post(`/tasks/${groupTask._id}/assign/${user._id}`);
await user.post('/user/class/cast/brightness');
await user.sync();
- let memberTasks = await user.get('/tasks/user');
+ const memberTasks = await user.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === guild._id;
- });
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === guild._id);
- let userChallengeTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.challenge.id === challenge._id;
- });
+ const userChallengeTask = find(
+ memberTasks,
+ memberTask => memberTask.challenge.id === challenge._id,
+ );
expect(userChallengeTask).to.exist;
expect(syncedGroupTask).to.exist;
@@ -287,12 +284,12 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('increases both user\'s achievement values', async () => {
- let party = await createAndPopulateGroup({
+ const party = await createAndPopulateGroup({
members: 1,
});
- let leader = party.groupLeader;
- let recipient = party.members[0];
- await leader.update({'stats.gp': 10});
+ const leader = party.groupLeader;
+ const recipient = party.members[0];
+ await leader.update({ 'stats.gp': 10 });
await leader.post(`/user/class/cast/birthday?targetId=${recipient._id}`);
await leader.sync();
await recipient.sync();
@@ -301,29 +298,29 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('only increases user\'s achievement one if target == caster', async () => {
- await user.update({'stats.gp': 10});
+ await user.update({ 'stats.gp': 10 });
await user.post(`/user/class/cast/birthday?targetId=${user._id}`);
await user.sync();
expect(user.achievements.birthday).to.equal(1);
});
it('passes correct target to spell when targetType === \'task\'', async () => {
- await user.update({'stats.class': 'wizard', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'wizard', 'stats.lvl': 11 });
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
- let result = await user.post(`/user/class/cast/fireball?targetId=${task._id}`);
+ const result = await user.post(`/user/class/cast/fireball?targetId=${task._id}`);
expect(result.task._id).to.equal(task._id);
});
it('passes correct target to spell when targetType === \'self\'', async () => {
- await user.update({'stats.class': 'wizard', 'stats.lvl': 14, 'stats.mp': 50});
+ await user.update({ 'stats.class': 'wizard', 'stats.lvl': 14, 'stats.mp': 50 });
- let result = await user.post('/user/class/cast/frost');
+ const result = await user.post('/user/class/cast/frost');
expect(result.user.stats.mp).to.equal(10);
});
diff --git a/test/api/v3/integration/user/POST-user_custom-day-start.test.js b/test/api/v3/integration/user/POST-user_custom-day-start.test.js
index 868b9ae91d..158c3667ae 100644
--- a/test/api/v3/integration/user/POST-user_custom-day-start.test.js
+++ b/test/api/v3/integration/user/POST-user_custom-day-start.test.js
@@ -5,7 +5,7 @@ import {
} from '../../../../helpers/api-integration/v3';
let user;
-let endpoint = '/user/custom-day-start';
+const endpoint = '/user/custom-day-start';
describe('POST /user/custom-day-start', () => {
beforeEach(async () => {
@@ -22,9 +22,9 @@ describe('POST /user/custom-day-start', () => {
});
it('sets lastCron to the current time to prevent an unexpected cron', async () => {
- let oldCron = moment().subtract(7, 'hours');
+ const oldCron = moment().subtract(7, 'hours');
- await user.update({lastCron: oldCron});
+ await user.update({ lastCron: oldCron });
await user.post(endpoint, { dayStart: 1 });
await user.sync();
@@ -32,7 +32,7 @@ describe('POST /user/custom-day-start', () => {
});
it('returns a confirmation message', async () => {
- let {message} = await user.post(endpoint, { dayStart: 1 });
+ const { message } = await user.post(endpoint, { dayStart: 1 });
expect(message).to.eql(t('customDayStartHasChanged'));
});
@@ -41,7 +41,7 @@ describe('POST /user/custom-day-start', () => {
await expect(user.post(endpoint, { dayStart: 'foo' }))
.to.eventually.be.rejected;
- await expect(user.post(endpoint, { dayStart: 24}))
+ await expect(user.post(endpoint, { dayStart: 24 }))
.to.eventually.be.rejected;
});
});
diff --git a/test/api/v3/integration/user/POST-user_disable-classes.test.js b/test/api/v3/integration/user/POST-user_disable-classes.test.js
index 0632a8adc7..30763e09af 100644
--- a/test/api/v3/integration/user/POST-user_disable-classes.test.js
+++ b/test/api/v3/integration/user/POST-user_disable-classes.test.js
@@ -12,7 +12,7 @@ describe('POST /user/disable-classes', () => {
// More tests in common code unit tests
it('disable classes', async () => {
- let res = await user.post('/user/disable-classes');
+ const res = await user.post('/user/disable-classes');
await user.sync();
expect(res).to.eql(JSON.parse(
@@ -20,7 +20,7 @@ describe('POST /user/disable-classes', () => {
preferences: user.preferences,
stats: user.stats,
flags: user.flags,
- })
+ }),
));
});
});
diff --git a/test/api/v3/integration/user/POST-user_equip_type_key.test.js b/test/api/v3/integration/user/POST-user_equip_type_key.test.js
index c5cde777df..aed598d583 100644
--- a/test/api/v3/integration/user/POST-user_equip_type_key.test.js
+++ b/test/api/v3/integration/user/POST-user_equip_type_key.test.js
@@ -32,7 +32,7 @@ describe('POST /user/equip/:type/:key', () => {
});
await user.post('/user/equip/equipped/weapon_warrior_1');
- let res = await user.post('/user/equip/equipped/weapon_warrior_2');
+ const res = await user.post('/user/equip/equipped/weapon_warrior_2');
await user.sync();
expect(res).to.eql(JSON.parse(JSON.stringify(user.items)));
diff --git a/test/api/v3/integration/user/POST-user_feed_pet_food.test.js b/test/api/v3/integration/user/POST-user_feed_pet_food.test.js
index 5026416795..9818b4ab9e 100644
--- a/test/api/v3/integration/user/POST-user_feed_pet_food.test.js
+++ b/test/api/v3/integration/user/POST-user_feed_pet_food.test.js
@@ -1,5 +1,6 @@
/* eslint-disable camelcase */
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
@@ -7,7 +8,6 @@ import {
sleep,
} from '../../../../helpers/api-integration/v3';
import content from '../../../../../website/common/script/content';
-import { v4 as generateUUID } from 'uuid';
describe('POST /user/feed/:pet/:food', () => {
let user;
@@ -24,10 +24,10 @@ describe('POST /user/feed/:pet/:food', () => {
'items.food.Milk': 2,
});
- let food = content.food.Milk;
- let pet = content.petInfo['Wolf-Base'];
+ const food = content.food.Milk;
+ const pet = content.petInfo['Wolf-Base'];
- let res = await user.post('/user/feed/Wolf-Base/Milk');
+ const res = await user.post('/user/feed/Wolf-Base/Milk');
await user.sync();
expect(res).to.eql({
data: user.items.pets['Wolf-Base'],
@@ -51,7 +51,7 @@ describe('POST /user/feed/:pet/:food', () => {
});
it('sends user activity webhook when a new mount is raised', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -66,11 +66,11 @@ describe('POST /user/feed/:pet/:food', () => {
'items.pets.Wolf-Base': 49,
'items.food.Milk': 2,
});
- let res = await user.post('/user/feed/Wolf-Base/Milk');
+ const res = await user.post('/user/feed/Wolf-Base/Milk');
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('mountRaised');
expect(body.pet).to.eql('Wolf-Base');
diff --git a/test/api/v3/integration/user/POST-user_hatch_egg_hatchingPotion.test.js b/test/api/v3/integration/user/POST-user_hatch_egg_hatchingPotion.test.js
index 2aaa54e5e5..9f5c6ce7b5 100644
--- a/test/api/v3/integration/user/POST-user_hatch_egg_hatchingPotion.test.js
+++ b/test/api/v3/integration/user/POST-user_hatch_egg_hatchingPotion.test.js
@@ -1,10 +1,10 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
server,
sleep,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
describe('POST /user/hatch/:egg/:hatchingPotion', () => {
let user;
@@ -20,7 +20,7 @@ describe('POST /user/hatch/:egg/:hatchingPotion', () => {
'items.eggs.Wolf': 1,
'items.hatchingPotions.Base': 1,
});
- let res = await user.post('/user/hatch/Wolf/Base');
+ const res = await user.post('/user/hatch/Wolf/Base');
await user.sync();
expect(user.items.pets['Wolf-Base']).to.equal(5);
expect(user.items.eggs.Wolf).to.equal(0);
@@ -42,7 +42,7 @@ describe('POST /user/hatch/:egg/:hatchingPotion', () => {
});
it('sends user activity webhook when a new pet is hatched', async () => {
- let uuid = generateUUID();
+ const uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
@@ -57,11 +57,11 @@ describe('POST /user/hatch/:egg/:hatchingPotion', () => {
'items.eggs.Wolf': 1,
'items.hatchingPotions.Base': 1,
});
- let res = await user.post('/user/hatch/Wolf/Base');
+ const res = await user.post('/user/hatch/Wolf/Base');
await sleep();
- let body = server.getWebhookData(uuid);
+ const body = server.getWebhookData(uuid);
expect(body.type).to.eql('petHatched');
expect(body.pet).to.eql('Wolf-Base');
diff --git a/test/api/v3/integration/user/POST-user_open_mystery_item.test.js b/test/api/v3/integration/user/POST-user_open_mystery_item.test.js
index 1c81cfe439..9fbd3cadcc 100644
--- a/test/api/v3/integration/user/POST-user_open_mystery_item.test.js
+++ b/test/api/v3/integration/user/POST-user_open_mystery_item.test.js
@@ -6,16 +6,16 @@ import content from '../../../../../website/common/script/content/index';
describe('POST /user/open-mystery-item', () => {
let user;
- let mysteryItemKey = 'eyewear_special_summerRogue';
- let mysteryItemIndex = content.gear.flat[mysteryItemKey].index;
- let mysteryItemType = content.gear.flat[mysteryItemKey].type;
- let mysteryItemText = content.gear.flat[mysteryItemKey].text();
+ const mysteryItemKey = 'eyewear_special_summerRogue';
+ const mysteryItemIndex = content.gear.flat[mysteryItemKey].index;
+ const mysteryItemType = content.gear.flat[mysteryItemKey].type;
+ const mysteryItemText = content.gear.flat[mysteryItemKey].text();
beforeEach(async () => {
user = await generateUser({
'purchased.plan.mysteryItems': [mysteryItemKey],
notifications: [
- {type: 'NEW_MYSTERY_ITEMS', data: { items: [mysteryItemKey] }},
+ { type: 'NEW_MYSTERY_ITEMS', data: { items: [mysteryItemKey] } },
],
});
});
@@ -24,7 +24,7 @@ describe('POST /user/open-mystery-item', () => {
it('opens a mystery item', async () => {
expect(user.notifications.length).to.equal(1);
- let response = await user.post('/user/open-mystery-item');
+ const response = await user.post('/user/open-mystery-item');
await user.sync();
expect(user.notifications.length).to.equal(0);
diff --git a/test/api/v3/integration/user/POST-user_purchase.test.js b/test/api/v3/integration/user/POST-user_purchase.test.js
index b1d3749256..502bcb3790 100644
--- a/test/api/v3/integration/user/POST-user_purchase.test.js
+++ b/test/api/v3/integration/user/POST-user_purchase.test.js
@@ -6,8 +6,8 @@ import {
describe('POST /user/purchase/:type/:key', () => {
let user;
- let type = 'hatchingPotions';
- let key = 'Base';
+ const type = 'hatchingPotions';
+ const key = 'Base';
beforeEach(async () => {
user = await generateUser({
@@ -34,7 +34,7 @@ describe('POST /user/purchase/:type/:key', () => {
});
it('can convert gold to gems if subscribed', async () => {
- let oldBalance = user.balance;
+ const oldBalance = user.balance;
await user.update({
'purchased.plan.customerId': 'group-plan',
'stats.gp': 1000,
@@ -45,7 +45,7 @@ describe('POST /user/purchase/:type/:key', () => {
});
it('leader can convert gold to gems even if the group plan prevents it', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: {
name: 'test',
type: 'guild',
@@ -57,7 +57,7 @@ describe('POST /user/purchase/:type/:key', () => {
'purchased.plan.customerId': 123,
});
await groupLeader.sync();
- let oldBalance = groupLeader.balance;
+ const oldBalance = groupLeader.balance;
await groupLeader.update({
'purchased.plan.customerId': 'group-plan',
@@ -70,7 +70,7 @@ describe('POST /user/purchase/:type/:key', () => {
});
it('cannot convert gold to gems if the group plan prevents it', async () => {
- let { group, members } = await createAndPopulateGroup({
+ const { group, members } = await createAndPopulateGroup({
groupDetails: {
name: 'test',
type: 'guild',
@@ -82,7 +82,7 @@ describe('POST /user/purchase/:type/:key', () => {
'leaderOnly.getGems': true,
'purchased.plan.customerId': 123,
});
- let oldBalance = members[0].balance;
+ const oldBalance = members[0].balance;
await members[0].update({
'purchased.plan.customerId': 'group-plan',
@@ -101,19 +101,19 @@ describe('POST /user/purchase/:type/:key', () => {
describe('bulk purchasing', () => {
it('purchases a gem item', async () => {
- await user.post(`/user/purchase/${type}/${key}`, {quantity: 2});
+ await user.post(`/user/purchase/${type}/${key}`, { quantity: 2 });
await user.sync();
expect(user.items[type][key]).to.equal(2);
});
it('can convert gold to gems if subscribed', async () => {
- let oldBalance = user.balance;
+ const oldBalance = user.balance;
await user.update({
'purchased.plan.customerId': 'group-plan',
'stats.gp': 1000,
});
- await user.post('/user/purchase/gems/gem', {quantity: 2});
+ await user.post('/user/purchase/gems/gem', { quantity: 2 });
await user.sync();
expect(user.balance).to.equal(oldBalance + 0.50);
});
diff --git a/test/api/v3/integration/user/POST-user_purchase_hourglass.test.js b/test/api/v3/integration/user/POST-user_purchase_hourglass.test.js
index 721eb69aa9..3133354b71 100644
--- a/test/api/v3/integration/user/POST-user_purchase_hourglass.test.js
+++ b/test/api/v3/integration/user/POST-user_purchase_hourglass.test.js
@@ -15,7 +15,7 @@ describe('POST /user/purchase-hourglass/:type/:key', () => {
// More tests in common code unit tests
it('buys an hourglass pet', async () => {
- let response = await user.post('/user/purchase-hourglass/pets/MantisShrimp-Base');
+ const response = await user.post('/user/purchase-hourglass/pets/MantisShrimp-Base');
await user.sync();
expect(response.message).to.eql(t('hourglassPurchase'));
@@ -24,7 +24,7 @@ describe('POST /user/purchase-hourglass/:type/:key', () => {
});
it('buys an hourglass quest', async () => {
- let response = await user.post('/user/purchase-hourglass/quests/robot');
+ const response = await user.post('/user/purchase-hourglass/quests/robot');
await user.sync();
expect(response.message).to.eql(t('hourglassPurchase'));
@@ -33,7 +33,7 @@ describe('POST /user/purchase-hourglass/:type/:key', () => {
});
it('buys multiple hourglass quests', async () => {
- let response = await user.post('/user/purchase-hourglass/quests/robot', {quantity: 2});
+ const response = await user.post('/user/purchase-hourglass/quests/robot', { quantity: 2 });
await user.sync();
expect(response.message).to.eql(t('hourglassPurchase'));
diff --git a/test/api/v3/integration/user/POST-user_push_device.test.js b/test/api/v3/integration/user/POST-user_push_device.test.js
index a0c302de71..9c39616cc8 100644
--- a/test/api/v3/integration/user/POST-user_push_device.test.js
+++ b/test/api/v3/integration/user/POST-user_push_device.test.js
@@ -5,15 +5,15 @@ import {
describe('POST /user/push-devices', () => {
let user;
- let regId = '10';
- let type = 'ios';
+ const regId = '10';
+ const type = 'ios';
beforeEach(async () => {
user = await generateUser();
});
it('returns an error when regId is not provided', async () => {
- await expect(user.post('/user/push-devices'), {type})
+ await expect(user.post('/user/push-devices'), { type })
.to.eventually.be.rejected.and.to.eql({
code: 400,
error: 'BadRequest',
@@ -22,7 +22,7 @@ describe('POST /user/push-devices', () => {
});
it('returns an error when type is not provided', async () => {
- await expect(user.post('/user/push-devices', {regId}))
+ await expect(user.post('/user/push-devices', { regId }))
.to.eventually.be.rejected.and.to.eql({
code: 400,
error: 'BadRequest',
@@ -31,7 +31,7 @@ describe('POST /user/push-devices', () => {
});
it('returns an error when type is not valid', async () => {
- await expect(user.post('/user/push-devices', {regId, type: 'invalid'}))
+ await expect(user.post('/user/push-devices', { regId, type: 'invalid' }))
.to.eventually.be.rejected.and.to.eql({
code: 400,
error: 'BadRequest',
@@ -40,8 +40,8 @@ describe('POST /user/push-devices', () => {
});
it('fails silently if user already has the push device', async () => {
- await user.post('/user/push-devices', {type, regId});
- const response = await user.post('/user/push-devices', {type, regId});
+ await user.post('/user/push-devices', { type, regId });
+ const response = await user.post('/user/push-devices', { type, regId });
await user.sync();
expect(response.message).to.equal(t('pushDeviceAdded'));
@@ -52,7 +52,7 @@ describe('POST /user/push-devices', () => {
});
it('adds a push device to the user', async () => {
- const response = await user.post('/user/push-devices', {type, regId});
+ const response = await user.post('/user/push-devices', { type, regId });
await user.sync();
expect(response.message).to.equal(t('pushDeviceAdded'));
@@ -63,7 +63,7 @@ describe('POST /user/push-devices', () => {
});
it('removes a push device to the user', async () => {
- await user.post('/user/push-devices', {type, regId});
+ await user.post('/user/push-devices', { type, regId });
const response = await user.del(`/user/push-devices/${regId}`);
await user.sync();
diff --git a/test/api/v3/integration/user/POST-user_read_card.test.js b/test/api/v3/integration/user/POST-user_read_card.test.js
index bb8f388db2..c04d24c734 100644
--- a/test/api/v3/integration/user/POST-user_read_card.test.js
+++ b/test/api/v3/integration/user/POST-user_read_card.test.js
@@ -5,7 +5,7 @@ import {
describe('POST /user/read-card/:cardType', () => {
let user;
- let cardType = 'greeting';
+ const cardType = 'greeting';
beforeEach(async () => {
user = await generateUser();
@@ -28,17 +28,17 @@ describe('POST /user/read-card/:cardType', () => {
'flags.cardReceived': true,
notifications: [{
type: 'CARD_RECEIVED',
- data: {card: cardType},
+ data: { card: cardType },
}],
});
await user.sync();
expect(user.notifications.length).to.equal(1);
- let response = await user.post(`/user/read-card/${cardType}`);
+ const response = await user.post(`/user/read-card/${cardType}`);
await user.sync();
- expect(response.message).to.equal(t('readCard', {cardType}));
+ expect(response.message).to.equal(t('readCard', { cardType }));
expect(user.items.special[`${cardType}Received`]).to.be.empty;
expect(user.flags.cardReceived).to.be.false;
expect(user.notifications.length).to.equal(0);
diff --git a/test/api/v3/integration/user/POST-user_rebirth.test.js b/test/api/v3/integration/user/POST-user_rebirth.test.js
index 6182091ad7..87826148f4 100644
--- a/test/api/v3/integration/user/POST-user_rebirth.test.js
+++ b/test/api/v3/integration/user/POST-user_rebirth.test.js
@@ -28,7 +28,7 @@ describe('POST /user/rebirth', () => {
balance: 1.5,
});
- let daily = await generateDaily({
+ const daily = await generateDaily({
text: 'test habit',
type: 'daily',
value: 1,
@@ -36,21 +36,21 @@ describe('POST /user/rebirth', () => {
userId: user._id,
});
- let reward = await generateReward({
+ const reward = await generateReward({
text: 'test reward',
type: 'reward',
value: 1,
userId: user._id,
});
- let response = await user.post('/user/rebirth');
+ const response = await user.post('/user/rebirth');
await user.sync();
expect(user.notifications.length).to.equal(1);
expect(user.notifications[0].type).to.equal('REBIRTH_ACHIEVEMENT');
- let updatedDaily = await user.get(`/tasks/${daily._id}`);
- let updatedReward = await user.get(`/tasks/${reward._id}`);
+ const updatedDaily = await user.get(`/tasks/${daily._id}`);
+ const updatedReward = await user.get(`/tasks/${reward._id}`);
expect(response.message).to.equal(t('rebirthComplete'));
expect(updatedDaily.streak).to.equal(0);
diff --git a/test/api/v3/integration/user/POST-user_release_both.test.js b/test/api/v3/integration/user/POST-user_release_both.test.js
index bbd11587c0..8519f1b359 100644
--- a/test/api/v3/integration/user/POST-user_release_both.test.js
+++ b/test/api/v3/integration/user/POST-user_release_both.test.js
@@ -6,21 +6,21 @@ import content from '../../../../../website/common/script/content/index';
describe('POST /user/release-both', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
const loadPets = () => {
- let pets = {};
- for (let p in content.pets) {
+ const pets = {};
+ Object.keys(content.pets).forEach(p => {
pets[p] = content.pets[p];
pets[p] = 5;
- }
+ });
return pets;
};
const loadMounts = () => {
- let mounts = {};
- for (let m in content.pets) {
+ const mounts = {};
+ Object.keys(content.pets).forEach(m => {
mounts[m] = content.pets[m];
mounts[m] = true;
- }
+ });
return mounts;
};
@@ -49,7 +49,7 @@ describe('POST /user/release-both', () => {
it('grants triad bingo with gems', async () => {
await user.update();
- let response = await user.post('/user/release-both');
+ const response = await user.post('/user/release-both');
await user.sync();
expect(response.message).to.equal(t('mountsAndPetsReleased'));
diff --git a/test/api/v3/integration/user/POST-user_release_mounts.test.js b/test/api/v3/integration/user/POST-user_release_mounts.test.js
index 728aa99c8c..10403028c3 100644
--- a/test/api/v3/integration/user/POST-user_release_mounts.test.js
+++ b/test/api/v3/integration/user/POST-user_release_mounts.test.js
@@ -6,14 +6,14 @@ import content from '../../../../../website/common/script/content/index';
describe('POST /user/release-mounts', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
const loadMounts = () => {
- let mounts = {};
- for (let m in content.pets) {
+ const mounts = {};
+ Object.keys(content.pets).forEach(m => {
mounts[m] = content.pets[m];
mounts[m] = true;
- }
+ });
return mounts;
};
@@ -40,7 +40,7 @@ describe('POST /user/release-mounts', () => {
balance: 1,
});
- let response = await user.post('/user/release-mounts');
+ const response = await user.post('/user/release-mounts');
await user.sync();
expect(response.message).to.equal(t('mountsReleased'));
diff --git a/test/api/v3/integration/user/POST-user_release_pets.test.js b/test/api/v3/integration/user/POST-user_release_pets.test.js
index 35b8126a82..96834cc044 100644
--- a/test/api/v3/integration/user/POST-user_release_pets.test.js
+++ b/test/api/v3/integration/user/POST-user_release_pets.test.js
@@ -6,14 +6,14 @@ import content from '../../../../../website/common/script/content/index';
describe('POST /user/release-pets', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
const loadPets = () => {
- let pets = {};
- for (let p in content.pets) {
+ const pets = {};
+ Object.keys(content.pets).forEach(p => {
pets[p] = content.pets[p];
pets[p] = 5;
- }
+ });
return pets;
};
@@ -40,7 +40,7 @@ describe('POST /user/release-pets', () => {
balance: 1,
});
- let response = await user.post('/user/release-pets');
+ const response = await user.post('/user/release-pets');
await user.sync();
expect(response.message).to.equal(t('petsReleased'));
diff --git a/test/api/v3/integration/user/POST-user_reroll.test.js b/test/api/v3/integration/user/POST-user_reroll.test.js
index 29774d1239..37d4b6eb6d 100644
--- a/test/api/v3/integration/user/POST-user_reroll.test.js
+++ b/test/api/v3/integration/user/POST-user_reroll.test.js
@@ -28,24 +28,24 @@ describe('POST /user/reroll', () => {
balance: 2,
});
- let daily = await generateDaily({
+ const daily = await generateDaily({
text: 'test habit',
type: 'daily',
userId: user._id,
});
- let reward = await generateReward({
+ const reward = await generateReward({
text: 'test reward',
type: 'reward',
value: 1,
userId: user._id,
});
- let response = await user.post('/user/reroll');
+ const response = await user.post('/user/reroll');
await user.sync();
- let updatedDaily = await user.get(`/tasks/${daily._id}`);
- let updatedReward = await user.get(`/tasks/${reward._id}`);
+ const updatedDaily = await user.get(`/tasks/${daily._id}`);
+ const updatedReward = await user.get(`/tasks/${reward._id}`);
expect(response.message).to.equal(t('fortifyComplete'));
expect(updatedDaily.value).to.equal(0);
diff --git a/test/api/v3/integration/user/POST-user_reset.test.js b/test/api/v3/integration/user/POST-user_reset.test.js
index 902dd7cd65..389b840d92 100644
--- a/test/api/v3/integration/user/POST-user_reset.test.js
+++ b/test/api/v3/integration/user/POST-user_reset.test.js
@@ -1,10 +1,10 @@
+import { find } from 'lodash';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { find } from 'lodash';
describe('POST /user/reset', () => {
let user;
@@ -16,7 +16,7 @@ describe('POST /user/reset', () => {
// More tests in common code unit tests
it('resets user\'s habits', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -34,7 +34,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s dailys', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
});
@@ -52,7 +52,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s todos', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
});
@@ -70,7 +70,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s rewards', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
});
@@ -88,15 +88,15 @@ describe('POST /user/reset', () => {
});
it('does not delete challenge or group tasks', async () => {
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test challenge habit',
type: 'habit',
});
- let groupTask = await user.post(`/tasks/group/${guild._id}`, {
+ const groupTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'todo group',
type: 'todo',
});
@@ -105,15 +105,14 @@ describe('POST /user/reset', () => {
await user.post('/user/reset');
await user.sync();
- let memberTasks = await user.get('/tasks/user');
+ const memberTasks = await user.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === guild._id;
- });
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === guild._id);
- let userChallengeTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.challenge.id === challenge._id;
- });
+ const userChallengeTask = find(
+ memberTasks,
+ memberTask => memberTask.challenge.id === challenge._id,
+ );
expect(userChallengeTask).to.exist;
expect(syncedGroupTask).to.exist;
diff --git a/test/api/v3/integration/user/POST-user_revive.test.js b/test/api/v3/integration/user/POST-user_revive.test.js
index 6ba85ac87f..e042dfd9f7 100644
--- a/test/api/v3/integration/user/POST-user_revive.test.js
+++ b/test/api/v3/integration/user/POST-user_revive.test.js
@@ -8,7 +8,7 @@ describe('POST /user/revive', () => {
beforeEach(async () => {
user = await generateUser({
- 'user.items.gear.owned': {weaponKey: true},
+ 'user.items.gear.owned': { weaponKey: true },
});
});
diff --git a/test/api/v3/integration/user/POST-user_sell.test.js b/test/api/v3/integration/user/POST-user_sell.test.js
index c9a0fdba64..896e9bf280 100644
--- a/test/api/v3/integration/user/POST-user_sell.test.js
+++ b/test/api/v3/integration/user/POST-user_sell.test.js
@@ -6,8 +6,8 @@ import content from '../../../../../website/common/script/content';
describe('POST /user/sell/:type/:key', () => {
let user;
- let type = 'eggs';
- let key = 'Wolf';
+ const type = 'eggs';
+ const key = 'Wolf';
beforeEach(async () => {
user = await generateUser();
@@ -20,7 +20,7 @@ describe('POST /user/sell/:type/:key', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userItemsKeyNotFound', {type}),
+ message: t('userItemsKeyNotFound', { type }),
});
});
diff --git a/test/api/v3/integration/user/POST-user_sleep.test.js b/test/api/v3/integration/user/POST-user_sleep.test.js
index 292b77e9db..9afb4a1956 100644
--- a/test/api/v3/integration/user/POST-user_sleep.test.js
+++ b/test/api/v3/integration/user/POST-user_sleep.test.js
@@ -13,12 +13,12 @@ describe('POST /user/sleep', () => {
// More tests in common code unit tests
it('toggles sleep status', async () => {
- let res = await user.post('/user/sleep');
+ const res = await user.post('/user/sleep');
expect(res).to.eql(true);
await user.sync();
expect(user.preferences.sleep).to.be.true;
- let res2 = await user.post('/user/sleep');
+ const res2 = await user.post('/user/sleep');
expect(res2).to.eql(false);
await user.sync();
expect(user.preferences.sleep).to.be.false;
diff --git a/test/api/v3/integration/user/POST-user_unlock.js b/test/api/v3/integration/user/POST-user_unlock.js
index 6dbdb3c1b1..4418af54c3 100644
--- a/test/api/v3/integration/user/POST-user_unlock.js
+++ b/test/api/v3/integration/user/POST-user_unlock.js
@@ -5,9 +5,9 @@ import {
describe('POST /user/unlock', () => {
let user;
- let unlockPath = 'shirt.convict,shirt.cross,shirt.fire,shirt.horizon,shirt.ocean,shirt.purple,shirt.rainbow,shirt.redblue,shirt.thunder,shirt.tropical,shirt.zombie';
- let unlockCost = 1.25;
- let usersStartingGems = 5;
+ const unlockPath = 'shirt.convict,shirt.cross,shirt.fire,shirt.horizon,shirt.ocean,shirt.purple,shirt.rainbow,shirt.redblue,shirt.thunder,shirt.tropical,shirt.zombie';
+ const unlockCost = 1.25;
+ const usersStartingGems = 5;
beforeEach(async () => {
user = await generateUser();
@@ -28,7 +28,7 @@ describe('POST /user/unlock', () => {
await user.update({
balance: usersStartingGems,
});
- let response = await user.post(`/user/unlock?path=${unlockPath}`);
+ const response = await user.post(`/user/unlock?path=${unlockPath}`);
await user.sync();
expect(response.message).to.equal(t('unlocked'));
diff --git a/test/api/v3/integration/user/PUT-user.test.js b/test/api/v3/integration/user/PUT-user.test.js
index bef5ec25d0..b1f576a791 100644
--- a/test/api/v3/integration/user/PUT-user.test.js
+++ b/test/api/v3/integration/user/PUT-user.test.js
@@ -1,9 +1,9 @@
+import { each, get } from 'lodash';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { each, get } from 'lodash';
describe('PUT /user', () => {
let user;
@@ -40,7 +40,7 @@ describe('PUT /user', () => {
});
it('update tags', async () => {
- let userTags = user.tags;
+ const userTags = user.tags;
await user.put('/user', {
tags: [...user.tags, {
@@ -98,20 +98,20 @@ describe('PUT /user', () => {
});
context('Top Level Protected Operations', () => {
- let protectedOperations = {
- 'gem balance': {balance: 100},
- auth: {'auth.blocked': true, 'auth.timestamps.created': new Date()},
- contributor: {'contributor.level': 9, 'contributor.admin': true, 'contributor.text': 'some text'},
- backer: {'backer.tier': 10, 'backer.npc': 'Bilbo'},
- subscriptions: {'purchased.plan.extraMonths': 500, 'purchased.plan.consecutive.trinkets': 1000},
- 'customization gem purchases': {'purchased.background.tavern': true, 'purchased.skin.bear': true},
- notifications: [{type: 123}],
- webhooks: {webhooks: [{url: 'https://foobar.com'}]},
+ const protectedOperations = {
+ 'gem balance': { balance: 100 },
+ auth: { 'auth.blocked': true, 'auth.timestamps.created': new Date() },
+ contributor: { 'contributor.level': 9, 'contributor.admin': true, 'contributor.text': 'some text' },
+ backer: { 'backer.tier': 10, 'backer.npc': 'Bilbo' },
+ subscriptions: { 'purchased.plan.extraMonths': 500, 'purchased.plan.consecutive.trinkets': 1000 },
+ 'customization gem purchases': { 'purchased.background.tavern': true, 'purchased.skin.bear': true },
+ notifications: [{ type: 123 }],
+ webhooks: { webhooks: [{ url: 'https://foobar.com' }] },
};
each(protectedOperations, (data, testName) => {
it(`does not allow updating ${testName}`, async () => {
- let errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
+ const errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
await expect(user.put('/user', data)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -123,17 +123,17 @@ describe('PUT /user', () => {
});
context('Sub-Level Protected Operations', () => {
- let protectedOperations = {
- 'class stat': {'stats.class': 'wizard'},
- 'flags unless whitelisted': {'flags.dropsEnabled': true},
- webhooks: {'preferences.webhooks': [1, 2, 3]},
- sleep: {'preferences.sleep': true},
- 'disable classes': {'preferences.disableClasses': true},
+ const protectedOperations = {
+ 'class stat': { 'stats.class': 'wizard' },
+ 'flags unless whitelisted': { 'flags.dropsEnabled': true },
+ webhooks: { 'preferences.webhooks': [1, 2, 3] },
+ sleep: { 'preferences.sleep': true },
+ 'disable classes': { 'preferences.disableClasses': true },
};
each(protectedOperations, (data, testName) => {
it(`does not allow updating ${testName}`, async () => {
- let errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
+ const errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
await expect(user.put('/user', data)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -145,7 +145,7 @@ describe('PUT /user', () => {
});
context('Default Appearance Preferences', () => {
- let testCases = {
+ const testCases = {
shirt: 'yellow',
skin: 'ddc994',
'hair.color': 'blond',
@@ -160,14 +160,14 @@ describe('PUT /user', () => {
update[`preferences.${type}`] = item;
it(`updates user with ${type} that is a default`, async () => {
- let dbUpdate = {};
+ const dbUpdate = {};
dbUpdate[`purchased.${type}.${item}`] = true;
await user.update(dbUpdate);
// Sanity checks to make sure user is not already equipped with item
expect(get(user.preferences, type)).to.not.eql(item);
- let updatedUser = await user.put('/user', update);
+ const updatedUser = await user.put('/user', update);
expect(get(updatedUser.preferences, type)).to.eql(item);
});
@@ -189,7 +189,7 @@ describe('PUT /user', () => {
'preferences.hair.beard': 3,
});
- let updatedUser = await user.put('/user', {
+ const updatedUser = await user.put('/user', {
'preferences.hair.beard': 0,
});
@@ -202,7 +202,7 @@ describe('PUT /user', () => {
'preferences.hair.mustache': 2,
});
- let updatedUser = await user.put('/user', {
+ const updatedUser = await user.put('/user', {
'preferences.hair.mustache': 0,
});
@@ -211,7 +211,7 @@ describe('PUT /user', () => {
});
context('Purchasable Appearance Preferences', () => {
- let testCases = {
+ const testCases = {
background: 'volcano',
shirt: 'convict',
skin: 'cactus',
@@ -229,19 +229,19 @@ describe('PUT /user', () => {
await expect(user.put('/user', update)).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('mustPurchaseToSet', {val: item, key: `preferences.${type}`}),
+ message: t('mustPurchaseToSet', { val: item, key: `preferences.${type}` }),
});
});
it(`updates user with ${type} user does own`, async () => {
- let dbUpdate = {};
+ const dbUpdate = {};
dbUpdate[`purchased.${type}.${item}`] = true;
await user.update(dbUpdate);
// Sanity check to make sure user is not already equipped with item
expect(get(user.preferences, type)).to.not.eql(item);
- let updatedUser = await user.put('/user', update);
+ const updatedUser = await user.put('/user', update);
expect(get(updatedUser.preferences, type)).to.eql(item);
});
diff --git a/test/api/v3/integration/user/auth/DELETE-user_auth_social_network.test.js b/test/api/v3/integration/user/auth/DELETE-user_auth_social_network.test.js
index 55c5522322..3f25404d50 100644
--- a/test/api/v3/integration/user/auth/DELETE-user_auth_social_network.test.js
+++ b/test/api/v3/integration/user/auth/DELETE-user_auth_social_network.test.js
@@ -38,7 +38,7 @@ describe('DELETE social registration', () => {
'auth.facebook.id': 'some-fb-id',
});
- let response = await user.del('/user/auth/social/facebook');
+ const response = await user.del('/user/auth/social/facebook');
expect(response).to.eql({});
await user.sync();
expect(user.auth.facebook).to.be.undefined;
@@ -51,7 +51,7 @@ describe('DELETE social registration', () => {
'auth.local': { ok: true },
});
- let response = await user.del('/user/auth/social/facebook');
+ const response = await user.del('/user/auth/social/facebook');
expect(response).to.eql({});
await user.sync();
expect(user.auth.facebook).to.be.undefined;
@@ -76,7 +76,7 @@ describe('DELETE social registration', () => {
'auth.google.id': 'some-google-id',
});
- let response = await user.del('/user/auth/social/google');
+ const response = await user.del('/user/auth/social/google');
expect(response).to.eql({});
await user.sync();
expect(user.auth.google).to.be.undefined;
@@ -89,7 +89,7 @@ describe('DELETE social registration', () => {
'auth.local': { ok: true },
});
- let response = await user.del('/user/auth/social/google');
+ const response = await user.del('/user/auth/social/google');
expect(response).to.eql({});
await user.sync();
expect(user.auth.goodl).to.be.undefined;
diff --git a/test/api/v3/integration/user/auth/GET-auth_reset-password-set-new-one.js b/test/api/v3/integration/user/auth/GET-auth_reset-password-set-new-one.js
index 760041b529..b805c4be02 100644
--- a/test/api/v3/integration/user/auth/GET-auth_reset-password-set-new-one.js
+++ b/test/api/v3/integration/user/auth/GET-auth_reset-password-set-new-one.js
@@ -1,18 +1,18 @@
-import {
- encrypt,
-} from '../../../../../../website/server/libs/encryption';
import moment from 'moment';
+import superagent from 'superagent';
+import nconf from 'nconf';
import {
generateUser,
} from '../../../../../helpers/api-integration/v3';
-import superagent from 'superagent';
-import nconf from 'nconf';
+import {
+ encrypt,
+} from '../../../../../../website/server/libs/encryption';
const API_TEST_SERVER_PORT = nconf.get('PORT');
// @TODO skipped because on travis the client isn't available and the redirect fails
xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
- let endpoint = `http://localhost:${API_TEST_SERVER_PORT}/static/user/auth/local/reset-password-set-new-one`;
+ const endpoint = `http://localhost:${API_TEST_SERVER_PORT}/static/user/auth/local/reset-password-set-new-one`;
// Tests to validate the validatePasswordResetCodeAndFindUser function
@@ -27,9 +27,9 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
});
it('renders an error page if the code cannot be decrypted', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = JSON.stringify({ // not encrypted
+ const code = JSON.stringify({ // not encrypted
userId: user._id,
expiresAt: new Date(),
});
@@ -38,11 +38,11 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
});
it('renders an error page if the code is expired', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().subtract({minutes: 1}),
+ expiresAt: moment().subtract({ minutes: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
@@ -53,9 +53,9 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
});
it('renders an error page if the user does not exist', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: Date.now().toString(),
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
const res = await superagent.get(`${endpoint}?code=${code}`);
@@ -63,11 +63,11 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
});
it('renders an error page if the user has no local auth', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
auth: 'not an object with valid fields',
@@ -78,11 +78,11 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
});
it('renders an error page if the code doesn\'t match the one saved at user.auth.passwordResetCode', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': 'invalid',
@@ -95,19 +95,18 @@ xdescribe('GET /user/auth/local/reset-password-set-new-one', () => {
//
it('returns the password reset page if the password reset code is valid', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
});
- let res = await superagent.get(`${endpoint}?code=${code}`);
+ const res = await superagent.get(`${endpoint}?code=${code}`);
expect(res.req.path.indexOf('hasError=false') !== -1).to.equal(true);
expect(res.req.path.indexOf('code=') !== -1).to.equal(true);
});
});
-
diff --git a/test/api/v3/integration/user/auth/POST-auth_reset-password-set-new-one.js b/test/api/v3/integration/user/auth/POST-auth_reset-password-set-new-one.js
index f4a9a4cbf1..ed3cf27e63 100644
--- a/test/api/v3/integration/user/auth/POST-auth_reset-password-set-new-one.js
+++ b/test/api/v3/integration/user/auth/POST-auth_reset-password-set-new-one.js
@@ -1,3 +1,4 @@
+import moment from 'moment';
import {
encrypt,
} from '../../../../../../website/server/libs/encryption';
@@ -7,7 +8,6 @@ import {
sha1MakeSalt,
sha1Encrypt as sha1EncryptPassword,
} from '../../../../../../website/server/libs/password';
-import moment from 'moment';
import {
generateUser,
requester,
@@ -36,9 +36,9 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders an error page if the code cannot be decrypted', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = JSON.stringify({ // not encrypted
+ const code = JSON.stringify({ // not encrypted
userId: user._id,
expiresAt: new Date(),
});
@@ -53,11 +53,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders an error page if the code is expired', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().subtract({minutes: 1}),
+ expiresAt: moment().subtract({ minutes: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
@@ -73,9 +73,9 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders an error page if the user does not exist', async () => {
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: Date.now().toString(),
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await expect(api.post(`${endpoint}`, {
@@ -88,11 +88,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders an error page if the user has no local auth', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await expect(api.post(`${endpoint}`, {
@@ -105,11 +105,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders an error page if the code doesn\'t match the one saved at user.auth.passwordResetCode', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': 'invalid',
@@ -127,11 +127,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
//
it('renders the error page if the new password is missing', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
@@ -147,11 +147,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders the error page if the password confirmation is missing', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
@@ -168,11 +168,11 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders the error page if the password confirmation does not match', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
@@ -190,17 +190,17 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
});
it('renders the success page and save the user', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
});
- let res = await api.post(`${endpoint}`, {
+ const res = await api.post(`${endpoint}`, {
newPassword: 'my new password',
confirmPassword: 'my new password',
code,
@@ -212,16 +212,16 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
expect(user.auth.local.passwordResetCode).to.equal(undefined);
expect(user.auth.local.passwordHashMethod).to.equal('bcrypt');
expect(user.auth.local.salt).to.be.undefined;
- let isPassValid = await compare(user, 'my new password');
+ const isPassValid = await compare(user, 'my new password');
expect(isPassValid).to.equal(true);
});
it('renders the success page and convert the password from sha1 to bcrypt', async () => {
- let user = await generateUser();
+ const user = await generateUser();
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -234,15 +234,15 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
expect(user.auth.local.salt).to.equal(salt);
expect(user.auth.local.hashed_password).to.equal(sha1HashedPassword);
- let code = encrypt(JSON.stringify({
+ const code = encrypt(JSON.stringify({
userId: user._id,
- expiresAt: moment().add({days: 1}),
+ expiresAt: moment().add({ days: 1 }),
}));
await user.update({
'auth.local.passwordResetCode': code,
});
- let res = await api.post(`${endpoint}`, {
+ const res = await api.post(`${endpoint}`, {
newPassword: 'my new password',
confirmPassword: 'my new password',
code,
@@ -256,7 +256,7 @@ describe('POST /user/auth/reset-password-set-new-one', () => {
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
- let isValidPassword = await bcryptCompare('my new password', user.auth.local.hashed_password);
+ const isValidPassword = await bcryptCompare('my new password', user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
});
diff --git a/test/api/v3/integration/user/auth/POST-login-local.test.js b/test/api/v3/integration/user/auth/POST-login-local.test.js
index 484ff16af5..c88176576d 100644
--- a/test/api/v3/integration/user/auth/POST-login-local.test.js
+++ b/test/api/v3/integration/user/auth/POST-login-local.test.js
@@ -1,3 +1,4 @@
+import nconf from 'nconf';
import {
generateUser,
requester,
@@ -9,20 +10,19 @@ import {
sha1Encrypt as sha1EncryptPassword,
} from '../../../../../../website/server/libs/password';
-import nconf from 'nconf';
describe('POST /user/auth/local/login', () => {
let api;
let user;
- let endpoint = '/user/auth/local/login';
- let password = 'password';
+ const endpoint = '/user/auth/local/login';
+ const password = 'password';
beforeEach(async () => {
api = requester();
user = await generateUser();
});
it('success with username', async () => {
- let response = await api.post(endpoint, {
+ const response = await api.post(endpoint, {
username: user.auth.local.username,
password,
});
@@ -30,7 +30,7 @@ describe('POST /user/auth/local/login', () => {
});
it('success with email', async () => {
- let response = await api.post(endpoint, {
+ const response = await api.post(endpoint, {
username: user.auth.local.email,
password,
});
@@ -81,9 +81,9 @@ describe('POST /user/auth/local/login', () => {
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -107,7 +107,7 @@ describe('POST /user/auth/local/login', () => {
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
- let isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
+ const isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
diff --git a/test/api/v3/integration/user/auth/POST-register_local.test.js b/test/api/v3/integration/user/auth/POST-register_local.test.js
index c6b3248258..896e20a0c0 100644
--- a/test/api/v3/integration/user/auth/POST-register_local.test.js
+++ b/test/api/v3/integration/user/auth/POST-register_local.test.js
@@ -1,3 +1,5 @@
+import { v4 as uuid } from 'uuid';
+import { each } from 'lodash';
import {
generateUser,
requester,
@@ -6,8 +8,6 @@ import {
getProperty,
} from '../../../../../helpers/api-integration/v3';
import { ApiUser } from '../../../../../helpers/api-integration/api-classes';
-import { v4 as uuid } from 'uuid';
-import { each } from 'lodash';
import { encrypt } from '../../../../../../website/server/libs/encryption';
function generateRandomUserName () {
@@ -23,11 +23,11 @@ describe('POST /user/auth/local/register', () => {
});
it('registers a new user', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -42,11 +42,11 @@ describe('POST /user/auth/local/register', () => {
});
it('registers a new user and sets verifiedUsername to true', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -60,11 +60,11 @@ describe('POST /user/auth/local/register', () => {
xit('remove spaces from username', async () => {
// TODO can probably delete this test now
- let username = ' usernamewithspaces ';
- let email = 'test@example.com';
- let password = 'password';
+ const username = ' usernamewithspaces ';
+ const email = 'test@example.com';
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -125,24 +125,24 @@ describe('POST /user/auth/local/register', () => {
context('provides default tags and tasks', async () => {
it('for a generic API consumer', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -162,26 +162,26 @@ describe('POST /user/auth/local/register', () => {
xit('for Web', async () => {
api = requester(
null,
- {'x-client': 'habitica-web'},
+ { 'x-client': 'habitica-web' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(3);
expect(habits[0].text).to.eql(t('defaultHabit1Text'));
@@ -216,26 +216,26 @@ describe('POST /user/auth/local/register', () => {
it('for Android', async () => {
api = requester(
null,
- {'x-client': 'habitica-android'},
+ { 'x-client': 'habitica-android' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -247,26 +247,26 @@ describe('POST /user/auth/local/register', () => {
it('for iOS', async () => {
api = requester(
null,
- {'x-client': 'habitica-ios'},
+ { 'x-client': 'habitica-ios' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -277,11 +277,11 @@ describe('POST /user/auth/local/register', () => {
});
xit('enrolls new users in an A/B test', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -292,11 +292,11 @@ describe('POST /user/auth/local/register', () => {
});
it('includes items awarded by default when creating a new user', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -309,10 +309,10 @@ describe('POST /user/auth/local/register', () => {
});
it('requires password and confirmPassword to match', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
- let confirmPassword = 'not password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
+ const confirmPassword = 'not password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -327,9 +327,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a username', async () => {
- let email = `${generateRandomUserName()}@example.com`;
- let password = 'password';
- let confirmPassword = 'password';
+ const email = `${generateRandomUserName()}@example.com`;
+ const password = 'password';
+ const confirmPassword = 'password';
await expect(api.post('/user/auth/local/register', {
email,
@@ -343,8 +343,8 @@ describe('POST /user/auth/local/register', () => {
});
it('requires an email', async () => {
- let username = generateRandomUserName();
- let password = 'password';
+ const username = generateRandomUserName();
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -358,9 +358,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a valid email', async () => {
- let username = generateRandomUserName();
- let email = 'notanemail@sdf';
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = 'notanemail@sdf';
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -375,11 +375,11 @@ describe('POST /user/auth/local/register', () => {
});
it('sanitizes email params to a lowercase string before creating the user', async () => {
- let username = generateRandomUserName();
- let email = 'ISANEmAiL@ExAmPle.coM';
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = 'ISANEmAiL@ExAmPle.coM';
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -390,9 +390,9 @@ describe('POST /user/auth/local/register', () => {
});
it('fails on a habitica.com email', async () => {
- let username = generateRandomUserName();
- let email = `${username}@habitica.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@habitica.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -407,9 +407,9 @@ describe('POST /user/auth/local/register', () => {
});
it('fails on a habitrpg.com email', async () => {
- let username = generateRandomUserName();
- let email = `${username}@habitrpg.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@habitrpg.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -424,9 +424,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a password', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let confirmPassword = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const confirmPassword = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -442,9 +442,9 @@ describe('POST /user/auth/local/register', () => {
context('attach to facebook user', () => {
let user;
- let email = 'some@email.net';
- let username = 'some-username';
- let password = 'some-password';
+ const email = 'some@email.net';
+ const username = 'some-username';
+ const password = 'some-password';
beforeEach(async () => {
user = await generateUser();
});
@@ -475,7 +475,8 @@ describe('POST /user/auth/local/register', () => {
});
context('login is already taken', () => {
- let username, email, api;
+ let username; let email; let
+ api;
beforeEach(async () => {
api = requester();
@@ -490,8 +491,8 @@ describe('POST /user/auth/local/register', () => {
});
it('rejects if username is already taken', async () => {
- let uniqueEmail = `${generateRandomUserName()}@exampe.com`;
- let password = 'password';
+ const uniqueEmail = `${generateRandomUserName()}@exampe.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -506,8 +507,8 @@ describe('POST /user/auth/local/register', () => {
});
it('rejects if email is already taken', async () => {
- let uniqueUsername = generateRandomUserName();
- let password = 'password';
+ const uniqueUsername = generateRandomUserName();
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username: uniqueUsername,
@@ -523,7 +524,8 @@ describe('POST /user/auth/local/register', () => {
});
context('req.query.groupInvite', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
api = requester();
@@ -533,7 +535,7 @@ describe('POST /user/auth/local/register', () => {
});
it('does not crash the signup process when it\'s invalid', async () => {
- let user = await api.post('/user/auth/local/register?groupInvite=aaaaInvalid', {
+ const user = await api.post('/user/auth/local/register?groupInvite=aaaaInvalid', {
username,
email,
password,
@@ -544,17 +546,17 @@ describe('POST /user/auth/local/register', () => {
});
it('supports invite using req.query.groupInvite', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(), // so we can let it expire
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -567,11 +569,11 @@ describe('POST /user/auth/local/register', () => {
});
it('awards achievement to inviter', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(),
@@ -589,17 +591,17 @@ describe('POST /user/auth/local/register', () => {
});
it('user not added to a party on expired invite', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now() - 6.912e8, // 8 days old
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -610,17 +612,17 @@ describe('POST /user/auth/local/register', () => {
});
it('adds a user to a guild on an invite of type other than party', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(),
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -636,7 +638,8 @@ describe('POST /user/auth/local/register', () => {
});
context('successful login via api', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
api = requester();
@@ -646,7 +649,7 @@ describe('POST /user/auth/local/register', () => {
});
it('sets all site tour values to -2 (already seen)', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -655,13 +658,13 @@ describe('POST /user/auth/local/register', () => {
expect(user.flags.tour).to.not.be.empty;
- each(user.flags.tour, (value) => {
+ each(user.flags.tour, value => {
expect(value).to.eql(-2);
});
});
it('populates user with default todos, not no other task types', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -675,7 +678,7 @@ describe('POST /user/auth/local/register', () => {
});
it('populates user with default tags', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -687,17 +690,18 @@ describe('POST /user/auth/local/register', () => {
});
context('successful login with habitica-web header', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
- api = requester({}, {'x-client': 'habitica-web'});
+ api = requester({}, { 'x-client': 'habitica-web' });
username = generateRandomUserName();
email = `${username}@example.com`;
password = 'password';
});
it('sets all common tutorial flags to true', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -706,13 +710,13 @@ describe('POST /user/auth/local/register', () => {
expect(user.flags.tour).to.not.be.empty;
- each(user.flags.tutorial.common, (value) => {
+ each(user.flags.tutorial.common, value => {
expect(value).to.eql(true);
});
});
it('populates user with default todos, habits, and rewards', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -726,7 +730,7 @@ describe('POST /user/auth/local/register', () => {
});
it('populates user with default tags', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -737,17 +741,17 @@ describe('POST /user/auth/local/register', () => {
});
it('adds the correct tags to the correct tasks', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let todos = await requests.get('/tasks/user?type=todos');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const todos = await requests.get('/tasks/user?type=todos');
expect(habits).to.have.a.lengthOf(0);
expect(todos).to.have.a.lengthOf(0);
diff --git a/test/api/v3/integration/user/auth/POST-user_auth_social.test.js b/test/api/v3/integration/user/auth/POST-user_auth_social.test.js
index 65aeb7985d..a934f3b8ed 100644
--- a/test/api/v3/integration/user/auth/POST-user_auth_social.test.js
+++ b/test/api/v3/integration/user/auth/POST-user_auth_social.test.js
@@ -1,18 +1,18 @@
+import passport from 'passport';
import {
generateUser,
requester,
translate as t,
getProperty,
} from '../../../../../helpers/api-integration/v3';
-import passport from 'passport';
describe('POST /user/auth/social', () => {
let api;
let user;
- let endpoint = '/user/auth/social';
- let randomAccessToken = '123456';
- let facebookId = 'facebookId';
- let googleId = 'googleId';
+ const endpoint = '/user/auth/social';
+ const randomAccessToken = '123456';
+ const facebookId = 'facebookId';
+ const googleId = 'googleId';
let network = 'NoNetwork';
beforeEach(async () => {
@@ -22,7 +22,7 @@ describe('POST /user/auth/social', () => {
it('fails if network is not supported', async () => {
await expect(api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
})).to.eventually.be.rejected.and.eql({
code: 400,
@@ -33,14 +33,14 @@ describe('POST /user/auth/social', () => {
describe('facebook', () => {
before(async () => {
- let expectedResult = {id: facebookId, displayName: 'a facebook user'};
+ const expectedResult = { id: facebookId, displayName: 'a facebook user' };
sandbox.stub(passport._strategies.facebook, 'userProfile').yields(null, expectedResult);
network = 'facebook';
});
it('registers a new user', async () => {
const response = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -54,13 +54,13 @@ describe('POST /user/auth/social', () => {
});
it('logs an existing user in', async () => {
- let registerResponse = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const registerResponse = await api.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
- let response = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const response = await api.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -70,8 +70,8 @@ describe('POST /user/auth/social', () => {
});
it('add social auth to an existing user', async () => {
- let response = await user.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const response = await user.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -82,7 +82,7 @@ describe('POST /user/auth/social', () => {
xit('enrolls a new user in an A/B test', async () => {
await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -92,14 +92,14 @@ describe('POST /user/auth/social', () => {
describe('google', () => {
before(async () => {
- let expectedResult = {id: googleId, displayName: 'a google user'};
+ const expectedResult = { id: googleId, displayName: 'a google user' };
sandbox.stub(passport._strategies.google, 'userProfile').yields(null, expectedResult);
network = 'google';
});
it('registers a new user', async () => {
- let response = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const response = await api.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -110,13 +110,13 @@ describe('POST /user/auth/social', () => {
});
it('logs an existing user in', async () => {
- let registerResponse = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const registerResponse = await api.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
- let response = await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const response = await api.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -126,8 +126,8 @@ describe('POST /user/auth/social', () => {
});
it('add social auth to an existing user', async () => {
- let response = await user.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ const response = await user.post(endpoint, {
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
@@ -138,7 +138,7 @@ describe('POST /user/auth/social', () => {
xit('enrolls a new user in an A/B test', async () => {
await api.post(endpoint, {
- authResponse: {access_token: randomAccessToken}, // eslint-disable-line camelcase
+ authResponse: { access_token: randomAccessToken }, // eslint-disable-line camelcase
network,
});
diff --git a/test/api/v3/integration/user/auth/POST-user_reset_password.test.js b/test/api/v3/integration/user/auth/POST-user_reset_password.test.js
index ab86bdcb90..8603fa7cb3 100644
--- a/test/api/v3/integration/user/auth/POST-user_reset_password.test.js
+++ b/test/api/v3/integration/user/auth/POST-user_reset_password.test.js
@@ -1,14 +1,14 @@
+import moment from 'moment';
import {
generateUser,
translate as t,
} from '../../../../../helpers/api-integration/v3';
-import moment from 'moment';
import {
decrypt,
} from '../../../../../../website/server/libs/encryption';
describe('POST /user/reset-password', async () => {
- let endpoint = '/user/reset-password';
+ const endpoint = '/user/reset-password';
let user;
beforeEach(async () => {
@@ -16,8 +16,8 @@ describe('POST /user/reset-password', async () => {
});
it('resets password', async () => {
- let previousPassword = user.auth.local.hashed_password;
- let response = await user.post(endpoint, {
+ const previousPassword = user.auth.local.hashed_password;
+ const response = await user.post(endpoint, {
email: user.auth.local.email,
});
expect(response).to.eql({ data: {}, message: t('passwordReset') });
@@ -26,7 +26,7 @@ describe('POST /user/reset-password', async () => {
});
it('same message on error as on success', async () => {
- let response = await user.post(endpoint, {
+ const response = await user.post(endpoint, {
email: 'nonExistent@email.com',
});
expect(response).to.eql({ data: {}, message: t('passwordReset') });
@@ -50,8 +50,8 @@ describe('POST /user/reset-password', async () => {
await user.sync();
expect(user.auth.local.passwordResetCode).to.be.a.string;
- let decryptedCode = JSON.parse(decrypt(user.auth.local.passwordResetCode));
+ const decryptedCode = JSON.parse(decrypt(user.auth.local.passwordResetCode));
expect(decryptedCode.userId).to.equal(user._id);
- expect(moment(decryptedCode.expiresAt).isAfter(moment().add({hours: 23}))).to.equal(true);
+ expect(moment(decryptedCode.expiresAt).isAfter(moment().add({ hours: 23 }))).to.equal(true);
});
});
diff --git a/test/api/v3/integration/user/auth/PUT-user_update_email.test.js b/test/api/v3/integration/user/auth/PUT-user_update_email.test.js
index d540dbd27b..d924a99ebf 100644
--- a/test/api/v3/integration/user/auth/PUT-user_update_email.test.js
+++ b/test/api/v3/integration/user/auth/PUT-user_update_email.test.js
@@ -1,3 +1,4 @@
+import nconf from 'nconf';
import {
generateUser,
translate as t,
@@ -8,13 +9,12 @@ import {
sha1Encrypt as sha1EncryptPassword,
} from '../../../../../../website/server/libs/password';
-import nconf from 'nconf';
const ENDPOINT = '/user/auth/update-email';
describe('PUT /user/auth/update-email', () => {
- let newEmail = 'SOmE-nEw-emAIl_2@example.net';
- let oldPassword = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
+ const newEmail = 'SOmE-nEw-emAIl_2@example.net';
+ const oldPassword = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
context('Local Authenticaion User', async () => {
let user;
@@ -53,8 +53,8 @@ describe('PUT /user/auth/update-email', () => {
});
it('changes email if new email and existing password are provided', async () => {
- let lowerCaseNewEmail = newEmail.toLowerCase();
- let response = await user.put(ENDPOINT, {
+ const lowerCaseNewEmail = newEmail.toLowerCase();
+ const response = await user.put(ENDPOINT, {
newEmail,
password: oldPassword,
});
@@ -76,10 +76,10 @@ describe('PUT /user/auth/update-email', () => {
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
- let myNewEmail = 'my-new-random-email@example.net';
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const myNewEmail = 'my-new-random-email@example.net';
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -93,7 +93,7 @@ describe('PUT /user/auth/update-email', () => {
expect(user.auth.local.hashed_password).to.equal(sha1HashedPassword);
// update email
- let response = await user.put(ENDPOINT, {
+ const response = await user.put(ENDPOINT, {
newEmail: myNewEmail,
password: textPassword,
});
@@ -106,7 +106,7 @@ describe('PUT /user/auth/update-email', () => {
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
- let isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
+ const isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
});
diff --git a/test/api/v3/integration/user/auth/PUT-user_update_password.test.js b/test/api/v3/integration/user/auth/PUT-user_update_password.test.js
index 81d03047b0..a46eb0f916 100644
--- a/test/api/v3/integration/user/auth/PUT-user_update_password.test.js
+++ b/test/api/v3/integration/user/auth/PUT-user_update_password.test.js
@@ -12,17 +12,17 @@ const ENDPOINT = '/user/auth/update-password';
describe('PUT /user/auth/update-password', async () => {
let user;
- let password = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
- let wrongPassword = 'wrong-password';
- let newPassword = 'new-password';
+ const password = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
+ const wrongPassword = 'wrong-password';
+ const newPassword = 'new-password';
beforeEach(async () => {
user = await generateUser();
});
it('successfully changes the password', async () => {
- let previousHashedPassword = user.auth.local.hashed_password;
- let response = await user.put(ENDPOINT, {
+ const previousHashedPassword = user.auth.local.hashed_password;
+ const response = await user.put(ENDPOINT, {
password,
newPassword,
confirmPassword: newPassword,
@@ -57,7 +57,7 @@ describe('PUT /user/auth/update-password', async () => {
});
it('returns an error when password is missing', async () => {
- let body = {
+ const body = {
newPassword,
confirmPassword: newPassword,
};
@@ -70,7 +70,7 @@ describe('PUT /user/auth/update-password', async () => {
});
it('returns an error when newPassword is missing', async () => {
- let body = {
+ const body = {
password,
confirmPassword: newPassword,
};
@@ -83,7 +83,7 @@ describe('PUT /user/auth/update-password', async () => {
});
it('returns an error when confirmPassword is missing', async () => {
- let body = {
+ const body = {
password,
newPassword,
};
@@ -96,9 +96,9 @@ describe('PUT /user/auth/update-password', async () => {
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -123,7 +123,7 @@ describe('PUT /user/auth/update-password', async () => {
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
- let isValidPassword = await bcryptCompare(newPassword, user.auth.local.hashed_password);
+ const isValidPassword = await bcryptCompare(newPassword, user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
});
diff --git a/test/api/v3/integration/user/auth/PUT-user_update_username.test.js b/test/api/v3/integration/user/auth/PUT-user_update_username.test.js
index 987f7bd556..7e2da12bc0 100644
--- a/test/api/v3/integration/user/auth/PUT-user_update_username.test.js
+++ b/test/api/v3/integration/user/auth/PUT-user_update_username.test.js
@@ -12,15 +12,15 @@ const ENDPOINT = '/user/auth/update-username';
describe('PUT /user/auth/update-username', async () => {
let user;
- let password = 'password'; // from habitrpg/test/helpers/api-integration/v4/object-generators.js
+ const password = 'password'; // from habitrpg/test/helpers/api-integration/v4/object-generators.js
beforeEach(async () => {
user = await generateUser();
});
it('successfully changes username with password', async () => {
- let newUsername = 'new-username';
- let response = await user.put(ENDPOINT, {
+ const newUsername = 'new-username';
+ const response = await user.put(ENDPOINT, {
username: newUsername,
password,
});
@@ -30,8 +30,8 @@ describe('PUT /user/auth/update-username', async () => {
});
it('successfully changes username without password', async () => {
- let newUsername = 'new-username-nopw';
- let response = await user.put(ENDPOINT, {
+ const newUsername = 'new-username-nopw';
+ const response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
@@ -40,8 +40,8 @@ describe('PUT /user/auth/update-username', async () => {
});
it('successfully changes username containing number and underscore', async () => {
- let newUsername = 'new_username9';
- let response = await user.put(ENDPOINT, {
+ const newUsername = 'new_username9';
+ const response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
@@ -52,8 +52,8 @@ describe('PUT /user/auth/update-username', async () => {
it('sets verifiedUsername when changing username', async () => {
user.flags.verifiedUsername = false;
await user.sync();
- let newUsername = 'new-username-verify';
- let response = await user.put(ENDPOINT, {
+ const newUsername = 'new-username-verify';
+ const response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
@@ -62,10 +62,10 @@ describe('PUT /user/auth/update-username', async () => {
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
- let myNewUsername = 'my-new-username';
- let textPassword = 'mySecretPassword';
- let salt = sha1MakeSalt();
- let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
+ const myNewUsername = 'my-new-username';
+ const textPassword = 'mySecretPassword';
+ const salt = sha1MakeSalt();
+ const sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
@@ -79,7 +79,7 @@ describe('PUT /user/auth/update-username', async () => {
expect(user.auth.local.hashed_password).to.equal(sha1HashedPassword);
// update email
- let response = await user.put(ENDPOINT, {
+ const response = await user.put(ENDPOINT, {
username: myNewUsername,
password: textPassword,
});
@@ -92,14 +92,14 @@ describe('PUT /user/auth/update-username', async () => {
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
- let isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
+ const isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
context('errors', async () => {
it('prevents username update if new username is already taken', async () => {
- let existingUsername = 'existing-username';
- await generateUser({'auth.local.username': existingUsername, 'auth.local.lowerCaseUsername': existingUsername });
+ const existingUsername = 'existing-username';
+ await generateUser({ 'auth.local.username': existingUsername, 'auth.local.lowerCaseUsername': existingUsername });
await expect(user.put(ENDPOINT, {
username: existingUsername,
@@ -112,7 +112,7 @@ describe('PUT /user/auth/update-username', async () => {
});
it('errors if password is wrong', async () => {
- let newUsername = 'new-username';
+ const newUsername = 'new-username';
await expect(user.put(ENDPOINT, {
username: newUsername,
password: 'wrong-password',
diff --git a/test/api/v3/integration/user/buy/POST-user_buy.test.js b/test/api/v3/integration/user/buy/POST-user_buy.test.js
index fddd08802a..4b39704500 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy.test.js
@@ -7,7 +7,7 @@ import {
import shared from '../../../../../../website/common/script';
import apiError from '../../../../../../website/server/libs/apiError';
-let content = shared.content;
+const { content } = shared;
describe('POST /user/buy/:key', () => {
let user;
@@ -25,7 +25,7 @@ describe('POST /user/buy/:key', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('itemNotFound', {key: 'notExisting'}),
+ message: apiError('itemNotFound', { key: 'notExisting' }),
});
});
@@ -35,13 +35,13 @@ describe('POST /user/buy/:key', () => {
'stats.hp': 40,
});
- let potion = content.potion;
- let res = await user.post('/user/buy/potion');
+ const { potion } = content;
+ const res = await user.post('/user/buy/potion');
await user.sync();
expect(user.stats.hp).to.equal(50);
expect(res.data).to.eql(user.stats);
- expect(res.message).to.equal(t('messageBought', {itemText: potion.text()}));
+ expect(res.message).to.equal(t('messageBought', { itemText: potion.text() }));
});
it('returns an error if user tries to buy a potion with full health', async () => {
@@ -59,7 +59,7 @@ describe('POST /user/buy/:key', () => {
});
it('buys a piece of gear', async () => {
- let key = 'armor_warrior_1';
+ const key = 'armor_warrior_1';
await user.post(`/user/buy/${key}`);
await user.sync();
@@ -68,11 +68,11 @@ describe('POST /user/buy/:key', () => {
});
it('buys a special spell', async () => {
- let key = 'spookySparkles';
- let item = content.special[key];
+ const key = 'spookySparkles';
+ const item = content.special[key];
- await user.update({'stats.gp': 250});
- let res = await user.post(`/user/buy/${key}`);
+ await user.update({ 'stats.gp': 250 });
+ const res = await user.post(`/user/buy/${key}`);
await user.sync();
expect(res.data).to.eql({
@@ -90,12 +90,12 @@ describe('POST /user/buy/:key', () => {
'stats.hp': 20,
});
- let potion = content.potion;
- let res = await user.post('/user/buy/potion', {quantity: 2});
+ const { potion } = content;
+ const res = await user.post('/user/buy/potion', { quantity: 2 });
await user.sync();
expect(user.stats.hp).to.equal(50);
expect(res.data).to.eql(user.stats);
- expect(res.message).to.equal(t('messageBought', {itemText: potion.text()}));
+ expect(res.message).to.equal(t('messageBought', { itemText: potion.text() }));
});
});
diff --git a/test/api/v3/integration/user/buy/POST-user_buy_gear.test.js b/test/api/v3/integration/user/buy/POST-user_buy_gear.test.js
index f60cbe793a..9e3120b8c7 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy_gear.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy_gear.test.js
@@ -21,12 +21,12 @@ describe('POST /user/buy-gear/:key', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('itemNotFound', {key: 'notExisting'}),
+ message: apiError('itemNotFound', { key: 'notExisting' }),
});
});
it('buys the first level weapon gear', async () => {
- let key = 'weapon_warrior_0';
+ const key = 'weapon_warrior_0';
await user.post(`/user/buy-gear/${key}`);
await user.sync();
@@ -35,7 +35,7 @@ describe('POST /user/buy-gear/:key', () => {
});
it('buys the first level armor gear', async () => {
- let key = 'armor_warrior_1';
+ const key = 'armor_warrior_1';
await user.post(`/user/buy-gear/${key}`);
await user.sync();
@@ -44,7 +44,7 @@ describe('POST /user/buy-gear/:key', () => {
});
it('tries to buy subsequent, level gear', async () => {
- let key = 'armor_warrior_2';
+ const key = 'armor_warrior_2';
return expect(user.post(`/user/buy-gear/${key}`))
.to.eventually.be.rejected.and.eql({
@@ -55,7 +55,7 @@ describe('POST /user/buy-gear/:key', () => {
});
it('returns an error if tries to buy gear from a different class', async () => {
- let key = 'armor_rogue_1';
+ const key = 'armor_rogue_1';
return expect(user.post(`/user/buy-gear/${key}`))
.to.eventually.be.rejected.and.eql({
diff --git a/test/api/v3/integration/user/buy/POST-user_buy_health_potion.test.js b/test/api/v3/integration/user/buy/POST-user_buy_health_potion.test.js
index 437d0e6a39..e79132fa5e 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy_health_potion.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy_health_potion.test.js
@@ -4,7 +4,7 @@ import {
} from '../../../../../helpers/api-integration/v3';
import shared from '../../../../../../website/common/script';
-let content = shared.content;
+const { content } = shared;
describe('POST /user/buy-health-potion', () => {
let user;
@@ -31,12 +31,12 @@ describe('POST /user/buy-health-potion', () => {
'stats.gp': 400,
});
- let potion = content.potion;
- let res = await user.post('/user/buy-health-potion');
+ const { potion } = content;
+ const res = await user.post('/user/buy-health-potion');
await user.sync();
expect(user.stats.hp).to.equal(50);
expect(res.data).to.eql(user.stats);
- expect(res.message).to.equal(t('messageBought', {itemText: potion.text()}));
+ expect(res.message).to.equal(t('messageBought', { itemText: potion.text() }));
});
});
diff --git a/test/api/v3/integration/user/buy/POST-user_buy_mystery_set.test.js b/test/api/v3/integration/user/buy/POST-user_buy_mystery_set.test.js
index bd49fae5a5..d4df2c93b3 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy_mystery_set.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy_mystery_set.test.js
@@ -24,9 +24,9 @@ describe('POST /user/buy-mystery-set/:key', () => {
});
it('buys a mystery set', async () => {
- let key = 301404;
+ const key = 301404;
- let res = await user.post(`/user/buy-mystery-set/${key}`);
+ const res = await user.post(`/user/buy-mystery-set/${key}`);
await user.sync();
expect(res.data).to.eql({
diff --git a/test/api/v3/integration/user/buy/POST-user_buy_quest.test.js b/test/api/v3/integration/user/buy/POST-user_buy_quest.test.js
index 8f1e6bf896..025f8dd3bd 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy_quest.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy_quest.test.js
@@ -5,7 +5,7 @@ import {
import shared from '../../../../../../website/common/script';
import apiError from '../../../../../../website/server/libs/apiError';
-let content = shared.content;
+const { content } = shared;
describe('POST /user/buy-quest/:key', () => {
let user;
@@ -21,16 +21,16 @@ describe('POST /user/buy-quest/:key', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('questNotFound', {key: 'notExisting'}),
+ message: apiError('questNotFound', { key: 'notExisting' }),
});
});
it('buys a quest', async () => {
- let key = 'dilatoryDistress1';
- let item = content.quests[key];
+ const key = 'dilatoryDistress1';
+ const item = content.quests[key];
- await user.update({'stats.gp': 250});
- let res = await user.post(`/user/buy-quest/${key}`);
+ await user.update({ 'stats.gp': 250 });
+ const res = await user.post(`/user/buy-quest/${key}`);
await user.sync();
expect(res.data).to.eql(user.items.quests);
@@ -40,13 +40,13 @@ describe('POST /user/buy-quest/:key', () => {
});
it('returns an error if quest prerequisites are not met', async () => {
- let key = 'dilatoryDistress2';
+ const key = 'dilatoryDistress2';
await expect(user.post(`/user/buy-quest/${key}`))
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('mustComplete', {quest: 'dilatoryDistress1'}),
+ message: t('mustComplete', { quest: 'dilatoryDistress1' }),
});
});
@@ -57,8 +57,8 @@ describe('POST /user/buy-quest/:key', () => {
const achievementName = `achievements.quests.${prerequisite}`;
- await user.update({[achievementName]: true, 'stats.gp': 9999});
- let res = await user.post(`/user/buy-quest/${key}`);
+ await user.update({ [achievementName]: true, 'stats.gp': 9999 });
+ const res = await user.post(`/user/buy-quest/${key}`);
await user.sync();
expect(res.data).to.eql(user.items.quests);
diff --git a/test/api/v3/integration/user/buy/POST-user_buy_special_spell.test.js b/test/api/v3/integration/user/buy/POST-user_buy_special_spell.test.js
index 20a73fb173..266661c421 100644
--- a/test/api/v3/integration/user/buy/POST-user_buy_special_spell.test.js
+++ b/test/api/v3/integration/user/buy/POST-user_buy_special_spell.test.js
@@ -5,7 +5,7 @@ import {
import shared from '../../../../../../website/common/script';
import apiError from '../../../../../../website/server/libs/apiError';
-let content = shared.content;
+const { content } = shared;
describe('POST /user/buy-special-spell/:key', () => {
let user;
@@ -21,16 +21,16 @@ describe('POST /user/buy-special-spell/:key', () => {
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('spellNotFound', {spellId: 'notExisting'}),
+ message: apiError('spellNotFound', { spellId: 'notExisting' }),
});
});
it('buys a special spell', async () => {
- let key = 'thankyou';
- let item = content.special[key];
+ const key = 'thankyou';
+ const item = content.special[key];
- await user.update({'stats.gp': 250});
- let res = await user.post(`/user/buy-special-spell/${key}`);
+ await user.update({ 'stats.gp': 250 });
+ const res = await user.post(`/user/buy-special-spell/${key}`);
await user.sync();
expect(res.data).to.eql({
@@ -43,7 +43,7 @@ describe('POST /user/buy-special-spell/:key', () => {
});
it('returns an error if user does not have enough gold', async () => {
- let key = 'thankyou';
+ const key = 'thankyou';
await user.update({
'stats.gp': 5,
diff --git a/test/api/v3/integration/user/stats/POST-user_allocate.test.js b/test/api/v3/integration/user/stats/POST-user_allocate.test.js
index 6ace8731db..c7c7f18204 100644
--- a/test/api/v3/integration/user/stats/POST-user_allocate.test.js
+++ b/test/api/v3/integration/user/stats/POST-user_allocate.test.js
@@ -22,7 +22,7 @@ describe('POST /user/allocate', () => {
.to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
- message: apiError('invalidAttribute', {attr: 'invalid'}),
+ message: apiError('invalidAttribute', { attr: 'invalid' }),
});
});
@@ -36,7 +36,7 @@ describe('POST /user/allocate', () => {
});
it('returns an error if the user hasn\'t selected class', async () => {
- await user.update({'flags.classSelected': false});
+ await user.update({ 'flags.classSelected': false });
await expect(user.post('/user/allocate'))
.to.eventually.be.rejected.and.eql({
code: 401,
@@ -46,8 +46,8 @@ describe('POST /user/allocate', () => {
});
it('allocates attribute points', async () => {
- await user.update({'stats.points': 1});
- let res = await user.post('/user/allocate?stat=con');
+ await user.update({ 'stats.points': 1 });
+ const res = await user.post('/user/allocate?stat=con');
await user.sync();
expect(user.stats.con).to.equal(1);
expect(user.stats.points).to.equal(0);
diff --git a/test/api/v3/integration/user/stats/POST-user_allocate_bulk.test.js b/test/api/v3/integration/user/stats/POST-user_allocate_bulk.test.js
index a665521d0d..fb60c80c49 100644
--- a/test/api/v3/integration/user/stats/POST-user_allocate_bulk.test.js
+++ b/test/api/v3/integration/user/stats/POST-user_allocate_bulk.test.js
@@ -32,7 +32,7 @@ describe('POST /user/allocate-bulk', () => {
});
it('returns an error if user has not selected class', async () => {
- await user.update({'flags.classSelected': false});
+ await user.update({ 'flags.classSelected': false });
await expect(user.post('/user/allocate-bulk', statsUpdate))
.to.eventually.be.rejected.and.eql({
code: 401,
@@ -42,7 +42,7 @@ describe('POST /user/allocate-bulk', () => {
});
it('allocates attribute points', async () => {
- await user.update({'stats.points': 3});
+ await user.update({ 'stats.points': 3 });
await user.post('/user/allocate-bulk', statsUpdate);
await user.sync();
diff --git a/test/api/v3/integration/user/stats/POST-user_allocate_now.test.js b/test/api/v3/integration/user/stats/POST-user_allocate_now.test.js
index b8f3ee5603..a0f1cf57ac 100644
--- a/test/api/v3/integration/user/stats/POST-user_allocate_now.test.js
+++ b/test/api/v3/integration/user/stats/POST-user_allocate_now.test.js
@@ -6,7 +6,7 @@ describe('POST /user/allocate-now', () => {
// More tests in common code unit tests
it('auto allocates all points', async () => {
- let user = await generateUser({
+ const user = await generateUser({
'stats.points': 5,
'stats.int': 3,
'stats.con': 9,
@@ -15,7 +15,7 @@ describe('POST /user/allocate-now', () => {
'preferences.allocationMode': 'flat',
});
- let res = await user.post('/user/allocate-now');
+ const res = await user.post('/user/allocate-now');
await user.sync();
expect(res).to.eql(user.stats);
diff --git a/test/api/v3/integration/webhook/DELETE-user_delete_webhook.test.js b/test/api/v3/integration/webhook/DELETE-user_delete_webhook.test.js
index 3126cd2b5a..b6a2d5a53d 100644
--- a/test/api/v3/integration/webhook/DELETE-user_delete_webhook.test.js
+++ b/test/api/v3/integration/webhook/DELETE-user_delete_webhook.test.js
@@ -3,8 +3,9 @@ import {
translate as t,
} from '../../../../helpers/api-integration/v3';
-let user, webhookToDelete;
-let endpoint = '/user/webhook';
+let user; let
+ webhookToDelete;
+const endpoint = '/user/webhook';
describe('DELETE /user/webhook', () => {
beforeEach(async () => {
@@ -32,11 +33,11 @@ describe('DELETE /user/webhook', () => {
});
it('returns the remaining webhooks', async () => {
- let [remainingWebhook] = await user.del(`${endpoint}/${webhookToDelete.id}`);
+ const [remainingWebhook] = await user.del(`${endpoint}/${webhookToDelete.id}`);
await user.sync();
- let webhook = user.webhooks[0];
+ const webhook = user.webhooks[0];
expect(remainingWebhook.id).to.eql(webhook.id);
expect(remainingWebhook.url).to.eql(webhook.url);
@@ -48,7 +49,7 @@ describe('DELETE /user/webhook', () => {
await expect(user.del(`${endpoint}/id-that-does-not-exist`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('noWebhookWithId', {id: 'id-that-does-not-exist'}),
+ message: t('noWebhookWithId', { id: 'id-that-does-not-exist' }),
});
});
});
diff --git a/test/api/v3/integration/webhook/GET-user-webhook.test.js b/test/api/v3/integration/webhook/GET-user-webhook.test.js
index 138aad902a..d1ea6939f4 100644
--- a/test/api/v3/integration/webhook/GET-user-webhook.test.js
+++ b/test/api/v3/integration/webhook/GET-user-webhook.test.js
@@ -22,7 +22,7 @@ describe('GET /user/webhook', () => {
});
it('returns users webhooks', async () => {
- let response = await user.get('/user/webhook');
+ const response = await user.get('/user/webhook');
expect(response).to.eql(user.webhooks.map(w => {
w.createdAt = w.createdAt.toISOString();
diff --git a/test/api/v3/integration/webhook/POST-user_add_webhook.test.js b/test/api/v3/integration/webhook/POST-user_add_webhook.test.js
index cbed7e56af..306ba771c0 100644
--- a/test/api/v3/integration/webhook/POST-user_add_webhook.test.js
+++ b/test/api/v3/integration/webhook/POST-user_add_webhook.test.js
@@ -1,12 +1,13 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID } from 'uuid';
import apiError from '../../../../../website/server/libs/apiError';
describe('POST /user/webhook', () => {
- let user, body;
+ let user; let
+ body;
beforeEach(async () => {
user = await generateUser();
@@ -41,7 +42,7 @@ describe('POST /user/webhook', () => {
it('defaults id to a uuid', async () => {
delete body.id;
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.id).to.exist;
});
@@ -59,7 +60,7 @@ describe('POST /user/webhook', () => {
it('defaults enabled to true', async () => {
delete body.enabled;
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.enabled).to.be.true;
});
@@ -67,7 +68,7 @@ describe('POST /user/webhook', () => {
it('can pass a label', async () => {
body.label = 'Custom Label';
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.label).to.equal('Custom Label');
});
@@ -75,7 +76,7 @@ describe('POST /user/webhook', () => {
it('defaults type to taskActivity', async () => {
delete body.type;
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.type).to.eql('taskActivity');
});
@@ -83,7 +84,7 @@ describe('POST /user/webhook', () => {
it('successfully adds the webhook', async () => {
expect(user.webhooks).to.eql([]);
- let response = await user.post('/user/webhook', body);
+ const response = await user.post('/user/webhook', body);
expect(response.id).to.eql(body.id);
expect(response.type).to.eql(body.type);
@@ -94,7 +95,7 @@ describe('POST /user/webhook', () => {
expect(user.webhooks).to.not.eql([]);
- let webhook = user.webhooks[0];
+ const webhook = user.webhooks[0];
expect(webhook.enabled).to.be.false;
expect(webhook.type).to.eql('taskActivity');
@@ -114,7 +115,7 @@ describe('POST /user/webhook', () => {
it('defaults taskActivity options', async () => {
body.type = 'taskActivity';
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
checklistScored: false,
@@ -135,7 +136,7 @@ describe('POST /user/webhook', () => {
scored: false,
};
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
checklistScored: true,
@@ -157,7 +158,7 @@ describe('POST /user/webhook', () => {
foo: 'bar',
};
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options.foo).to.not.exist;
expect(webhook.options).to.eql({
@@ -169,7 +170,7 @@ describe('POST /user/webhook', () => {
});
});
- ['created', 'updated', 'deleted', 'scored'].forEach((option) => {
+ ['created', 'updated', 'deleted', 'scored'].forEach(option => {
it(`requires taskActivity option ${option} to be a boolean`, async () => {
body.type = 'taskActivity';
body.options = {
@@ -190,7 +191,7 @@ describe('POST /user/webhook', () => {
groupId: generateUUID(),
};
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
groupId: body.options.groupId,
@@ -217,7 +218,7 @@ describe('POST /user/webhook', () => {
foo: 'bar',
};
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options.foo).to.not.exist;
expect(webhook.options).to.eql({
@@ -231,7 +232,7 @@ describe('POST /user/webhook', () => {
foo: 'bar',
};
- let webhook = await user.post('/user/webhook', body);
+ const webhook = await user.post('/user/webhook', body);
expect(webhook.options.foo).to.not.exist;
expect(webhook.options).to.eql({});
diff --git a/test/api/v3/integration/webhook/PUT-user_update_webhook.test.js b/test/api/v3/integration/webhook/PUT-user_update_webhook.test.js
index abebc4aff3..0f00e238e9 100644
--- a/test/api/v3/integration/webhook/PUT-user_update_webhook.test.js
+++ b/test/api/v3/integration/webhook/PUT-user_update_webhook.test.js
@@ -1,12 +1,13 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
-import { v4 as generateUUID} from 'uuid';
import apiError from '../../../../../website/server/libs/apiError';
describe('PUT /user/webhook/:id', () => {
- let user, webhookToUpdate;
+ let user; let
+ webhookToUpdate;
beforeEach(async () => {
user = await generateUser();
@@ -30,7 +31,7 @@ describe('PUT /user/webhook/:id', () => {
await expect(user.put('/user/webhook/id-that-does-not-exist')).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('noWebhookWithId', {id: 'id-that-does-not-exist'}),
+ message: t('noWebhookWithId', { id: 'id-that-does-not-exist' }),
});
});
@@ -43,16 +44,18 @@ describe('PUT /user/webhook/:id', () => {
});
it('updates a webhook', async () => {
- let url = 'http://a-new-url.com';
- let type = 'groupChatReceived';
- let label = 'New Label';
- let options = { groupId: generateUUID() };
+ const url = 'http://a-new-url.com';
+ const type = 'groupChatReceived';
+ const label = 'New Label';
+ const options = { groupId: generateUUID() };
- await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, type, options, label});
+ await user.put(`/user/webhook/${webhookToUpdate.id}`, {
+ url, type, options, label,
+ });
await user.sync();
- let webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
+ const webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
expect(webhook.url).to.equal(url);
expect(webhook.label).to.equal(label);
@@ -61,11 +64,11 @@ describe('PUT /user/webhook/:id', () => {
});
it('returns the updated webhook', async () => {
- let url = 'http://a-new-url.com';
- let type = 'groupChatReceived';
- let options = { groupId: generateUUID() };
+ const url = 'http://a-new-url.com';
+ const type = 'groupChatReceived';
+ const options = { groupId: generateUUID() };
- let response = await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, type, options});
+ const response = await user.put(`/user/webhook/${webhookToUpdate.id}`, { url, type, options });
expect(response.url).to.eql(url);
expect(response.type).to.eql(type);
@@ -73,27 +76,27 @@ describe('PUT /user/webhook/:id', () => {
});
it('cannot update the id', async () => {
- let id = generateUUID();
- let url = 'http://a-new-url.com';
+ const id = generateUUID();
+ const url = 'http://a-new-url.com';
- await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, id});
+ await user.put(`/user/webhook/${webhookToUpdate.id}`, { url, id });
await user.sync();
- let webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
+ const webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
expect(webhook.id).to.eql(webhookToUpdate.id);
expect(webhook.url).to.eql(url);
});
it('can update taskActivity options', async () => {
- let type = 'taskActivity';
- let options = {
+ const type = 'taskActivity';
+ const options = {
updated: false,
deleted: true,
};
- let webhook = await user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options});
+ const webhook = await user.put(`/user/webhook/${webhookToUpdate.id}`, { type, options });
expect(webhook.options).to.eql({
checklistScored: false, // starting value
@@ -105,14 +108,14 @@ describe('PUT /user/webhook/:id', () => {
});
it('errors if taskActivity option is not a boolean', async () => {
- let type = 'taskActivity';
- let options = {
+ const type = 'taskActivity';
+ const options = {
created: 'not a boolean',
updated: false,
deleted: true,
};
- await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options})).to.eventually.be.rejected.and.eql({
+ await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, { type, options })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('webhookBooleanOption', { option: 'created' }),
@@ -120,12 +123,12 @@ describe('PUT /user/webhook/:id', () => {
});
it('errors if groupChatRecieved groupId option is not a uuid', async () => {
- let type = 'groupChatReceived';
- let options = {
+ const type = 'groupChatReceived';
+ const options = {
groupId: 'not-a-uuid',
};
- await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options})).to.eventually.be.rejected.and.eql({
+ await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, { type, options })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: apiError('groupIdRequired'),
diff --git a/test/api/v3/integration/world-state/GET-world-state.test.js b/test/api/v3/integration/world-state/GET-world-state.test.js
index 4d8e7fbbbd..2b8f9cdfbd 100644
--- a/test/api/v3/integration/world-state/GET-world-state.test.js
+++ b/test/api/v3/integration/world-state/GET-world-state.test.js
@@ -16,7 +16,7 @@ describe('GET /world-state', () => {
});
it('returns Tavern quest data when world boss is active', async () => {
- await updateDocument('groups', {_id: TAVERN_ID}, {quest: {active: true, key: 'dysheartener', progress: {hp: 50000, rage: 9999}}});
+ await updateDocument('groups', { _id: TAVERN_ID }, { quest: { active: true, key: 'dysheartener', progress: { hp: 50000, rage: 9999 } } });
const res = await requester().get('/world-state');
expect(res).to.have.nested.property('worldBoss');
diff --git a/test/api/v4/coupon/POST-coupons_enter_code.test.js b/test/api/v4/coupon/POST-coupons_enter_code.test.js
index 01fe5fd0b6..71e4c05719 100644
--- a/test/api/v4/coupon/POST-coupons_enter_code.test.js
+++ b/test/api/v4/coupon/POST-coupons_enter_code.test.js
@@ -36,7 +36,7 @@ describe('POST /coupons/enter/:code', () => {
});
it('returns an error if coupon has been used', async () => {
- let [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
+ const [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
await user.post(`/coupons/enter/${coupon._id}`); // use coupon
await expect(user.post(`/coupons/enter/${coupon._id}`)).to.eventually.be.rejected.and.eql({
@@ -47,8 +47,8 @@ describe('POST /coupons/enter/:code', () => {
});
it('should apply the coupon to the user', async () => {
- let [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
- let userRes = await user.post(`/coupons/enter/${coupon._id}`);
+ const [coupon] = await sudoUser.post('/coupons/generate/wondercon?count=1');
+ const userRes = await user.post(`/coupons/enter/${coupon._id}`);
expect(userRes._id).to.equal(user._id);
expect(userRes.items.gear.owned.eyewear_special_wondercon_red).to.be.true;
expect(userRes.items.gear.owned.eyewear_special_wondercon_black).to.be.true;
@@ -57,6 +57,6 @@ describe('POST /coupons/enter/:code', () => {
expect(userRes.items.gear.owned.body_special_wondercon_red).to.be.true;
expect(userRes.items.gear.owned.body_special_wondercon_black).to.be.true;
expect(userRes.items.gear.owned.body_special_wondercon_gold).to.be.true;
- expect(userRes.extra).to.eql({signupEvent: 'wondercon'});
+ expect(userRes.extra).to.eql({ signupEvent: 'wondercon' });
});
});
diff --git a/test/api/v4/inbox/DELETE-inbox_clear.test.js b/test/api/v4/inbox/DELETE-inbox_clear.test.js
index ff0af5cceb..e351b764a7 100644
--- a/test/api/v4/inbox/DELETE-inbox_clear.test.js
+++ b/test/api/v4/inbox/DELETE-inbox_clear.test.js
@@ -27,4 +27,4 @@ describe('DELETE /inbox/clear', () => {
messages = await user.get('/inbox/messages');
expect(messages.length).to.equal(0);
});
-});
\ No newline at end of file
+});
diff --git a/test/api/v4/inbox/DELETE-inbox_messages_messageId.test.js b/test/api/v4/inbox/DELETE-inbox_messages_messageId.test.js
index 99365daf8f..1ea160a5da 100644
--- a/test/api/v4/inbox/DELETE-inbox_messages_messageId.test.js
+++ b/test/api/v4/inbox/DELETE-inbox_messages_messageId.test.js
@@ -1,8 +1,8 @@
+import { v4 as generateUUID } from 'uuid';
import {
generateUser,
translate as t,
} from '../../../helpers/api-integration/v4';
-import { v4 as generateUUID } from 'uuid';
describe('DELETE /inbox/messages/:messageId', () => {
let user;
diff --git a/test/api/v4/inbox/GET-inbox-conversations.test.js b/test/api/v4/inbox/GET-inbox-conversations.test.js
index ce94e919d5..d2317a3f65 100644
--- a/test/api/v4/inbox/GET-inbox-conversations.test.js
+++ b/test/api/v4/inbox/GET-inbox-conversations.test.js
@@ -8,7 +8,11 @@ describe('GET /inbox/conversations', () => {
let thirdUser;
beforeEach(async () => {
- [user, otherUser, thirdUser] = await Promise.all([generateUser(), generateUser(), generateUser()]);
+ [user, otherUser, thirdUser] = await Promise.all([
+ generateUser(),
+ generateUser(),
+ generateUser(),
+ ]);
await otherUser.post('/members/send-private-message', {
toUserId: user.id,
@@ -62,7 +66,7 @@ describe('GET /inbox/conversations', () => {
it('returns four messages when using page-query ', async () => {
const promises = [];
- for (let i = 0; i < 10; i++) {
+ for (let i = 0; i < 10; i += 1) {
promises.push(user.post('/members/send-private-message', {
toUserId: user.id,
message: 'fourth',
diff --git a/test/api/v4/members/POST-flag_private_message.test.js b/test/api/v4/members/POST-flag_private_message.test.js
index de9a75b9da..e4af36e302 100644
--- a/test/api/v4/members/POST-flag_private_message.test.js
+++ b/test/api/v4/members/POST-flag_private_message.test.js
@@ -5,61 +5,64 @@ import {
describe('POST /members/flag-private-message/:messageId', () => {
let userToSendMessage;
- let messageToSend = 'Test Private Message';
+ const messageToSend = 'Test Private Message';
beforeEach(async () => {
userToSendMessage = await generateUser();
});
it('Allows players to flag their own private message', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
await userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
toUserId: receiver._id,
});
- let senderMessages = await userToSendMessage.get('/inbox/paged-messages');
+ const senderMessages = await userToSendMessage.get('/inbox/paged-messages');
- let sendersMessageInSendersInbox = _.find(senderMessages, (message) => {
- return message.toUUID === receiver._id && message.text === messageToSend;
- });
+ const sendersMessageInSendersInbox = _.find(
+ senderMessages,
+ message => message.toUUID === receiver._id && message.text === messageToSend,
+ );
expect(sendersMessageInSendersInbox).to.exist;
await expect(userToSendMessage.post(`/members/flag-private-message/${sendersMessageInSendersInbox.id}`)).to.eventually.be.ok;
});
it('Flags a private message', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
await userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
toUserId: receiver._id,
});
- let receiversMessages = await receiver.get('/inbox/paged-messages');
+ const receiversMessages = await receiver.get('/inbox/paged-messages');
- let sendersMessageInReceiversInbox = _.find(receiversMessages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === messageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ receiversMessages,
+ message => message.uuid === userToSendMessage._id && message.text === messageToSend,
+ );
expect(sendersMessageInReceiversInbox).to.exist;
await expect(receiver.post(`/members/flag-private-message/${sendersMessageInReceiversInbox.id}`)).to.eventually.be.ok;
});
it('Returns an error when user tries to flag a private message that is already flagged', async () => {
- let receiver = await generateUser();
+ const receiver = await generateUser();
await userToSendMessage.post('/members/send-private-message', {
message: messageToSend,
toUserId: receiver._id,
});
- let receiversMessages = await receiver.get('/inbox/paged-messages');
+ const receiversMessages = await receiver.get('/inbox/paged-messages');
- let sendersMessageInReceiversInbox = _.find(receiversMessages, (message) => {
- return message.uuid === userToSendMessage._id && message.text === messageToSend;
- });
+ const sendersMessageInReceiversInbox = _.find(
+ receiversMessages,
+ message => message.uuid === userToSendMessage._id && message.text === messageToSend,
+ );
expect(sendersMessageInReceiversInbox).to.exist;
await expect(receiver.post(`/members/flag-private-message/${sendersMessageInReceiversInbox.id}`)).to.eventually.be.ok;
diff --git a/test/api/v4/user/GET-user.test.js b/test/api/v4/user/GET-user.test.js
index 4b1bad4054..fd05479560 100644
--- a/test/api/v4/user/GET-user.test.js
+++ b/test/api/v4/user/GET-user.test.js
@@ -11,7 +11,7 @@ describe('GET /user', () => {
});
it('returns the authenticated user with computed stats', async () => {
- let returnedUser = await user.get('/user');
+ const returnedUser = await user.get('/user');
expect(returnedUser._id).to.equal(user._id);
expect(returnedUser.stats.maxMP).to.exist;
@@ -20,7 +20,7 @@ describe('GET /user', () => {
});
it('does not return private paths (and apiToken)', async () => {
- let returnedUser = await user.get('/user');
+ const returnedUser = await user.get('/user');
expect(returnedUser.auth.local.hashed_password).to.not.exist;
expect(returnedUser.auth.local.passwordHashMethod).to.not.exist;
@@ -29,7 +29,7 @@ describe('GET /user', () => {
});
it('returns only user properties requested', async () => {
- let returnedUser = await user.get('/user?userFields=achievements,items.mounts');
+ const returnedUser = await user.get('/user?userFields=achievements,items.mounts');
expect(returnedUser._id).to.equal(user._id);
expect(returnedUser.achievements).to.exist;
@@ -50,7 +50,7 @@ describe('GET /user', () => {
toUserId: user.id,
message: 'second',
});
- let returnedUser = await user.get('/user');
+ const returnedUser = await user.get('/user');
expect(returnedUser._id).to.equal(user._id);
expect(returnedUser.inbox.messages).to.be.undefined;
diff --git a/test/api/v4/user/POST-user_class_cast_spellId.test.js b/test/api/v4/user/POST-user_class_cast_spellId.test.js
index 90c2eae1db..6e46b92931 100644
--- a/test/api/v4/user/POST-user_class_cast_spellId.test.js
+++ b/test/api/v4/user/POST-user_class_cast_spellId.test.js
@@ -1,3 +1,6 @@
+
+import { v4 as generateUUID } from 'uuid';
+import { find } from 'lodash';
import {
generateUser,
translate as t,
@@ -6,9 +9,6 @@ import {
generateChallenge,
sleep,
} from '../../../helpers/api-integration/v4';
-
-import { v4 as generateUUID } from 'uuid';
-import { find } from 'lodash';
import apiError from '../../../../website/server/libs/apiError';
describe('POST /user/class/cast/:spellId', () => {
@@ -19,28 +19,28 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if spell does not exist', async () => {
- await user.update({'stats.class': 'rogue'});
- let spellId = 'invalidSpell';
+ await user.update({ 'stats.class': 'rogue' });
+ const spellId = 'invalidSpell';
await expect(user.post(`/user/class/cast/${spellId}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('spellNotFound', {spellId}),
+ message: apiError('spellNotFound', { spellId }),
});
});
it('returns an error if spell does not exist in user\'s class', async () => {
- let spellId = 'pickPocket';
+ const spellId = 'pickPocket';
await expect(user.post(`/user/class/cast/${spellId}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: apiError('spellNotFound', {spellId}),
+ message: apiError('spellNotFound', { spellId }),
});
});
it('returns an error if spell.mana > user.mana', async () => {
- await user.update({'stats.class': 'rogue'});
+ await user.update({ 'stats.class': 'rogue' });
await expect(user.post('/user/class/cast/backStab'))
.to.eventually.be.rejected.and.eql({
code: 401,
@@ -59,12 +59,12 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if spell.lvl > user.level', async () => {
- await user.update({'stats.mp': 200, 'stats.class': 'wizard'});
+ await user.update({ 'stats.mp': 200, 'stats.class': 'wizard' });
await expect(user.post('/user/class/cast/earth'))
.to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('spellLevelTooHigh', {level: 13}),
+ message: t('spellLevelTooHigh', { level: 13 }),
});
});
@@ -87,7 +87,7 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targetId is required but missing', async () => {
- await user.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await expect(user.post('/user/class/cast/pickPocket'))
.to.eventually.be.rejected.and.eql({
code: 400,
@@ -97,7 +97,7 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targeted task doesn\'t exist', async () => {
- await user.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await expect(user.post(`/user/class/cast/pickPocket?targetId=${generateUUID()}`))
.to.eventually.be.rejected.and.eql({
code: 404,
@@ -107,13 +107,13 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if a challenge task was targeted', async () => {
- let {group, groupLeader} = await createAndPopulateGroup();
- let challenge = await generateChallenge(groupLeader, group);
+ const { group, groupLeader } = await createAndPopulateGroup();
+ const challenge = await generateChallenge(groupLeader, group);
await groupLeader.post(`/challenges/${challenge._id}/join`);
await groupLeader.post(`/tasks/challenge/${challenge._id}`, [
- {type: 'habit', text: 'task text'},
+ { type: 'habit', text: 'task text' },
]);
- await groupLeader.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await groupLeader.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await sleep(0.5);
await groupLeader.sync();
await expect(groupLeader.post(`/user/class/cast/pickPocket?targetId=${groupLeader.tasksOrder.habits[0]}`))
@@ -125,19 +125,17 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if a group task was targeted', async () => {
- let {group, groupLeader} = await createAndPopulateGroup();
+ const { group, groupLeader } = await createAndPopulateGroup();
- let groupTask = await groupLeader.post(`/tasks/group/${group._id}`, {
+ const groupTask = await groupLeader.post(`/tasks/group/${group._id}`, {
text: 'todo group',
type: 'todo',
});
await groupLeader.post(`/tasks/${groupTask._id}/assign/${groupLeader._id}`);
- let memberTasks = await groupLeader.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === group._id;
- });
+ const memberTasks = await groupLeader.get('/tasks/user');
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === group._id);
- await groupLeader.update({'stats.class': 'rogue', 'stats.lvl': 11});
+ await groupLeader.update({ 'stats.class': 'rogue', 'stats.lvl': 11 });
await sleep(0.5);
await groupLeader.sync();
@@ -150,23 +148,23 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('returns an error if targeted party member doesn\'t exist', async () => {
- let {groupLeader} = await createAndPopulateGroup({
+ const { groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'items.special.snowball': 3});
+ await groupLeader.update({ 'items.special.snowball': 3 });
- let target = generateUUID();
+ const target = generateUUID();
await expect(groupLeader.post(`/user/class/cast/snowball?targetId=${target}`))
.to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
- message: t('userWithIDNotFound', {userId: target}),
+ message: t('userWithIDNotFound', { userId: target }),
});
});
it('returns an error if party does not exists', async () => {
- await user.update({'items.special.snowball': 3});
+ await user.update({ 'items.special.snowball': 3 });
await expect(user.post(`/user/class/cast/snowball?targetId=${generateUUID()}`))
.to.eventually.be.rejected.and.eql({
@@ -177,11 +175,11 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('send message in party chat if party && !spell.silent', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13});
+ await groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13 });
await groupLeader.post('/user/class/cast/earth');
await sleep(1);
@@ -192,17 +190,17 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('Ethereal Surge does not recover mp of other mages', async () => {
- let group = await createAndPopulateGroup({
+ const group = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
members: 4,
});
let promises = [];
- promises.push(group.groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 20}));
- promises.push(group.members[0].update({'stats.mp': 0, 'stats.class': 'warrior', 'stats.lvl': 20}));
- promises.push(group.members[1].update({'stats.mp': 0, 'stats.class': 'wizard', 'stats.lvl': 20}));
- promises.push(group.members[2].update({'stats.mp': 0, 'stats.class': 'rogue', 'stats.lvl': 20}));
- promises.push(group.members[3].update({'stats.mp': 0, 'stats.class': 'healer', 'stats.lvl': 20}));
+ promises.push(group.groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 20 }));
+ promises.push(group.members[0].update({ 'stats.mp': 0, 'stats.class': 'warrior', 'stats.lvl': 20 }));
+ promises.push(group.members[1].update({ 'stats.mp': 0, 'stats.class': 'wizard', 'stats.lvl': 20 }));
+ promises.push(group.members[2].update({ 'stats.mp': 0, 'stats.class': 'rogue', 'stats.lvl': 20 }));
+ promises.push(group.members[3].update({ 'stats.mp': 0, 'stats.class': 'healer', 'stats.lvl': 20 }));
await Promise.all(promises);
await group.groupLeader.post('/user/class/cast/mpheal');
@@ -221,13 +219,13 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('cast bulk', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ let { group, groupLeader } = await createAndPopulateGroup({ // eslint-disable-line prefer-const
groupDetails: { type: 'party', privacy: 'private' },
members: 1,
});
- await groupLeader.update({'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13});
- await groupLeader.post('/user/class/cast/earth', {quantity: 2});
+ await groupLeader.update({ 'stats.mp': 200, 'stats.class': 'wizard', 'stats.lvl': 13 });
+ await groupLeader.post('/user/class/cast/earth', { quantity: 2 });
await sleep(1);
group = await groupLeader.get(`/groups/${group._id}`);
@@ -237,33 +235,32 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('searing brightness does not affect challenge or group tasks', async () => {
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test challenge habit',
type: 'habit',
});
- let groupTask = await user.post(`/tasks/group/${guild._id}`, {
+ const groupTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'todo group',
type: 'todo',
});
- await user.update({'stats.class': 'healer', 'stats.mp': 200, 'stats.lvl': 15});
+ await user.update({ 'stats.class': 'healer', 'stats.mp': 200, 'stats.lvl': 15 });
await user.post(`/tasks/${groupTask._id}/assign/${user._id}`);
await user.post('/user/class/cast/brightness');
await user.sync();
- let memberTasks = await user.get('/tasks/user');
+ const memberTasks = await user.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === guild._id;
- });
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === guild._id);
- let userChallengeTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.challenge.id === challenge._id;
- });
+ const userChallengeTask = find(
+ memberTasks,
+ memberTask => memberTask.challenge.id === challenge._id,
+ );
expect(userChallengeTask).to.exist;
expect(syncedGroupTask).to.exist;
@@ -272,12 +269,12 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('increases both user\'s achievement values', async () => {
- let party = await createAndPopulateGroup({
+ const party = await createAndPopulateGroup({
members: 1,
});
- let leader = party.groupLeader;
- let recipient = party.members[0];
- await leader.update({'stats.gp': 10});
+ const leader = party.groupLeader;
+ const recipient = party.members[0];
+ await leader.update({ 'stats.gp': 10 });
await leader.post(`/user/class/cast/birthday?targetId=${recipient._id}`);
await leader.sync();
await recipient.sync();
@@ -286,29 +283,29 @@ describe('POST /user/class/cast/:spellId', () => {
});
it('only increases user\'s achievement one if target == caster', async () => {
- await user.update({'stats.gp': 10});
+ await user.update({ 'stats.gp': 10 });
await user.post(`/user/class/cast/birthday?targetId=${user._id}`);
await user.sync();
expect(user.achievements.birthday).to.equal(1);
});
it('passes correct target to spell when targetType === \'task\'', async () => {
- await user.update({'stats.class': 'wizard', 'stats.lvl': 11});
+ await user.update({ 'stats.class': 'wizard', 'stats.lvl': 11 });
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
- let result = await user.post(`/user/class/cast/fireball?targetId=${task._id}`);
+ const result = await user.post(`/user/class/cast/fireball?targetId=${task._id}`);
expect(result.task._id).to.equal(task._id);
});
it('passes correct target to spell when targetType === \'self\'', async () => {
- await user.update({'stats.class': 'wizard', 'stats.lvl': 14, 'stats.mp': 50});
+ await user.update({ 'stats.class': 'wizard', 'stats.lvl': 14, 'stats.mp': 50 });
- let result = await user.post('/user/class/cast/frost');
+ const result = await user.post('/user/class/cast/frost');
expect(result.user.stats.mp).to.equal(10);
});
diff --git a/test/api/v4/user/POST-user_rebirth.test.js b/test/api/v4/user/POST-user_rebirth.test.js
index 94b91ddf6b..b4781c6bc6 100644
--- a/test/api/v4/user/POST-user_rebirth.test.js
+++ b/test/api/v4/user/POST-user_rebirth.test.js
@@ -28,7 +28,7 @@ describe('POST /user/rebirth', () => {
balance: 1.5,
});
- let daily = await generateDaily({
+ const daily = await generateDaily({
text: 'test habit',
type: 'daily',
value: 1,
@@ -36,21 +36,21 @@ describe('POST /user/rebirth', () => {
userId: user._id,
});
- let reward = await generateReward({
+ const reward = await generateReward({
text: 'test reward',
type: 'reward',
value: 1,
userId: user._id,
});
- let response = await user.post('/user/rebirth');
+ const response = await user.post('/user/rebirth');
await user.sync();
expect(user.notifications.length).to.equal(1);
expect(user.notifications[0].type).to.equal('REBIRTH_ACHIEVEMENT');
- let updatedDaily = await user.get(`/tasks/${daily._id}`);
- let updatedReward = await user.get(`/tasks/${reward._id}`);
+ const updatedDaily = await user.get(`/tasks/${daily._id}`);
+ const updatedReward = await user.get(`/tasks/${reward._id}`);
expect(response.message).to.equal(t('rebirthComplete'));
expect(updatedDaily.streak).to.equal(0);
diff --git a/test/api/v4/user/POST-user_reroll.test.js b/test/api/v4/user/POST-user_reroll.test.js
index 10ac0c2843..18d1aaad79 100644
--- a/test/api/v4/user/POST-user_reroll.test.js
+++ b/test/api/v4/user/POST-user_reroll.test.js
@@ -28,24 +28,24 @@ describe('POST /user/reroll', () => {
balance: 2,
});
- let daily = await generateDaily({
+ const daily = await generateDaily({
text: 'test habit',
type: 'daily',
userId: user._id,
});
- let reward = await generateReward({
+ const reward = await generateReward({
text: 'test reward',
type: 'reward',
value: 1,
userId: user._id,
});
- let response = await user.post('/user/reroll');
+ const response = await user.post('/user/reroll');
await user.sync();
- let updatedDaily = await user.get(`/tasks/${daily._id}`);
- let updatedReward = await user.get(`/tasks/${reward._id}`);
+ const updatedDaily = await user.get(`/tasks/${daily._id}`);
+ const updatedReward = await user.get(`/tasks/${reward._id}`);
expect(response.message).to.equal(t('fortifyComplete'));
expect(updatedDaily.value).to.equal(0);
diff --git a/test/api/v4/user/POST-user_reset.test.js b/test/api/v4/user/POST-user_reset.test.js
index c8cf7b9f6b..a664ba31ea 100644
--- a/test/api/v4/user/POST-user_reset.test.js
+++ b/test/api/v4/user/POST-user_reset.test.js
@@ -1,10 +1,10 @@
+import { find } from 'lodash';
import {
generateUser,
generateGroup,
generateChallenge,
translate as t,
} from '../../../helpers/api-integration/v4';
-import { find } from 'lodash';
describe('POST /user/reset', () => {
let user;
@@ -16,7 +16,7 @@ describe('POST /user/reset', () => {
// More tests in common code unit tests
it('resets user\'s habits', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
@@ -34,7 +34,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s dailys', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test daily',
type: 'daily',
});
@@ -52,7 +52,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s todos', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test todo',
type: 'todo',
});
@@ -70,7 +70,7 @@ describe('POST /user/reset', () => {
});
it('resets user\'s rewards', async () => {
- let task = await user.post('/tasks/user', {
+ const task = await user.post('/tasks/user', {
text: 'test reward',
type: 'reward',
});
@@ -88,15 +88,15 @@ describe('POST /user/reset', () => {
});
it('does not delete challenge or group tasks', async () => {
- let guild = await generateGroup(user);
- let challenge = await generateChallenge(user, guild);
+ const guild = await generateGroup(user);
+ const challenge = await generateChallenge(user, guild);
await user.post(`/challenges/${challenge._id}/join`);
await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test challenge habit',
type: 'habit',
});
- let groupTask = await user.post(`/tasks/group/${guild._id}`, {
+ const groupTask = await user.post(`/tasks/group/${guild._id}`, {
text: 'todo group',
type: 'todo',
});
@@ -105,15 +105,14 @@ describe('POST /user/reset', () => {
await user.post('/user/reset');
await user.sync();
- let memberTasks = await user.get('/tasks/user');
+ const memberTasks = await user.get('/tasks/user');
- let syncedGroupTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.group.id === guild._id;
- });
+ const syncedGroupTask = find(memberTasks, memberTask => memberTask.group.id === guild._id);
- let userChallengeTask = find(memberTasks, function findAssignedTask (memberTask) {
- return memberTask.challenge.id === challenge._id;
- });
+ const userChallengeTask = find(
+ memberTasks,
+ memberTask => memberTask.challenge.id === challenge._id,
+ );
expect(userChallengeTask).to.exist;
expect(syncedGroupTask).to.exist;
diff --git a/test/api/v4/user/PUT-user.test.js b/test/api/v4/user/PUT-user.test.js
index 9ea1c145dd..0830b6f139 100644
--- a/test/api/v4/user/PUT-user.test.js
+++ b/test/api/v4/user/PUT-user.test.js
@@ -1,9 +1,9 @@
+import { each, get } from 'lodash';
import {
generateUser,
translate as t,
} from '../../../helpers/api-integration/v4';
-import { each, get } from 'lodash';
describe('PUT /user', () => {
let user;
@@ -40,7 +40,7 @@ describe('PUT /user', () => {
});
it('update tags', async () => {
- let userTags = user.tags;
+ const userTags = user.tags;
await user.put('/user', {
tags: [...user.tags, {
@@ -82,20 +82,20 @@ describe('PUT /user', () => {
});
context('Top Level Protected Operations', () => {
- let protectedOperations = {
- 'gem balance': {balance: 100},
- auth: {'auth.blocked': true, 'auth.timestamps.created': new Date()},
- contributor: {'contributor.level': 9, 'contributor.admin': true, 'contributor.text': 'some text'},
- backer: {'backer.tier': 10, 'backer.npc': 'Bilbo'},
- subscriptions: {'purchased.plan.extraMonths': 500, 'purchased.plan.consecutive.trinkets': 1000},
- 'customization gem purchases': {'purchased.background.tavern': true, 'purchased.skin.bear': true},
- notifications: [{type: 123}],
- webhooks: {webhooks: [{url: 'https://foobar.com'}]},
+ const protectedOperations = {
+ 'gem balance': { balance: 100 },
+ auth: { 'auth.blocked': true, 'auth.timestamps.created': new Date() },
+ contributor: { 'contributor.level': 9, 'contributor.admin': true, 'contributor.text': 'some text' },
+ backer: { 'backer.tier': 10, 'backer.npc': 'Bilbo' },
+ subscriptions: { 'purchased.plan.extraMonths': 500, 'purchased.plan.consecutive.trinkets': 1000 },
+ 'customization gem purchases': { 'purchased.background.tavern': true, 'purchased.skin.bear': true },
+ notifications: [{ type: 123 }],
+ webhooks: { webhooks: [{ url: 'https://foobar.com' }] },
};
each(protectedOperations, (data, testName) => {
it(`does not allow updating ${testName}`, async () => {
- let errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
+ const errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
await expect(user.put('/user', data)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -107,17 +107,17 @@ describe('PUT /user', () => {
});
context('Sub-Level Protected Operations', () => {
- let protectedOperations = {
- 'class stat': {'stats.class': 'wizard'},
- 'flags unless whitelisted': {'flags.dropsEnabled': true},
- webhooks: {'preferences.webhooks': [1, 2, 3]},
- sleep: {'preferences.sleep': true},
- 'disable classes': {'preferences.disableClasses': true},
+ const protectedOperations = {
+ 'class stat': { 'stats.class': 'wizard' },
+ 'flags unless whitelisted': { 'flags.dropsEnabled': true },
+ webhooks: { 'preferences.webhooks': [1, 2, 3] },
+ sleep: { 'preferences.sleep': true },
+ 'disable classes': { 'preferences.disableClasses': true },
};
each(protectedOperations, (data, testName) => {
it(`does not allow updating ${testName}`, async () => {
- let errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
+ const errorText = t('messageUserOperationProtected', { operation: Object.keys(data)[0] });
await expect(user.put('/user', data)).to.eventually.be.rejected.and.eql({
code: 401,
@@ -129,7 +129,7 @@ describe('PUT /user', () => {
});
context('Default Appearance Preferences', () => {
- let testCases = {
+ const testCases = {
shirt: 'yellow',
skin: 'ddc994',
'hair.color': 'blond',
@@ -144,14 +144,14 @@ describe('PUT /user', () => {
update[`preferences.${type}`] = item;
it(`updates user with ${type} that is a default`, async () => {
- let dbUpdate = {};
+ const dbUpdate = {};
dbUpdate[`purchased.${type}.${item}`] = true;
await user.update(dbUpdate);
// Sanity checks to make sure user is not already equipped with item
expect(get(user.preferences, type)).to.not.eql(item);
- let updatedUser = await user.put('/user', update);
+ const updatedUser = await user.put('/user', update);
expect(get(updatedUser.preferences, type)).to.eql(item);
});
@@ -173,7 +173,7 @@ describe('PUT /user', () => {
'preferences.hair.beard': 3,
});
- let updatedUser = await user.put('/user', {
+ const updatedUser = await user.put('/user', {
'preferences.hair.beard': 0,
});
@@ -186,7 +186,7 @@ describe('PUT /user', () => {
'preferences.hair.mustache': 2,
});
- let updatedUser = await user.put('/user', {
+ const updatedUser = await user.put('/user', {
'preferences.hair.mustache': 0,
});
@@ -195,7 +195,7 @@ describe('PUT /user', () => {
});
context('Purchasable Appearance Preferences', () => {
- let testCases = {
+ const testCases = {
background: 'volcano',
shirt: 'convict',
skin: 'cactus',
@@ -213,19 +213,19 @@ describe('PUT /user', () => {
await expect(user.put('/user', update)).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
- message: t('mustPurchaseToSet', {val: item, key: `preferences.${type}`}),
+ message: t('mustPurchaseToSet', { val: item, key: `preferences.${type}` }),
});
});
it(`updates user with ${type} user does own`, async () => {
- let dbUpdate = {};
+ const dbUpdate = {};
dbUpdate[`purchased.${type}.${item}`] = true;
await user.update(dbUpdate);
// Sanity check to make sure user is not already equipped with item
expect(get(user.preferences, type)).to.not.eql(item);
- let updatedUser = await user.put('/user', update);
+ const updatedUser = await user.put('/user', update);
expect(get(updatedUser.preferences, type)).to.eql(item);
});
diff --git a/test/api/v4/user/auth/POST-register_local.test.js b/test/api/v4/user/auth/POST-register_local.test.js
index 62df06f307..5d5b3abdbb 100644
--- a/test/api/v4/user/auth/POST-register_local.test.js
+++ b/test/api/v4/user/auth/POST-register_local.test.js
@@ -1,3 +1,5 @@
+import { v4 as uuid } from 'uuid';
+import { each } from 'lodash';
import {
generateUser,
requester,
@@ -6,8 +8,6 @@ import {
getProperty,
} from '../../../../helpers/api-integration/v4';
import { ApiUser } from '../../../../helpers/api-integration/api-classes';
-import { v4 as uuid } from 'uuid';
-import { each } from 'lodash';
import { encrypt } from '../../../../../website/server/libs/encryption';
function generateRandomUserName () {
@@ -23,11 +23,11 @@ describe('POST /user/auth/local/register', () => {
});
it('registers a new user', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -43,11 +43,11 @@ describe('POST /user/auth/local/register', () => {
xit('remove spaces from username', async () => {
// TODO can probably delete this test now
- let username = ' usernamewithspaces ';
- let email = 'test@example.com';
- let password = 'password';
+ const username = ' usernamewithspaces ';
+ const email = 'test@example.com';
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -108,24 +108,24 @@ describe('POST /user/auth/local/register', () => {
context('provides default tags and tasks', async () => {
it('for a generic API consumer', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -145,26 +145,26 @@ describe('POST /user/auth/local/register', () => {
xit('for Web', async () => {
api = requester(
null,
- {'x-client': 'habitica-web'},
+ { 'x-client': 'habitica-web' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(3);
expect(habits[0].text).to.eql(t('defaultHabit1Text'));
@@ -199,26 +199,26 @@ describe('POST /user/auth/local/register', () => {
it('for Android', async () => {
api = requester(
null,
- {'x-client': 'habitica-android'},
+ { 'x-client': 'habitica-android' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -230,26 +230,26 @@ describe('POST /user/auth/local/register', () => {
it('for iOS', async () => {
api = requester(
null,
- {'x-client': 'habitica-ios'},
+ { 'x-client': 'habitica-ios' },
);
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let dailys = await requests.get('/tasks/user?type=dailys');
- let todos = await requests.get('/tasks/user?type=todos');
- let rewards = await requests.get('/tasks/user?type=rewards');
- let tags = await requests.get('/tags');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const dailys = await requests.get('/tasks/user?type=dailys');
+ const todos = await requests.get('/tasks/user?type=todos');
+ const rewards = await requests.get('/tasks/user?type=rewards');
+ const tags = await requests.get('/tags');
expect(habits).to.have.a.lengthOf(0);
expect(dailys).to.have.a.lengthOf(0);
@@ -260,11 +260,11 @@ describe('POST /user/auth/local/register', () => {
});
it('enrolls new users in an A/B test', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -275,11 +275,11 @@ describe('POST /user/auth/local/register', () => {
});
it('includes items awarded by default when creating a new user', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -292,10 +292,10 @@ describe('POST /user/auth/local/register', () => {
});
it('requires password and confirmPassword to match', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let password = 'password';
- let confirmPassword = 'not password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const password = 'password';
+ const confirmPassword = 'not password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -310,9 +310,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a username', async () => {
- let email = `${generateRandomUserName()}@example.com`;
- let password = 'password';
- let confirmPassword = 'password';
+ const email = `${generateRandomUserName()}@example.com`;
+ const password = 'password';
+ const confirmPassword = 'password';
await expect(api.post('/user/auth/local/register', {
email,
@@ -326,8 +326,8 @@ describe('POST /user/auth/local/register', () => {
});
it('requires an email', async () => {
- let username = generateRandomUserName();
- let password = 'password';
+ const username = generateRandomUserName();
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -341,9 +341,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a valid email', async () => {
- let username = generateRandomUserName();
- let email = 'notanemail@sdf';
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = 'notanemail@sdf';
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -358,11 +358,11 @@ describe('POST /user/auth/local/register', () => {
});
it('sanitizes email params to a lowercase string before creating the user', async () => {
- let username = generateRandomUserName();
- let email = 'ISANEmAiL@ExAmPle.coM';
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = 'ISANEmAiL@ExAmPle.coM';
+ const password = 'password';
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -373,9 +373,9 @@ describe('POST /user/auth/local/register', () => {
});
it('fails on a habitica.com email', async () => {
- let username = generateRandomUserName();
- let email = `${username}@habitica.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@habitica.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -390,9 +390,9 @@ describe('POST /user/auth/local/register', () => {
});
it('fails on a habitrpg.com email', async () => {
- let username = generateRandomUserName();
- let email = `${username}@habitrpg.com`;
- let password = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@habitrpg.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -407,9 +407,9 @@ describe('POST /user/auth/local/register', () => {
});
it('requires a password', async () => {
- let username = generateRandomUserName();
- let email = `${username}@example.com`;
- let confirmPassword = 'password';
+ const username = generateRandomUserName();
+ const email = `${username}@example.com`;
+ const confirmPassword = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -425,9 +425,9 @@ describe('POST /user/auth/local/register', () => {
context('attach to facebook user', () => {
let user;
- let email = 'some@email.net';
- let username = 'some-username';
- let password = 'some-password';
+ const email = 'some@email.net';
+ const username = 'some-username';
+ const password = 'some-password';
beforeEach(async () => {
user = await generateUser();
});
@@ -458,7 +458,8 @@ describe('POST /user/auth/local/register', () => {
});
context('login is already taken', () => {
- let username, email, api;
+ let username; let email; let
+ api;
beforeEach(async () => {
api = requester();
@@ -473,8 +474,8 @@ describe('POST /user/auth/local/register', () => {
});
it('rejects if username is already taken', async () => {
- let uniqueEmail = `${generateRandomUserName()}@example.com`;
- let password = 'password';
+ const uniqueEmail = `${generateRandomUserName()}@example.com`;
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username,
@@ -489,8 +490,8 @@ describe('POST /user/auth/local/register', () => {
});
it('rejects if email is already taken', async () => {
- let uniqueUsername = generateRandomUserName();
- let password = 'password';
+ const uniqueUsername = generateRandomUserName();
+ const password = 'password';
await expect(api.post('/user/auth/local/register', {
username: uniqueUsername,
@@ -506,7 +507,8 @@ describe('POST /user/auth/local/register', () => {
});
context('req.query.groupInvite', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
api = requester();
@@ -516,7 +518,7 @@ describe('POST /user/auth/local/register', () => {
});
it('does not crash the signup process when it\'s invalid', async () => {
- let user = await api.post('/user/auth/local/register?groupInvite=aaaaInvalid', {
+ const user = await api.post('/user/auth/local/register?groupInvite=aaaaInvalid', {
username,
email,
password,
@@ -527,17 +529,17 @@ describe('POST /user/auth/local/register', () => {
});
it('supports invite using req.query.groupInvite', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(), // so we can let it expire
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -550,11 +552,11 @@ describe('POST /user/auth/local/register', () => {
});
it('awards achievement to inviter', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(),
@@ -572,17 +574,17 @@ describe('POST /user/auth/local/register', () => {
});
it('user not added to a party on expired invite', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'party', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now() - 6.912e8, // 8 days old
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -593,17 +595,17 @@ describe('POST /user/auth/local/register', () => {
});
it('adds a user to a guild on an invite of type other than party', async () => {
- let { group, groupLeader } = await createAndPopulateGroup({
+ const { group, groupLeader } = await createAndPopulateGroup({
groupDetails: { type: 'guild', privacy: 'private' },
});
- let invite = encrypt(JSON.stringify({
+ const invite = encrypt(JSON.stringify({
id: group._id,
inviter: groupLeader._id,
sentAt: Date.now(),
}));
- let user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
+ const user = await api.post(`/user/auth/local/register?groupInvite=${invite}`, {
username,
email,
password,
@@ -619,7 +621,8 @@ describe('POST /user/auth/local/register', () => {
});
context('successful login via api', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
api = requester();
@@ -629,7 +632,7 @@ describe('POST /user/auth/local/register', () => {
});
it('sets all site tour values to -2 (already seen)', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -638,13 +641,13 @@ describe('POST /user/auth/local/register', () => {
expect(user.flags.tour).to.not.be.empty;
- each(user.flags.tour, (value) => {
+ each(user.flags.tour, value => {
expect(value).to.eql(-2);
});
});
it('populates user with default todos, not no other task types', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -658,7 +661,7 @@ describe('POST /user/auth/local/register', () => {
});
it('populates user with default tags', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -670,17 +673,18 @@ describe('POST /user/auth/local/register', () => {
});
context('successful login with habitica-web header', () => {
- let api, username, email, password;
+ let api; let username; let email; let
+ password;
beforeEach(() => {
- api = requester({}, {'x-client': 'habitica-web'});
+ api = requester({}, { 'x-client': 'habitica-web' });
username = generateRandomUserName();
email = `${username}@example.com`;
password = 'password';
});
it('sets all common tutorial flags to true', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -689,13 +693,13 @@ describe('POST /user/auth/local/register', () => {
expect(user.flags.tour).to.not.be.empty;
- each(user.flags.tutorial.common, (value) => {
+ each(user.flags.tutorial.common, value => {
expect(value).to.eql(true);
});
});
it('populates user with default todos, habits, and rewards', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -709,7 +713,7 @@ describe('POST /user/auth/local/register', () => {
});
it('populates user with default tags', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
@@ -720,17 +724,17 @@ describe('POST /user/auth/local/register', () => {
});
it('adds the correct tags to the correct tasks', async () => {
- let user = await api.post('/user/auth/local/register', {
+ const user = await api.post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let requests = new ApiUser(user);
+ const requests = new ApiUser(user);
- let habits = await requests.get('/tasks/user?type=habits');
- let todos = await requests.get('/tasks/user?type=todos');
+ const habits = await requests.get('/tasks/user?type=habits');
+ const todos = await requests.get('/tasks/user?type=todos');
expect(habits).to.have.a.lengthOf(0);
expect(todos).to.have.a.lengthOf(0);
diff --git a/test/api/v4/user/auth/POST-user_verify_display_name.test.js b/test/api/v4/user/auth/POST-user_verify_display_name.test.js
index 8fa1b9d5b9..77f30f6a4f 100644
--- a/test/api/v4/user/auth/POST-user_verify_display_name.test.js
+++ b/test/api/v4/user/auth/POST-user_verify_display_name.test.js
@@ -13,8 +13,8 @@ describe('POST /user/auth/verify-display-name', async () => {
});
it('successfully verifies display name including funky characters', async () => {
- let newDisplayName = 'Sabé 🤬';
- let response = await user.post(ENDPOINT, {
+ const newDisplayName = 'Sabé 🤬';
+ const response = await user.post(ENDPOINT, {
displayName: newDisplayName,
});
expect(response).to.eql({ isUsable: true });
diff --git a/test/api/v4/user/auth/POST-user_verify_username.test.js b/test/api/v4/user/auth/POST-user_verify_username.test.js
index c17b789a41..2ae95b1c52 100644
--- a/test/api/v4/user/auth/POST-user_verify_username.test.js
+++ b/test/api/v4/user/auth/POST-user_verify_username.test.js
@@ -13,16 +13,16 @@ describe('POST /user/auth/verify-username', async () => {
});
it('successfully verifies username', async () => {
- let newUsername = 'new-username';
- let response = await user.post(ENDPOINT, {
+ const newUsername = 'new-username';
+ const response = await user.post(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ isUsable: true });
});
it('successfully verifies username with allowed characters', async () => {
- let newUsername = 'new-username_123';
- let response = await user.post(ENDPOINT, {
+ const newUsername = 'new-username_123';
+ const response = await user.post(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ isUsable: true });
diff --git a/test/client/unit/index.js b/test/client/unit/index.js
index f56cc96744..9a3f4b6f9a 100644
--- a/test/client/unit/index.js
+++ b/test/client/unit/index.js
@@ -1,3 +1,4 @@
+/* eslint-disable */
// TODO verify if it's needed, added because Axios require Promise in the global scope
// and babel-runtime doesn't affect external libraries
require('babel-polyfill');
@@ -12,9 +13,9 @@ afterEach(() => {
});
// require all test files
-let testsContext = require.context('./specs', true, /\.js$/);
+const testsContext = require.context('./specs', true, /\.js$/);
testsContext.keys().forEach(testsContext);
// require all .vue and .js files except main.js for coverage.
-let srcContext = require.context('../../../website/client', true, /^\.\/(?=(?!main(\.js)?$))(?=(.*\.(vue|js)$))/);
-srcContext.keys().forEach(srcContext);
\ No newline at end of file
+const srcContext = require.context('../../../website/client', true, /^\.\/(?=(?!main(\.js)?$))(?=(.*\.(vue|js)$))/);
+srcContext.keys().forEach(srcContext);
diff --git a/test/client/unit/karma.conf.js b/test/client/unit/karma.conf.js
index 7bc7b3800e..b12c5aac67 100644
--- a/test/client/unit/karma.conf.js
+++ b/test/client/unit/karma.conf.js
@@ -1,3 +1,4 @@
+/* eslint-disable */
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
@@ -6,7 +7,8 @@
// Necessary for babel to respect the env version of .babelrc which is necessary
// Because inject-loader does not work with ["es2015", { modules: false }] that we use
// in order to let webpack2 handle the imports
-process.env.CHROME_BIN = require('puppeteer').executablePath(); // eslint-disable-line no-process-env
+process.env.CHROME_BIN = require('puppeteer').executablePath();
+// eslint-disable-line no-process-env
process.env.BABEL_ENV = process.env.NODE_ENV; // eslint-disable-line no-process-env
const webpackConfig = require('../../../webpack/webpack.test.conf');
diff --git a/test/common/count.js b/test/common/count.js
index fd44d04b7d..6320b2d3c4 100644
--- a/test/common/count.js
+++ b/test/common/count.js
@@ -1,64 +1,64 @@
/* eslint-disable camelcase */
-let count = require('../../website/common/script/count');
+const count = require('../../website/common/script/count');
describe('count', () => {
describe('beastMasterProgress', () => {
it('returns 0 if no pets', () => {
- let pets = {};
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const pets = {};
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(0);
});
it('counts drop pets', () => {
- let pets = { 'Dragon-Red': 1, 'Wolf-Base': 2 };
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const pets = { 'Dragon-Red': 1, 'Wolf-Base': 2 };
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(2);
});
it('does not count quest pets', () => {
- let pets = { 'Dragon-Red': 1, 'Gryphon-Base': 1 };
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const pets = { 'Dragon-Red': 1, 'Gryphon-Base': 1 };
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(1);
});
it('does not count pets hatched with premium potions', () => {
- let pets = {
+ const pets = {
'Wolf-Spooky': 5,
'Dragon-Spooky': 5,
'FlyingPig-Base': 5,
};
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(1);
});
it('does not count special pets', () => {
- let pets = {
+ const pets = {
'Wolf-Base': 2,
'Wolf-Veteran': 1,
'Wolf-Cerberus': 1,
'Dragon-Hydra': 1,
};
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(1);
});
it('counts drop pets that have been raised to a mount', () => {
- let raisedToMount = -1;
- let pets = { 'Dragon-Red': 1, 'Wolf-Base': raisedToMount };
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const raisedToMount = -1;
+ const pets = { 'Dragon-Red': 1, 'Wolf-Base': raisedToMount };
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(2);
});
it('does not counts drop pets that have been released', () => {
- let releasedPet = 0;
- let pets = { 'Dragon-Red': 1, 'Wolf-Base': releasedPet };
- let beastMasterTotal = count.beastMasterProgress(pets);
+ const releasedPet = 0;
+ const pets = { 'Dragon-Red': 1, 'Wolf-Base': releasedPet };
+ const beastMasterTotal = count.beastMasterProgress(pets);
expect(beastMasterTotal).to.eql(1);
});
@@ -66,47 +66,47 @@ describe('count', () => {
describe('mountMasterProgress', () => {
it('returns 0 if no mounts', () => {
- let mounts = {};
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const mounts = {};
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(0);
});
it('counts drop mounts', () => {
- let mounts = { 'Dragon-Red': true, 'Wolf-Base': true };
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const mounts = { 'Dragon-Red': true, 'Wolf-Base': true };
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(2);
});
it('does not count premium mounts', () => {
- let mounts = {
+ const mounts = {
'Dragon-Red': true,
'FlyingPig-Spooky': true,
};
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(1);
});
it('does not count quest mounts', () => {
- let mounts = { 'Dragon-Red': true, 'Gryphon-Base': true };
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const mounts = { 'Dragon-Red': true, 'Gryphon-Base': true };
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(1);
});
it('does not count special mounts', () => {
- let mounts = { 'Wolf-Base': true, 'BearCub-Polar': true};
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const mounts = { 'Wolf-Base': true, 'BearCub-Polar': true };
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(1);
});
it('only counts drop mounts that are currently owned', () => {
- let notCurrentlyOwned = false;
- let mounts = { 'Dragon-Red': true, 'Wolf-Base': notCurrentlyOwned };
- let mountMasterTotal = count.mountMasterProgress(mounts);
+ const notCurrentlyOwned = false;
+ const mounts = { 'Dragon-Red': true, 'Wolf-Base': notCurrentlyOwned };
+ const mountMasterTotal = count.mountMasterProgress(mounts);
expect(mountMasterTotal).to.eql(1);
});
@@ -114,7 +114,7 @@ describe('count', () => {
describe('remainingGearInSet', () => {
it('counts remaining gear based on set', () => {
- let gear = {
+ const gear = {
weapon_wizard_0: true,
weapon_wizard_1: true,
weapon_warrior_0: true,
@@ -123,20 +123,20 @@ describe('count', () => {
weapon_armor_1: true,
};
- let armoireCount = count.remainingGearInSet(gear, 'warrior');
+ const armoireCount = count.remainingGearInSet(gear, 'warrior');
expect(armoireCount).to.eql(20);
});
it.skip('includes previously owned items in count (https: //github.com/HabitRPG/habitrpg/issues/5624#issuecomment-124018717)', () => {
- let gear = {
+ const gear = {
weapon_warrior_0: false,
weapon_warrior_1: false,
weapon_armor_0: true,
weapon_armor_1: true,
};
- let armoireCount = count.remainingGearInSet(gear, 'warrior');
+ const armoireCount = count.remainingGearInSet(gear, 'warrior');
expect(armoireCount).to.eql(20);
});
@@ -144,45 +144,45 @@ describe('count', () => {
describe('dropPetsCurrentlyOwned', () => {
it('counts drop pets owned', () => {
- let pets = {
+ const pets = {
'Wolf-Base': 2,
'Wolf-Red': 4,
};
- let dropPets = count.dropPetsCurrentlyOwned(pets);
+ const dropPets = count.dropPetsCurrentlyOwned(pets);
expect(dropPets).to.eql(2);
});
it('does not count pets that have been raised to mounts', () => {
- let pets = {
+ const pets = {
'Wolf-Base': -1,
'Wolf-Red': 4,
'Wolf-Veteran': 1,
'Gryphon-Base': 1,
};
- let dropPets = count.dropPetsCurrentlyOwned(pets);
+ const dropPets = count.dropPetsCurrentlyOwned(pets);
expect(dropPets).to.eql(1);
});
it('does not count quest pets', () => {
- let pets = {
+ const pets = {
'Wolf-Base': 2,
'Wolf-Red': 4,
'Gryphon-Base': 1,
};
- let dropPets = count.dropPetsCurrentlyOwned(pets);
+ const dropPets = count.dropPetsCurrentlyOwned(pets);
expect(dropPets).to.eql(2);
});
it('does not count special pets', () => {
- let pets = {
+ const pets = {
'Wolf-Base': 2,
'Wolf-Red': 4,
'Wolf-Veteran': 1,
};
- let dropPets = count.dropPetsCurrentlyOwned(pets);
+ const dropPets = count.dropPetsCurrentlyOwned(pets);
expect(dropPets).to.eql(2);
});
@@ -190,16 +190,16 @@ describe('count', () => {
describe('questsOfCategory', () => {
it('counts user quest scrolls of a particular category', () => {
- let quests = {
+ const quests = {
atom1: 2,
whale: 4,
kraken: 2,
sheep: 1,
goldenknight2: 1,
};
- let petQuestCount = count.questsOfCategory(quests, 'pet');
- let unlockableQuestCount = count.questsOfCategory(quests, 'unlockable');
- let goldQuestCount = count.questsOfCategory(quests, 'gold');
+ const petQuestCount = count.questsOfCategory(quests, 'pet');
+ const unlockableQuestCount = count.questsOfCategory(quests, 'unlockable');
+ const goldQuestCount = count.questsOfCategory(quests, 'gold');
expect(petQuestCount).to.eql(3);
expect(unlockableQuestCount).to.eql(2);
diff --git a/test/common/fns/autoAllocate.test.js b/test/common/fns/autoAllocate.test.js
index 7db6f0d371..89d2859c1d 100644
--- a/test/common/fns/autoAllocate.test.js
+++ b/test/common/fns/autoAllocate.test.js
@@ -9,8 +9,8 @@ describe('shared.fns.autoAllocate', () => {
beforeEach(() => {
user = generateUser();
// necessary to test task training reset behavior
- user.stats.toObject = function () {
- let obj = JSON.parse(JSON.stringify(this));
+ user.stats.toObject = function toObject () {
+ const obj = JSON.parse(JSON.stringify(this));
return obj;
};
diff --git a/test/common/fns/crit.test.js b/test/common/fns/crit.test.js
index c4925c48c8..70261ebdef 100644
--- a/test/common/fns/crit.test.js
+++ b/test/common/fns/crit.test.js
@@ -11,7 +11,7 @@ describe('crit', () => {
});
it('computes', () => {
- let result = crit.crit(user);
+ const result = crit.crit(user);
expect(result).to.eql(1);
});
});
diff --git a/test/common/fns/handleTwoHanded.js b/test/common/fns/handleTwoHanded.js
index b45594fd12..03ae38f3de 100644
--- a/test/common/fns/handleTwoHanded.js
+++ b/test/common/fns/handleTwoHanded.js
@@ -13,11 +13,11 @@ describe('shared.fns.handleTwoHanded', () => {
});
it('uses "messageTwoHandedUnequip" message if item is a shield and current weapon is two handed (and sets the user\'s weapon to the base one)', () => {
- let item = content.gear.tree.shield.warrior['2'];
- let currentWeapon = content.gear.tree.weapon.armoire.rancherLasso;
+ const item = content.gear.tree.shield.warrior['2'];
+ const currentWeapon = content.gear.tree.weapon.armoire.rancherLasso;
user.items.gear.equipped.weapon = 'weapon_armoire_rancherLasso';
- let message = handleTwoHanded(user, item);
+ const message = handleTwoHanded(user, item);
expect(message).to.equal(i18n.t('messageTwoHandedUnequip', {
twoHandedText: currentWeapon.text(), offHandedText: item.text(),
}));
@@ -25,11 +25,11 @@ describe('shared.fns.handleTwoHanded', () => {
});
it('uses "messageTwoHandedEquip" message if item is two handed and currentShield exists but is not "shield_base_0" (and sets the user\'s shield to the base one)', () => {
- let item = content.gear.tree.weapon.armoire.rancherLasso;
- let currentShield = content.gear.tree.shield.armoire.gladiatorShield;
+ const item = content.gear.tree.weapon.armoire.rancherLasso;
+ const currentShield = content.gear.tree.shield.armoire.gladiatorShield;
user.items.gear.equipped.shield = 'shield_armoire_gladiatorShield';
- let message = handleTwoHanded(user, item);
+ const message = handleTwoHanded(user, item);
expect(message).to.equal(i18n.t('messageTwoHandedEquip', {
twoHandedText: item.text(), offHandedText: currentShield.text(),
}));
diff --git a/test/common/fns/predictableRandom.test.js b/test/common/fns/predictableRandom.test.js
index a4c726699e..5a4eeb9a05 100644
--- a/test/common/fns/predictableRandom.test.js
+++ b/test/common/fns/predictableRandom.test.js
@@ -18,8 +18,8 @@ describe('shared.fns.predictableRandom', () => {
user.stats.hp = 43;
user.stats.gp = 34;
- let val1 = predictableRandom(user);
- let val2 = predictableRandom(user);
+ const val1 = predictableRandom(user);
+ const val2 = predictableRandom(user);
expect(val2).to.equal(val1);
});
@@ -27,24 +27,24 @@ describe('shared.fns.predictableRandom', () => {
it('returns a different value when user.stats is not the same and no seed is passed', () => {
user.stats.hp = 43;
user.stats.gp = 34;
- let val1 = predictableRandom(user);
+ const val1 = predictableRandom(user);
user.stats.gp = 35;
- let val2 = predictableRandom(user);
+ const val2 = predictableRandom(user);
expect(val2).to.not.equal(val1);
});
it('returns the same value when the same seed is passed', () => {
- let val1 = predictableRandom(user, 4452673762);
- let val2 = predictableRandom(user, 4452673762);
+ const val1 = predictableRandom(user, 4452673762);
+ const val2 = predictableRandom(user, 4452673762);
expect(val2).to.equal(val1);
});
it('returns a different value when a different seed is passed', () => {
- let val1 = predictableRandom(user, 4452673761);
- let val2 = predictableRandom(user, 4452673762);
+ const val1 = predictableRandom(user, 4452673761);
+ const val2 = predictableRandom(user, 4452673762);
expect(val2).to.not.equal(val1);
});
diff --git a/test/common/fns/randomDrop.test.js b/test/common/fns/randomDrop.test.js
index c04bddacb7..6ebc31d2df 100644
--- a/test/common/fns/randomDrop.test.js
+++ b/test/common/fns/randomDrop.test.js
@@ -113,8 +113,9 @@ describe('common.fns.randomDrop', () => {
randomDrop(user, { task, predictableRandom });
expect(user._tmp.drop.type).to.eql('HatchingPotion');
expect(user._tmp.drop.value).to.eql(4);
- let acceptableDrops = ['Zombie', 'CottonCandyPink', 'CottonCandyBlue'];
- expect(acceptableDrops).to.contain(user._tmp.drop.key); // deterministically 'CottonCandyBlue'
+ const acceptableDrops = ['Zombie', 'CottonCandyPink', 'CottonCandyBlue'];
+ // deterministically 'CottonCandyBlue'
+ expect(acceptableDrops).to.contain(user._tmp.drop.key);
});
it('drops an uncommon potion', () => {
@@ -123,7 +124,7 @@ describe('common.fns.randomDrop', () => {
randomDrop(user, { task, predictableRandom });
expect(user._tmp.drop.type).to.eql('HatchingPotion');
expect(user._tmp.drop.value).to.eql(3);
- let acceptableDrops = ['Red', 'Shade', 'Skeleton'];
+ const acceptableDrops = ['Red', 'Shade', 'Skeleton'];
expect(acceptableDrops).to.contain(user._tmp.drop.key); // always skeleton
});
@@ -133,7 +134,7 @@ describe('common.fns.randomDrop', () => {
randomDrop(user, { task, predictableRandom });
expect(user._tmp.drop.type).to.eql('HatchingPotion');
expect(user._tmp.drop.value).to.eql(2);
- let acceptableDrops = ['Base', 'White', 'Desert'];
+ const acceptableDrops = ['Base', 'White', 'Desert'];
expect(acceptableDrops).to.contain(user._tmp.drop.key); // always Desert
});
});
diff --git a/test/common/fns/statsComputed.test.js b/test/common/fns/statsComputed.test.js
index 2fad55b349..2dce64dfd6 100644
--- a/test/common/fns/statsComputed.test.js
+++ b/test/common/fns/statsComputed.test.js
@@ -11,7 +11,7 @@ describe('common.fns.statsComputed', () => {
});
it('returns default values', () => {
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.per).to.eql(0);
expect(result.con).to.eql(0);
expect(result.str).to.eql(0);
@@ -20,7 +20,7 @@ describe('common.fns.statsComputed', () => {
it('calculates stat bonuses for equipment', () => {
user.items.gear.equipped.weapon = 'weapon_rogue_1';
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(2);
expect(result.gearBonus.str).to.eql(2);
@@ -28,7 +28,7 @@ describe('common.fns.statsComputed', () => {
it('calculates stat bonuses for class', () => {
user.items.gear.equipped.weapon = 'weapon_warrior_1';
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(4.5);
expect(result.gearBonus.str).to.eql(3);
@@ -37,7 +37,7 @@ describe('common.fns.statsComputed', () => {
it('calculates stat bonuses for level', () => {
user.stats.lvl = 25;
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(12);
expect(result.levelBonus.str).to.eql(12);
@@ -45,7 +45,7 @@ describe('common.fns.statsComputed', () => {
it('correctly caps level stat bonuses', () => {
user.stats.lvl = 150;
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(50);
expect(result.levelBonus.str).to.eql(50);
@@ -53,7 +53,7 @@ describe('common.fns.statsComputed', () => {
it('sets baseStat field', () => {
user.stats.str = 20;
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(20);
expect(result.baseStat.str).to.eql(20);
@@ -61,7 +61,7 @@ describe('common.fns.statsComputed', () => {
it('sets buffs field', () => {
user.stats.buffs.str = 150;
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.str).to.eql(150);
expect(result.buff.str).to.eql(150);
@@ -70,14 +70,14 @@ describe('common.fns.statsComputed', () => {
it('calculates mp from intelligence', () => {
user.stats.int = 150;
user.stats.buffs.int = 50;
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.maxMP).to.eql(430);
});
it('calculates stat bonuses for back equipment', () => {
user.items.gear.equipped.back = 'back_special_takeThis';
- let result = statsComputed(user);
+ const result = statsComputed(user);
expect(result.int).to.eql(1);
expect(result.per).to.eql(1);
diff --git a/test/common/fns/ultimateGear.js b/test/common/fns/ultimateGear.js
index 06530dd938..e5d35f4cba 100644
--- a/test/common/fns/ultimateGear.js
+++ b/test/common/fns/ultimateGear.js
@@ -8,24 +8,22 @@ describe('shared.fns.ultimateGear', () => {
beforeEach(() => {
user = generateUser();
- user.achievements.ultimateGearSets.toObject = function () {
+ user.achievements.ultimateGearSets.toObject = function toIbject () {
return this;
};
user.addNotification = sinon.spy();
});
it('sets armoirEnabled when partial achievement already achieved', () => {
- let items = {
+ const items = {
gear: {
owned: {
- toObject: () => {
- return {
- armor_warrior_5: true, // eslint-disable-line camelcase
- shield_warrior_5: true, // eslint-disable-line camelcase
- head_warrior_5: true, // eslint-disable-line camelcase
- weapon_warrior_6: true, // eslint-disable-line camelcase
- };
- },
+ toObject: () => ({
+ armor_warrior_5: true, // eslint-disable-line camelcase
+ shield_warrior_5: true, // eslint-disable-line camelcase
+ head_warrior_5: true, // eslint-disable-line camelcase
+ weapon_warrior_6: true, // eslint-disable-line camelcase
+ }),
},
},
};
@@ -40,17 +38,15 @@ describe('shared.fns.ultimateGear', () => {
it('does not set armoireEnabled when gear is not owned', () => {
user.flags.armoireEnabled = false;
- let items = {
+ const items = {
gear: {
owned: {
- toObject: () => {
- return {
- armor_warrior_5: true, // eslint-disable-line camelcase
- shield_warrior_5: true, // eslint-disable-line camelcase
- head_warrior_5: true, // eslint-disable-line camelcase
- weapon_warrior_6: false, // eslint-disable-line camelcase
- };
- },
+ toObject: () => ({
+ armor_warrior_5: true, // eslint-disable-line camelcase
+ shield_warrior_5: true, // eslint-disable-line camelcase
+ head_warrior_5: true, // eslint-disable-line camelcase
+ weapon_warrior_6: false, // eslint-disable-line camelcase
+ }),
},
},
};
diff --git a/test/common/fns/updateStats.test.js b/test/common/fns/updateStats.test.js
index de14a8ffff..d98f23341d 100644
--- a/test/common/fns/updateStats.test.js
+++ b/test/common/fns/updateStats.test.js
@@ -12,8 +12,8 @@ describe('common.fns.updateStats', () => {
});
context('No Hp', () => {
- it('updates user\s hp', () => {
- let stats = { hp: 0 };
+ it('updates user\'s hp', () => {
+ const stats = { hp: 0 };
expect(user.stats.hp).to.not.eql(0);
updateStats(user, stats);
expect(user.stats.hp).to.eql(0);
@@ -22,7 +22,7 @@ describe('common.fns.updateStats', () => {
});
it('does not lower hp below 0', () => {
- let stats = {
+ const stats = {
hp: -5,
};
updateStats(user, stats);
@@ -32,7 +32,7 @@ describe('common.fns.updateStats', () => {
context('Stat Allocation', () => {
it('adds only attribute points up to user\'s level', () => {
- let stats = {
+ const stats = {
exp: 261,
};
expect(user.stats.points).to.eql(0);
@@ -45,7 +45,7 @@ describe('common.fns.updateStats', () => {
});
it('adds an attibute point when user\'s stat points are less than max level', () => {
- let stats = {
+ const stats = {
exp: 3581,
};
@@ -61,7 +61,7 @@ describe('common.fns.updateStats', () => {
});
it('does not add an attibute point when user\'s stat points are equal to max level', () => {
- let stats = {
+ const stats = {
exp: 3581,
};
@@ -77,7 +77,7 @@ describe('common.fns.updateStats', () => {
});
it('does not add an attibute point when user\'s stat points + unallocated points are equal to max level', () => {
- let stats = {
+ const stats = {
exp: 3581,
};
@@ -94,7 +94,7 @@ describe('common.fns.updateStats', () => {
});
it('only awards stat points up to level 100 if user is missing unallocated stat points and is over level 100', () => {
- let stats = {
+ const stats = {
exp: 5581,
};
@@ -182,7 +182,7 @@ describe('common.fns.updateStats', () => {
xit('auto allocates stats if automaticAllocation is turned on', () => {
sandbox.stub(user.fns, 'autoAllocate');
- let stats = {
+ const stats = {
exp: 261,
};
diff --git a/test/common/libs/achievements.test.js b/test/common/libs/achievements.test.js
index 784e27b993..e3e356ff1b 100644
--- a/test/common/libs/achievements.test.js
+++ b/test/common/libs/achievements.test.js
@@ -5,11 +5,11 @@ import {
describe('achievements', () => {
describe('general well-formedness', () => {
- let user = generateUser();
- let achievements = shared.achievements.getAchievementsForProfile(user);
+ const user = generateUser();
+ const achievements = shared.achievements.getAchievementsForProfile(user);
it('each category has \'label\' and \'achievements\' fields', () => {
- _.each(achievements, (category) => {
+ _.each(achievements, category => {
expect(category).to.have.property('label')
.that.is.a('string');
expect(category).to.have.property('achievements')
@@ -18,8 +18,8 @@ describe('achievements', () => {
});
it('each achievement has all required fields of correct types', () => {
- _.each(achievements, (category) => {
- _.each(category.achievements, (achiev) => {
+ _.each(achievements, category => {
+ _.each(category.achievements, achiev => {
// May have additional fields (such as 'value' and 'optionalCount').
expect(achiev).to.contain.all.keys(['title', 'text', 'icon', 'earned', 'index']);
expect(achiev.title).to.be.a('string');
@@ -32,18 +32,18 @@ describe('achievements', () => {
});
it('categories have unique labels', () => {
- let achievementsArray = _.values(achievements).map(cat => cat.label);
- let labels = _.uniq(achievementsArray);
+ const achievementsArray = _.values(achievements).map(cat => cat.label);
+ const labels = _.uniq(achievementsArray);
expect(labels.length).to.be.greaterThan(0);
expect(labels.length).to.eql(_.size(achievements));
});
it('achievements have unique keys', () => {
- let keysSoFar = {};
+ const keysSoFar = {};
- _.each(achievements, (category) => {
- _.keys(category.achievements).forEach((key) => {
+ _.each(achievements, category => {
+ _.keys(category.achievements).forEach(key => {
expect(keysSoFar[key]).to.be.undefined;
keysSoFar[key] = key;
});
@@ -51,11 +51,11 @@ describe('achievements', () => {
});
it('achievements have unique indices', () => {
- let indicesSoFar = {};
+ const indicesSoFar = {};
- _.each(achievements, (category) => {
- _.each(category.achievements, (achiev) => {
- let i = achiev.index;
+ _.each(achievements, category => {
+ _.each(category.achievements, achiev => {
+ const i = achiev.index;
expect(indicesSoFar[i]).to.be.undefined;
indicesSoFar[i] = i;
});
@@ -63,19 +63,19 @@ describe('achievements', () => {
});
it('all categories have at least 1 achievement', () => {
- _.each(achievements, (category) => {
+ _.each(achievements, category => {
expect(_.size(category.achievements)).to.be.greaterThan(0);
});
});
});
describe('unearned basic achievements', () => {
- let user = generateUser();
- let basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
+ const user = generateUser();
+ const basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
it('streak and perfect day achievements exist with counts', () => {
- let streak = basicAchievs.streak;
- let perfect = basicAchievs.perfect;
+ const { streak } = basicAchievs;
+ const { perfect } = basicAchievs;
expect(streak).to.exist;
expect(streak).to.have.property('optionalCount')
@@ -86,8 +86,8 @@ describe('achievements', () => {
});
it('party up/on achievements exist with no counts', () => {
- let partyUp = basicAchievs.partyUp;
- let partyOn = basicAchievs.partyOn;
+ const { partyUp } = basicAchievs;
+ const { partyOn } = basicAchievs;
expect(partyUp).to.exist;
expect(partyUp.optionalCount).to.be.undefined;
@@ -96,9 +96,9 @@ describe('achievements', () => {
});
it('pet/mount master and triad bingo achievements exist with counts', () => {
- let beastMaster = basicAchievs.beastMaster;
- let mountMaster = basicAchievs.mountMaster;
- let triadBingo = basicAchievs.triadBingo;
+ const { beastMaster } = basicAchievs;
+ const { mountMaster } = basicAchievs;
+ const { triadBingo } = basicAchievs;
expect(beastMaster).to.exist;
expect(beastMaster).to.have.property('optionalCount')
@@ -112,9 +112,9 @@ describe('achievements', () => {
});
it('ultimate gear achievements exist with no counts', () => {
- let gearTypes = ['healer', 'rogue', 'warrior', 'mage'];
- gearTypes.forEach((gear) => {
- let gearAchiev = basicAchievs[`${gear}UltimateGear`];
+ const gearTypes = ['healer', 'rogue', 'warrior', 'mage'];
+ gearTypes.forEach(gear => {
+ const gearAchiev = basicAchievs[`${gear}UltimateGear`];
expect(gearAchiev).to.exist;
expect(gearAchiev.optionalCount).to.be.undefined;
@@ -122,9 +122,9 @@ describe('achievements', () => {
});
it('card achievements exist with counts', () => {
- let cardTypes = ['greeting', 'thankyou', 'birthday', 'congrats', 'getwell', 'goodluck'];
- cardTypes.forEach((card) => {
- let cardAchiev = basicAchievs[`${card}Cards`];
+ const cardTypes = ['greeting', 'thankyou', 'birthday', 'congrats', 'getwell', 'goodluck'];
+ cardTypes.forEach(card => {
+ const cardAchiev = basicAchievs[`${card}Cards`];
expect(cardAchiev).to.exist;
expect(cardAchiev).to.have.property('optionalCount')
@@ -133,7 +133,7 @@ describe('achievements', () => {
});
it('rebirth achievement exists with no count', () => {
- let rebirth = basicAchievs.rebirth;
+ const { rebirth } = basicAchievs;
expect(rebirth).to.exist;
expect(rebirth.optionalCount).to.be.undefined;
@@ -141,12 +141,13 @@ describe('achievements', () => {
});
describe('unearned seasonal achievements', () => {
- let user = generateUser();
- let seasonalAchievs = shared.achievements.getAchievementsForProfile(user).seasonal.achievements;
+ const user = generateUser();
+ const userAchievements = shared.achievements.getAchievementsForProfile(user);
+ const seasonalAchievs = userAchievements.seasonal.achievements;
it('habiticaDays and habitBirthdays achievements exist with counts', () => {
- let habiticaDays = seasonalAchievs.habiticaDays;
- let habitBirthdays = seasonalAchievs.habitBirthdays;
+ const { habiticaDays } = seasonalAchievs;
+ const { habitBirthdays } = seasonalAchievs;
expect(habiticaDays).to.exist;
expect(habiticaDays).to.have.property('optionalCount')
@@ -157,9 +158,9 @@ describe('achievements', () => {
});
it('spell achievements exist with counts', () => {
- let spellTypes = ['snowball', 'spookySparkles', 'shinySeed', 'seafoam'];
- spellTypes.forEach((spell) => {
- let spellAchiev = seasonalAchievs[spell];
+ const spellTypes = ['snowball', 'spookySparkles', 'shinySeed', 'seafoam'];
+ spellTypes.forEach(spell => {
+ const spellAchiev = seasonalAchievs[spell];
expect(spellAchiev).to.exist;
expect(spellAchiev).to.have.property('optionalCount')
@@ -168,16 +169,16 @@ describe('achievements', () => {
});
it('quest achievements do not exist', () => {
- let quests = ['dilatory', 'stressbeast', 'burnout', 'bewilder'];
- quests.forEach((quest) => {
- let questAchiev = seasonalAchievs[`${quest}Quest`];
+ const quests = ['dilatory', 'stressbeast', 'burnout', 'bewilder'];
+ quests.forEach(quest => {
+ const questAchiev = seasonalAchievs[`${quest}Quest`];
expect(questAchiev).to.not.exist;
});
});
it('costumeContests achievement exists with count', () => {
- let costumeContests = seasonalAchievs.costumeContests;
+ const { costumeContests } = seasonalAchievs;
expect(costumeContests).to.exist;
expect(costumeContests).to.have.property('optionalCount')
@@ -185,9 +186,9 @@ describe('achievements', () => {
});
it('card achievements exist with counts', () => {
- let cardTypes = ['nye', 'valentine'];
- cardTypes.forEach((card) => {
- let cardAchiev = seasonalAchievs[`${card}Cards`];
+ const cardTypes = ['nye', 'valentine'];
+ cardTypes.forEach(card => {
+ const cardAchiev = seasonalAchievs[`${card}Cards`];
expect(cardAchiev).to.exist;
expect(cardAchiev).to.have.property('optionalCount')
@@ -197,11 +198,11 @@ describe('achievements', () => {
});
describe('unearned special achievements', () => {
- let user = generateUser();
- let specialAchievs = shared.achievements.getAchievementsForProfile(user).special.achievements;
+ const user = generateUser();
+ const specialAchievs = shared.achievements.getAchievementsForProfile(user).special.achievements;
it('habitSurveys achievement exists with count', () => {
- let habitSurveys = specialAchievs.habitSurveys;
+ const { habitSurveys } = specialAchievs;
expect(habitSurveys).to.exist;
expect(habitSurveys).to.have.property('optionalCount')
@@ -209,7 +210,7 @@ describe('achievements', () => {
});
it('contributor achievement exists with value and no count', () => {
- let contributor = specialAchievs.contributor;
+ const { contributor } = specialAchievs;
expect(contributor).to.exist;
expect(contributor).to.have.property('value')
@@ -218,37 +219,38 @@ describe('achievements', () => {
});
it('npc achievement is hidden if unachieved', () => {
- let npc = specialAchievs.npc;
+ const { npc } = specialAchievs;
expect(npc).to.not.exist;
});
it('kickstarter achievement is hidden if unachieved', () => {
- let kickstarter = specialAchievs.kickstarter;
+ const { kickstarter } = specialAchievs;
expect(kickstarter).to.not.exist;
});
it('veteran achievement is hidden if unachieved', () => {
- let veteran = specialAchievs.veteran;
+ const { veteran } = specialAchievs;
expect(veteran).to.not.exist;
});
it('originalUser achievement is hidden if unachieved', () => {
- let originalUser = specialAchievs.originalUser;
+ const { originalUser } = specialAchievs;
expect(originalUser).to.not.exist;
});
});
describe('earned seasonal achievements', () => {
- let user = generateUser();
- let quests = ['dilatory', 'stressbeast', 'burnout', 'bewilder'];
- quests.forEach((quest) => {
+ const user = generateUser();
+ const quests = ['dilatory', 'stressbeast', 'burnout', 'bewilder'];
+ quests.forEach(quest => {
user.achievements.quests[quest] = 1;
});
- let seasonalAchievs = shared.achievements.getAchievementsForProfile(user).seasonal.achievements;
+ const userAchievements = shared.achievements.getAchievementsForProfile(user);
+ const seasonalAchievs = userAchievements.seasonal.achievements;
it('quest achievements exist', () => {
- quests.forEach((quest) => {
- let questAchiev = seasonalAchievs[`${quest}Quest`];
+ quests.forEach(quest => {
+ const questAchiev = seasonalAchievs[`${quest}Quest`];
expect(questAchiev).to.exist;
expect(questAchiev.optionalCount).to.be.undefined;
@@ -257,19 +259,19 @@ describe('achievements', () => {
});
describe('earned special achievements', () => {
- let user = generateUser({
+ const user = generateUser({
achievements: {
habitSurveys: 2,
veteran: true,
originalUser: true,
},
- backer: {tier: 3},
- contributor: {level: 1},
+ backer: { tier: 3 },
+ contributor: { level: 1 },
});
- let specialAchievs = shared.achievements.getAchievementsForProfile(user).special.achievements;
+ const specialAchievs = shared.achievements.getAchievementsForProfile(user).special.achievements;
it('habitSurveys achievement is earned with correct value', () => {
- let habitSurveys = specialAchievs.habitSurveys;
+ const { habitSurveys } = specialAchievs;
expect(habitSurveys).to.exist;
expect(habitSurveys.earned).to.eql(true);
@@ -277,7 +279,7 @@ describe('achievements', () => {
});
it('contributor achievement is earned with correct value', () => {
- let contributor = specialAchievs.contributor;
+ const { contributor } = specialAchievs;
expect(contributor).to.exist;
expect(contributor.earned).to.eql(true);
@@ -285,10 +287,10 @@ describe('achievements', () => {
});
it('npc achievement is earned with correct value', () => {
- let npcUser = generateUser({
- backer: {npc: 'test'},
+ const npcUser = generateUser({
+ backer: { npc: 'test' },
});
- let npc = shared.achievements.getAchievementsForProfile(npcUser).special.achievements.npc;
+ const { npc } = shared.achievements.getAchievementsForProfile(npcUser).special.achievements;
expect(npc).to.exist;
expect(npc.earned).to.eql(true);
@@ -296,7 +298,7 @@ describe('achievements', () => {
});
it('kickstarter achievement is earned with correct value', () => {
- let kickstarter = specialAchievs.kickstarter;
+ const { kickstarter } = specialAchievs;
expect(kickstarter).to.exist;
expect(kickstarter.earned).to.eql(true);
@@ -304,14 +306,14 @@ describe('achievements', () => {
});
it('veteran achievement is earned', () => {
- let veteran = specialAchievs.veteran;
+ const { veteran } = specialAchievs;
expect(veteran).to.exist;
expect(veteran.earned).to.eql(true);
});
it('originalUser achievement is earned', () => {
- let originalUser = specialAchievs.originalUser;
+ const { originalUser } = specialAchievs;
expect(originalUser).to.exist;
expect(originalUser.earned).to.eql(true);
@@ -320,12 +322,12 @@ describe('achievements', () => {
describe('mountMaster, beastMaster, and triadBingo achievements', () => {
it('master and triad bingo achievements do not include *Text2 strings if no keys have been used', () => {
- let user = generateUser();
- let basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
+ const user = generateUser();
+ const basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
- let beastMaster = basicAchievs.beastMaster;
- let mountMaster = basicAchievs.mountMaster;
- let triadBingo = basicAchievs.triadBingo;
+ const { beastMaster } = basicAchievs;
+ const { mountMaster } = basicAchievs;
+ const { triadBingo } = basicAchievs;
expect(beastMaster.text).to.not.match(/released/);
expect(beastMaster.text).to.not.match(/0 time\(s\)/);
@@ -336,18 +338,18 @@ describe('achievements', () => {
});
it('master and triad bingo achievements includes *Text2 strings if keys have been used', () => {
- let user = generateUser({
+ const user = generateUser({
achievements: {
beastMasterCount: 1,
mountMasterCount: 2,
triadBingoCount: 3,
},
});
- let basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
+ const basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
- let beastMaster = basicAchievs.beastMaster;
- let mountMaster = basicAchievs.mountMaster;
- let triadBingo = basicAchievs.triadBingo;
+ const { beastMaster } = basicAchievs;
+ const { mountMaster } = basicAchievs;
+ const { triadBingo } = basicAchievs;
expect(beastMaster.text).to.match(/released/);
expect(beastMaster.text).to.match(/1 time\(s\)/);
@@ -360,13 +362,13 @@ describe('achievements', () => {
describe('ultimateGear achievements', () => {
it('title and text contain localized class info', () => {
- let user = generateUser();
- let basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
- let gearTypes = ['healer', 'rogue', 'warrior', 'mage'];
+ const user = generateUser();
+ const basicAchievs = shared.achievements.getAchievementsForProfile(user).basic.achievements;
+ const gearTypes = ['healer', 'rogue', 'warrior', 'mage'];
- gearTypes.forEach((gear) => {
- let gearAchiev = basicAchievs[`${gear}UltimateGear`];
- let classNameRegex = new RegExp(gear.charAt(0).toUpperCase() + gear.slice(1));
+ gearTypes.forEach(gear => {
+ const gearAchiev = basicAchievs[`${gear}UltimateGear`];
+ const classNameRegex = new RegExp(gear.charAt(0).toUpperCase() + gear.slice(1));
expect(gearAchiev.title).to.match(classNameRegex);
expect(gearAchiev.text).to.match(classNameRegex);
diff --git a/test/common/libs/appliedTags.test.js b/test/common/libs/appliedTags.test.js
index b40b0ed232..313e89e6e3 100644
--- a/test/common/libs/appliedTags.test.js
+++ b/test/common/libs/appliedTags.test.js
@@ -2,9 +2,9 @@ import appliedTags from '../../../website/common/script/libs/appliedTags';
describe('appliedTags', () => {
it('returns the tasks', () => {
- let userTags = [{ id: 'tag1', name: 'tag 1' }, { id: 'tag2', name: 'tag 2' }, { id: 'tag3', name: 'tag 3' }];
- let taskTags = ['tag2', 'tag3'];
- let result = appliedTags(userTags, taskTags);
+ const userTags = [{ id: 'tag1', name: 'tag 1' }, { id: 'tag2', name: 'tag 2' }, { id: 'tag3', name: 'tag 3' }];
+ const taskTags = ['tag2', 'tag3'];
+ const result = appliedTags(userTags, taskTags);
expect(result).to.eql('tag 2, tag 3');
});
});
diff --git a/test/common/libs/hasClass.test.js b/test/common/libs/hasClass.test.js
index 1b7f9cc6c2..42f17653a6 100644
--- a/test/common/libs/hasClass.test.js
+++ b/test/common/libs/hasClass.test.js
@@ -3,49 +3,49 @@ import { generateUser } from '../../helpers/common.helper';
describe('hasClass', () => {
it('returns false for user with level below 10', () => {
- let userLvl9 = generateUser({
+ const userLvl9 = generateUser({
'stats.lvl': 9,
'flags.classSelected': true,
'preferences.disableClasses': false,
});
- let result = hasClass(userLvl9);
+ const result = hasClass(userLvl9);
expect(result).to.eql(false);
});
it('returns false for user with class not selected', () => {
- let userClassNotSelected = generateUser({
+ const userClassNotSelected = generateUser({
'stats.lvl': 10,
'flags.classSelected': false,
'preferences.disableClasses': false,
});
- let result = hasClass(userClassNotSelected);
+ const result = hasClass(userClassNotSelected);
expect(result).to.eql(false);
});
it('returns false for user with classes disabled', () => {
- let userClassesDisabled = generateUser({
+ const userClassesDisabled = generateUser({
'stats.lvl': 10,
'flags.classSelected': true,
'preferences.disableClasses': true,
});
- let result = hasClass(userClassesDisabled);
+ const result = hasClass(userClassesDisabled);
expect(result).to.eql(false);
});
it('returns true for user with class', () => {
- let userClassSelected = generateUser({
+ const userClassSelected = generateUser({
'stats.lvl': 10,
'flags.classSelected': true,
'preferences.disableClasses': false,
});
- let result = hasClass(userClassSelected);
+ const result = hasClass(userClassSelected);
expect(result).to.eql(true);
});
diff --git a/test/common/libs/inAppRewards.js b/test/common/libs/inAppRewards.js
index 43369f4307..a6093a63e8 100644
--- a/test/common/libs/inAppRewards.js
+++ b/test/common/libs/inAppRewards.js
@@ -1,7 +1,7 @@
import {
generateUser,
} from '../../helpers/common.helper';
-import getOfficialPinnedItems from '../../../website/common/script/libs/getOfficialPinnedItems.js';
+import getOfficialPinnedItems from '../../../website/common/script/libs/getOfficialPinnedItems';
import inAppRewards from '../../../website/common/script/libs/inAppRewards';
describe('inAppRewards', () => {
@@ -16,7 +16,8 @@ describe('inAppRewards', () => {
officialPinnedItems = getOfficialPinnedItems(user);
officialPinnedItemPaths = [];
- // officialPinnedItems are returned in { type: ..., path:... } format but we just need the paths for testPinnedItemsOrder
+ // officialPinnedItems are returned in { type: ..., path:... } format
+ // but we just need the paths for testPinnedItemsOrder
if (officialPinnedItems.length > 0) {
officialPinnedItemPaths = officialPinnedItems.map(item => item.path);
}
@@ -56,7 +57,7 @@ describe('inAppRewards', () => {
user.pinnedItems = testPinnedItems;
user.pinnedItemsOrder = testPinnedItemsOrder;
- let result = inAppRewards(user);
+ const result = inAppRewards(user);
expect(result[2].path).to.eql('armoire');
expect(result[9].path).to.eql('potion');
@@ -68,7 +69,7 @@ describe('inAppRewards', () => {
user.pinnedItems.push(undefined);
user.pinnedItemsOrder = testPinnedItemsOrder;
- let result = inAppRewards(user);
+ const result = inAppRewards(user);
expect(result[2].path).to.eql('armoire');
expect(result[9].path).to.eql('potion');
@@ -79,18 +80,18 @@ describe('inAppRewards', () => {
return; // if no seasonal items, this test is not applicable
}
- let testUnpinnedItem = officialPinnedItems[0];
- let testUnpinnedPath = testUnpinnedItem.path;
- let testUnpinnedItems = [
- { type: testUnpinnedItem.type, path: testUnpinnedPath},
+ const testUnpinnedItem = officialPinnedItems[0];
+ const testUnpinnedPath = testUnpinnedItem.path;
+ const testUnpinnedItems = [
+ { type: testUnpinnedItem.type, path: testUnpinnedPath },
];
user.pinnedItems = testPinnedItems;
user.pinnedItemsOrder = testPinnedItemsOrder;
user.unpinnedItems = testUnpinnedItems;
- let result = inAppRewards(user);
- let itemPaths = result.map(item => item.path);
+ const result = inAppRewards(user);
+ const itemPaths = result.map(item => item.path);
expect(itemPaths).to.not.include(testUnpinnedPath);
});
});
diff --git a/test/common/libs/noTags.test.js b/test/common/libs/noTags.test.js
index 6c50108e04..ebd24579f1 100644
--- a/test/common/libs/noTags.test.js
+++ b/test/common/libs/noTags.test.js
@@ -2,12 +2,12 @@ import noTags from '../../../website/common/script/libs/noTags';
describe('noTags', () => {
it('returns true for no tags', () => {
- let result = noTags([]);
+ const result = noTags([]);
expect(result).to.eql(true);
});
it('returns false for some tags', () => {
- let result = noTags(['a', 'b', 'c']);
+ const result = noTags(['a', 'b', 'c']);
expect(result).to.eql(false);
});
});
diff --git a/test/common/libs/pickDeep.js b/test/common/libs/pickDeep.js
index 70fc1904b9..0601a5120a 100644
--- a/test/common/libs/pickDeep.js
+++ b/test/common/libs/pickDeep.js
@@ -6,7 +6,7 @@ describe('pickDeep', () => {
});
it('returns an object of properties taken from the input object', () => {
- let obj = {
+ const obj = {
a: true,
b: [1, 2, 3],
c: {
@@ -19,7 +19,7 @@ describe('pickDeep', () => {
d: false,
};
- let res = pickDeep(obj, ['a', 'b[0]', 'c.nested.two.times']);
+ const res = pickDeep(obj, ['a', 'b[0]', 'c.nested.two.times']);
expect(res.a).to.be.true;
expect(res.b).to.eql([1]);
expect(res.c).to.eql({
diff --git a/test/common/libs/randomVal.js b/test/common/libs/randomVal.js
index 3a46938f76..4cbaceb820 100644
--- a/test/common/libs/randomVal.js
+++ b/test/common/libs/randomVal.js
@@ -1,5 +1,5 @@
+import { times } from 'lodash';
import randomVal from '../../../website/common/script/libs/randomVal';
-import {times} from 'lodash';
describe('randomVal', () => {
let obj;
@@ -18,7 +18,7 @@ describe('randomVal', () => {
});
it('returns a random value from an object', () => {
- let result = randomVal(obj);
+ const result = randomVal(obj);
expect(result).to.be.oneOf([1, 2, 3, 4]);
});
@@ -31,7 +31,7 @@ describe('randomVal', () => {
});
it('returns a random key when the key option is passed in', () => {
- let result = randomVal(obj, { key: true });
+ const result = randomVal(obj, { key: true });
expect(result).to.be.oneOf(['a', 'b', 'c', 'd']);
});
});
diff --git a/test/common/libs/refPush.js b/test/common/libs/refPush.js
index f4470fccb6..4212a36b17 100644
--- a/test/common/libs/refPush.js
+++ b/test/common/libs/refPush.js
@@ -1,10 +1,10 @@
-import shared from '../../../website/common';
import { v4 as generateUUID } from 'uuid';
+import shared from '../../../website/common';
describe('refPush', () => {
it('it hashes one object into another by its id', () => {
- let referenceObject = {};
- let objectToHash = {
+ const referenceObject = {};
+ const objectToHash = {
a: 1,
id: generateUUID(),
};
@@ -17,16 +17,14 @@ describe('refPush', () => {
});
it('it hashes one object into another by a uuid when object does not have an id', () => {
- let referenceObject = {};
- let objectToHash = {
+ const referenceObject = {};
+ const objectToHash = {
a: 1,
};
shared.refPush(referenceObject, objectToHash);
- let hashedObject = _.find(referenceObject, (hashedItem) => {
- return objectToHash.a === hashedItem.a;
- });
+ const hashedObject = _.find(referenceObject, hashedItem => objectToHash.a === hashedItem.a);
expect(hashedObject.a).to.equal(objectToHash.a);
expect(hashedObject.id).to.equal(objectToHash.id);
@@ -34,17 +32,15 @@ describe('refPush', () => {
});
it('it hashes one object into another by a id and gives it the highest sort value', () => {
- let referenceObject = {};
+ const referenceObject = {};
referenceObject[generateUUID()] = { b: 2, sort: 1 };
- let objectToHash = {
+ const objectToHash = {
a: 1,
};
shared.refPush(referenceObject, objectToHash);
- let hashedObject = _.find(referenceObject, (hashedItem) => {
- return objectToHash.a === hashedItem.a;
- });
+ const hashedObject = _.find(referenceObject, hashedItem => objectToHash.a === hashedItem.a);
expect(hashedObject.a).to.equal(objectToHash.a);
expect(hashedObject.id).to.equal(objectToHash.id);
diff --git a/test/common/libs/shops.js b/test/common/libs/shops.js
index 1da334dae0..b46f32f366 100644
--- a/test/common/libs/shops.js
+++ b/test/common/libs/shops.js
@@ -4,31 +4,31 @@ import {
} from '../../helpers/common.helper';
describe('shops', () => {
- let user = generateUser();
+ const user = generateUser();
describe('market', () => {
- let shopCategories = shared.shops.getMarketCategories(user);
+ const shopCategories = shared.shops.getMarketCategories(user);
it('contains at least the 3 default categories', () => {
expect(shopCategories.length).to.be.greaterThan(2);
});
it('does not contain an empty category', () => {
- _.each(shopCategories, (category) => {
+ _.each(shopCategories, category => {
expect(category.items.length).to.be.greaterThan(0);
});
});
it('does not duplicate identifiers', () => {
- let identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
+ const identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
expect(identifiers.length).to.eql(shopCategories.length);
});
it('items contain required fields', () => {
- _.each(shopCategories, (category) => {
- _.each(category.items, (item) => {
- _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'class'], (key) => {
+ _.each(shopCategories, category => {
+ _.each(category.items, item => {
+ _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'class'], key => {
expect(_.has(item, key)).to.eql(true);
});
});
@@ -36,7 +36,7 @@ describe('shops', () => {
});
it('shows relevant non class gear in special category', () => {
- let contributor = generateUser({
+ const contributor = generateUser({
contributor: {
level: 7,
critical: true,
@@ -50,18 +50,18 @@ describe('shops', () => {
},
});
- let gearCategories = shared.shops.getMarketGearCategories(contributor);
- let specialCategory = gearCategories.find(o => o.identifier === 'none');
- expect(specialCategory.items.find((item) => item.key === 'weapon_special_1'));
- expect(specialCategory.items.find((item) => item.key === 'armor_special_1'));
- expect(specialCategory.items.find((item) => item.key === 'head_special_1'));
- expect(specialCategory.items.find((item) => item.key === 'shield_special_1'));
- expect(specialCategory.items.find((item) => item.key === 'weapon_special_critical'));
- expect(specialCategory.items.find((item) => item.key === 'weapon_armoire_basicCrossbow'));// eslint-disable-line camelcase
+ const gearCategories = shared.shops.getMarketGearCategories(contributor);
+ const specialCategory = gearCategories.find(o => o.identifier === 'none');
+ expect(specialCategory.items.find(item => item.key === 'weapon_special_1'));
+ expect(specialCategory.items.find(item => item.key === 'armor_special_1'));
+ expect(specialCategory.items.find(item => item.key === 'head_special_1'));
+ expect(specialCategory.items.find(item => item.key === 'shield_special_1'));
+ expect(specialCategory.items.find(item => item.key === 'weapon_special_critical'));
+ expect(specialCategory.items.find(item => item.key === 'weapon_armoire_basicCrossbow'));// eslint-disable-line camelcase
});
it('does not show gear when it is all owned', () => {
- let userWithItems = generateUser({
+ const userWithItems = generateUser({
stats: {
class: 'wizard',
},
@@ -91,12 +91,12 @@ describe('shops', () => {
});
- let shopWizardItems = shared.shops.getMarketGearCategories(userWithItems).find(x => x.identifier === 'wizard').items.filter(x => x.klass === 'wizard' && (x.owned === false || x.owned === undefined));
+ const shopWizardItems = shared.shops.getMarketGearCategories(userWithItems).find(x => x.identifier === 'wizard').items.filter(x => x.klass === 'wizard' && (x.owned === false || x.owned === undefined));
expect(shopWizardItems.length).to.eql(0);
});
it('shows available gear not yet purchased and previously owned', () => {
- let userWithItems = generateUser({
+ const userWithItems = generateUser({
stats: {
class: 'wizard',
},
@@ -123,7 +123,7 @@ describe('shops', () => {
});
- let shopWizardItems = shared.shops.getMarketGearCategories(userWithItems).find(x => x.identifier === 'wizard').items.filter(x => x.klass === 'wizard' && (x.owned === false || x.owned === undefined));
+ const shopWizardItems = shared.shops.getMarketGearCategories(userWithItems).find(x => x.identifier === 'wizard').items.filter(x => x.klass === 'wizard' && (x.owned === false || x.owned === undefined));
expect(shopWizardItems.find(item => item.key === 'weapon_wizard_5').locked).to.eql(false);
expect(shopWizardItems.find(item => item.key === 'weapon_wizard_6').locked).to.eql(true);
expect(shopWizardItems.find(item => item.key === 'armor_wizard_3').locked).to.eql(false);
@@ -134,31 +134,31 @@ describe('shops', () => {
});
describe('questShop', () => {
- let shopCategories = shared.shops.getQuestShopCategories(user);
+ const shopCategories = shared.shops.getQuestShopCategories(user);
it('does not contain an empty category', () => {
- _.each(shopCategories, (category) => {
+ _.each(shopCategories, category => {
expect(category.items.length).to.be.greaterThan(0);
});
});
it('does not duplicate identifiers', () => {
- let identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
+ const identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
expect(identifiers.length).to.eql(shopCategories.length);
});
it('items contain required fields', () => {
- _.each(shopCategories, (category) => {
+ _.each(shopCategories, category => {
if (category.identifier === 'bundle') {
- _.each(category.items, (item) => {
- _.each(['key', 'text', 'notes', 'value', 'currency', 'purchaseType', 'class'], (key) => {
+ _.each(category.items, item => {
+ _.each(['key', 'text', 'notes', 'value', 'currency', 'purchaseType', 'class'], key => {
expect(_.has(item, key)).to.eql(true);
});
});
} else {
- _.each(category.items, (item) => {
- _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'boss', 'class', 'collect', 'drop', 'unlockCondition', 'lvl'], (key) => {
+ _.each(category.items, item => {
+ _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'boss', 'class', 'collect', 'drop', 'unlockCondition', 'lvl'], key => {
expect(_.has(item, key)).to.eql(true);
});
});
@@ -168,24 +168,24 @@ describe('shops', () => {
});
describe('timeTravelers', () => {
- let shopCategories = shared.shops.getTimeTravelersCategories(user);
+ const shopCategories = shared.shops.getTimeTravelersCategories(user);
it('does not contain an empty category', () => {
- _.each(shopCategories, (category) => {
+ _.each(shopCategories, category => {
expect(category.items.length).to.be.greaterThan(0);
});
});
it('does not duplicate identifiers', () => {
- let identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
+ const identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
expect(identifiers.length).to.eql(shopCategories.length);
});
it('items contain required fields', () => {
- _.each(shopCategories, (category) => {
- _.each(category.items, (item) => {
- _.each(['key', 'text', 'value', 'currency', 'locked', 'purchaseType', 'class', 'notes', 'class'], (key) => {
+ _.each(shopCategories, category => {
+ _.each(category.items, item => {
+ _.each(['key', 'text', 'value', 'currency', 'locked', 'purchaseType', 'class', 'notes', 'class'], key => {
expect(_.has(item, key)).to.eql(true);
});
});
@@ -194,24 +194,24 @@ describe('shops', () => {
});
describe('seasonalShop', () => {
- let shopCategories = shared.shops.getSeasonalShopCategories(user);
+ const shopCategories = shared.shops.getSeasonalShopCategories(user);
it('does not contain an empty category', () => {
- _.each(shopCategories, (category) => {
+ _.each(shopCategories, category => {
expect(category.items.length).to.be.greaterThan(0);
});
});
it('does not duplicate identifiers', () => {
- let identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
+ const identifiers = Array.from(new Set(shopCategories.map(cat => cat.identifier)));
expect(identifiers.length).to.eql(shopCategories.length);
});
it('items contain required fields', () => {
- _.each(shopCategories, (category) => {
- _.each(category.items, (item) => {
- _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'type'], (key) => {
+ _.each(shopCategories, category => {
+ _.each(category.items, item => {
+ _.each(['key', 'text', 'notes', 'value', 'currency', 'locked', 'purchaseType', 'type'], key => {
expect(_.has(item, key)).to.eql(true);
});
});
diff --git a/test/common/libs/taskDefaults.test.js b/test/common/libs/taskDefaults.test.js
index 1ec59b562c..e69bafa45d 100644
--- a/test/common/libs/taskDefaults.test.js
+++ b/test/common/libs/taskDefaults.test.js
@@ -5,7 +5,7 @@ import { generateUser } from '../../helpers/common.helper';
describe('taskDefaults', () => {
it('applies defaults to undefined type or habit', () => {
- let task = taskDefaults({}, generateUser());
+ const task = taskDefaults({}, generateUser());
expect(task.type).to.eql('habit');
expect(task._id).to.exist;
expect(task.text).to.eql(task._id);
@@ -21,7 +21,7 @@ describe('taskDefaults', () => {
});
it('applies defaults to a daily', () => {
- let task = taskDefaults({ type: 'daily' }, generateUser());
+ const task = taskDefaults({ type: 'daily' }, generateUser());
expect(task.type).to.eql('daily');
expect(task._id).to.exist;
expect(task.text).to.eql(task._id);
@@ -45,7 +45,7 @@ describe('taskDefaults', () => {
});
it('applies defaults a reward', () => {
- let task = taskDefaults({ type: 'reward' }, generateUser());
+ const task = taskDefaults({ type: 'reward' }, generateUser());
expect(task.type).to.eql('reward');
expect(task._id).to.exist;
expect(task.text).to.eql(task._id);
@@ -55,7 +55,7 @@ describe('taskDefaults', () => {
});
it('applies defaults a todo', () => {
- let task = taskDefaults({ type: 'todo' }, generateUser());
+ const task = taskDefaults({ type: 'todo' }, generateUser());
expect(task.type).to.eql('todo');
expect(task._id).to.exist;
expect(task.text).to.eql(task._id);
@@ -67,15 +67,15 @@ describe('taskDefaults', () => {
it('starts a task yesterday if user cron is later today', () => {
// Configure to have a day start that's *always* tomorrow.
- let user = generateUser({'preferences.dayStart': 25});
- let task = taskDefaults({ type: 'daily' }, user);
+ const user = generateUser({ 'preferences.dayStart': 25 });
+ const task = taskDefaults({ type: 'daily' }, user);
expect(task.startDate).to.eql(
moment()
.zone(user.preferences.timezoneOffset, 'hour')
.startOf('day')
.subtract(1, 'day')
- .toDate()
+ .toDate(),
);
});
});
diff --git a/test/common/libs/updateStore.js b/test/common/libs/updateStore.js
index e0e856adca..bc096fc21b 100644
--- a/test/common/libs/updateStore.js
+++ b/test/common/libs/updateStore.js
@@ -6,52 +6,36 @@ import i18n from '../../../website/common/script/i18n';
describe('updateStore', () => {
context('returns a list of gear items available for purchase', () => {
- let user = generateUser();
+ const user = generateUser();
user.items.gear.owned.armor_armoire_lunarArmor = false; // eslint-disable-line camelcase
user.contributor.level = 2;
user.purchased.plan.mysteryItems = ['armor_mystery_201402'];
user.items.gear.owned.armor_mystery_201402 = false; // eslint-disable-line camelcase
- let list = shared.updateStore(user);
+ const list = shared.updateStore(user);
it('contains the first item not purchased for each gear type', () => {
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorWarrior1Text');
- })).to.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorWarrior1Text'))).to.exist;
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorWarrior2Text');
- })).to.not.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorWarrior2Text'))).to.not.exist;
});
it('contains mystery items the user can own', () => {
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorMystery201402Text');
- })).to.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorMystery201402Text'))).to.exist;
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorMystery201403Text');
- })).to.not.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorMystery201403Text'))).to.not.exist;
});
it('contains special items the user can own', () => {
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorSpecial1Text');
- })).to.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorSpecial1Text'))).to.exist;
- expect(_.find(list, item => {
- return item.text() === i18n.t('headSpecial1Text');
- })).to.not.exist;
+ expect(_.find(list, item => item.text() === i18n.t('headSpecial1Text'))).to.not.exist;
});
it('contains armoire items the user can own', () => {
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorArmoireLunarArmorText');
- })).to.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorArmoireLunarArmorText'))).to.exist;
- expect(_.find(list, item => {
- return item.text() === i18n.t('armorArmoireGladiatorArmorText');
- })).to.not.exist;
+ expect(_.find(list, item => item.text() === i18n.t('armorArmoireGladiatorArmorText'))).to.not.exist;
});
});
});
diff --git a/test/common/ops/addTask.js b/test/common/ops/addTask.js
index 9d5e1d7a8e..6f02f47fdc 100644
--- a/test/common/ops/addTask.js
+++ b/test/common/ops/addTask.js
@@ -15,7 +15,7 @@ describe('shared.ops.addTask', () => {
});
it('adds an habit', () => {
- let habit = addTask(user, {
+ const habit = addTask(user, {
body: {
type: 'habit',
text: 'habit',
@@ -39,7 +39,7 @@ describe('shared.ops.addTask', () => {
});
it('adds a habit when type is invalid', () => {
- let habit = addTask(user, {
+ const habit = addTask(user, {
body: {
type: 'invalid',
text: 'habit',
@@ -60,7 +60,7 @@ describe('shared.ops.addTask', () => {
});
it('adds a daily', () => {
- let daily = addTask(user, {
+ const daily = addTask(user, {
body: {
type: 'daily',
text: 'daily',
@@ -80,7 +80,7 @@ describe('shared.ops.addTask', () => {
});
it('adds a todo', () => {
- let todo = addTask(user, {
+ const todo = addTask(user, {
body: {
type: 'todo',
text: 'todo',
@@ -99,7 +99,7 @@ describe('shared.ops.addTask', () => {
});
it('adds a reward', () => {
- let reward = addTask(user, {
+ const reward = addTask(user, {
body: {
type: 'reward',
text: 'reward',
diff --git a/test/common/ops/armoireCanOwn.js b/test/common/ops/armoireCanOwn.js
index e0127c4b45..a0dd802aa0 100644
--- a/test/common/ops/armoireCanOwn.js
+++ b/test/common/ops/armoireCanOwn.js
@@ -2,8 +2,8 @@ import * as armoireSet from '../../../website/common/script/content/gear/sets/ar
describe('armoireSet items', () => {
it('checks if canOwn has the same id', () => {
- for (const type of Object.keys(armoireSet)) {
- for (const itemKey of Object.keys(armoireSet[type])) {
+ Object.keys(armoireSet).forEach(type => {
+ Object.keys(armoireSet[type]).forEach(itemKey => {
const ownedKey = `${type}_armoire_${itemKey}`;
expect(armoireSet[type][itemKey].canOwn({
@@ -15,7 +15,7 @@ describe('armoireSet items', () => {
},
},
}), `${ownedKey} canOwn is broken`).to.eq(true);
- }
- }
+ });
+ });
});
});
diff --git a/test/common/ops/blockUser.test.js b/test/common/ops/blockUser.test.js
index 16c439c94d..7c871f5b62 100644
--- a/test/common/ops/blockUser.test.js
+++ b/test/common/ops/blockUser.test.js
@@ -16,7 +16,7 @@ describe('shared.ops.blockUser', () => {
expect(user.inbox.blocks).to.eql([]);
});
- it('validates uuid', (done) => {
+ it('validates uuid', done => {
try {
blockUser(user, { params: { uuid: '1' } });
} catch (error) {
@@ -25,7 +25,7 @@ describe('shared.ops.blockUser', () => {
}
});
- it('validates user can\'t block himself', (done) => {
+ it('validates user can\'t block himself', done => {
try {
blockUser(user, { params: { uuid: user._id } });
} catch (error) {
@@ -46,7 +46,7 @@ describe('shared.ops.blockUser', () => {
it('blocks, then unblocks user', () => {
blockUser(user, { params: { uuid: blockedUser._id } });
expect(user.inbox.blocks).to.eql([blockedUser._id]);
- let [result] = blockUser(user, { params: { uuid: blockedUser._id } });
+ const [result] = blockUser(user, { params: { uuid: blockedUser._id } });
expect(user.inbox.blocks).to.eql([]);
expect(result).to.eql([]);
});
diff --git a/test/common/ops/buy/buy.js b/test/common/ops/buy/buy.js
index 582166e9a9..eed601e10a 100644
--- a/test/common/ops/buy/buy.js
+++ b/test/common/ops/buy/buy.js
@@ -1,4 +1,5 @@
/* eslint-disable camelcase */
+import { defaultsDeep } from 'lodash';
import {
generateUser,
} from '../../../helpers/common.helper';
@@ -9,11 +10,10 @@ import {
import i18n from '../../../../website/common/script/i18n';
import content from '../../../../website/common/script/content/index';
import errorMessage from '../../../../website/common/script/libs/errorMessage';
-import { defaultsDeep } from 'lodash';
describe('shared.ops.buy', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
beforeEach(() => {
user = generateUser({
@@ -40,7 +40,7 @@ describe('shared.ops.buy', () => {
analytics.track.restore();
});
- it('returns error when key is not provided', (done) => {
+ it('returns error when key is not provided', done => {
try {
buy(user);
} catch (err) {
@@ -52,7 +52,7 @@ describe('shared.ops.buy', () => {
it('recovers 15 hp', () => {
user.stats.hp = 30;
- buy(user, {params: {key: 'potion'}}, analytics);
+ buy(user, { params: { key: 'potion' } }, analytics);
expect(user.stats.hp).to.eql(45);
expect(analytics.track).to.be.calledOnce;
@@ -61,7 +61,7 @@ describe('shared.ops.buy', () => {
it('adds equipment to inventory', () => {
user.stats.gp = 31;
- buy(user, {params: {key: 'armor_warrior_1'}});
+ buy(user, { params: { key: 'armor_warrior_1' } });
expect(user.items.gear.owned).to.eql({
weapon_warrior_0: true,
@@ -118,15 +118,15 @@ describe('shared.ops.buy', () => {
type: 'quest',
});
- expect(user.items.quests).to.eql({dilatoryDistress1: 1});
+ expect(user.items.quests).to.eql({ dilatoryDistress1: 1 });
expect(user.stats.gp).to.equal(5);
});
it('buys a special item', () => {
user.stats.gp = 11;
- let item = content.special.thankyou;
+ const item = content.special.thankyou;
- let [data, message] = buy(user, {
+ const [data, message] = buy(user, {
params: {
key: 'thankyou',
},
@@ -146,11 +146,11 @@ describe('shared.ops.buy', () => {
it('allows for bulk purchases', () => {
user.stats.hp = 30;
- buy(user, {params: {key: 'potion'}, quantity: 2});
+ buy(user, { params: { key: 'potion' }, quantity: 2 });
expect(user.stats.hp).to.eql(50);
});
- it('errors if user supplies a non-numeric quantity', (done) => {
+ it('errors if user supplies a non-numeric quantity', done => {
try {
buy(user, {
params: {
@@ -166,7 +166,7 @@ describe('shared.ops.buy', () => {
}
});
- it('errors if user supplies a negative quantity', (done) => {
+ it('errors if user supplies a negative quantity', done => {
try {
buy(user, {
params: {
@@ -182,7 +182,7 @@ describe('shared.ops.buy', () => {
}
});
- it('errors if user supplies a decimal quantity', (done) => {
+ it('errors if user supplies a decimal quantity', done => {
try {
buy(user, {
params: {
diff --git a/test/common/ops/buy/buyArmoire.js b/test/common/ops/buy/buyArmoire.js
index 545c32a359..a3a79d8341 100644
--- a/test/common/ops/buy/buyArmoire.js
+++ b/test/common/ops/buy/buyArmoire.js
@@ -4,7 +4,7 @@ import {
generateUser,
} from '../../../helpers/common.helper';
import * as count from '../../../../website/common/script/count';
-import {BuyArmoireOperation} from '../../../../website/common/script/ops/buy/buyArmoire';
+import { BuyArmoireOperation } from '../../../../website/common/script/ops/buy/buyArmoire';
import * as randomValFns from '../../../../website/common/script/libs/randomVal';
import content from '../../../../website/common/script/content/index';
import {
@@ -13,11 +13,11 @@ import {
import i18n from '../../../../website/common/script/i18n';
function getFullArmoire () {
- let fullArmoire = {};
+ const fullArmoire = {};
- _.each(content.gearTypes, (type) => {
- _.each(content.gear.tree[type].armoire, (gearObject) => {
- let armoireKey = gearObject.key;
+ _.each(content.gearTypes, type => {
+ _.each(content.gear.tree[type].armoire, gearObject => {
+ const armoireKey = gearObject.key;
fullArmoire[armoireKey] = true;
});
@@ -28,10 +28,10 @@ function getFullArmoire () {
describe('shared.ops.buyArmoire', () => {
let user;
- let YIELD_EQUIPMENT = 0.5;
- let YIELD_FOOD = 0.7;
- let YIELD_EXP = 0.9;
- let analytics = {track () {}};
+ const YIELD_EQUIPMENT = 0.5;
+ const YIELD_FOOD = 0.7;
+ const YIELD_EXP = 0.9;
+ const analytics = { track () {} };
function buyArmoire (_user, _req, _analytics) {
const buyOp = new BuyArmoireOperation(_user, _req, _analytics);
@@ -61,7 +61,7 @@ describe('shared.ops.buyArmoire', () => {
});
context('failure conditions', () => {
- it('does not open if user does not have enough gold', (done) => {
+ it('does not open if user does not have enough gold', done => {
user.stats.gp = 50;
try {
@@ -81,25 +81,25 @@ describe('shared.ops.buyArmoire', () => {
context('non-gear awards', () => {
it('gives Experience', () => {
- let previousExp = user.stats.exp;
+ const previousExp = user.stats.exp;
randomValFns.trueRandom.returns(YIELD_EXP);
buyArmoire(user);
- expect(user.items.gear.owned).to.eql({weapon_warrior_0: true});
+ expect(user.items.gear.owned).to.eql({ weapon_warrior_0: true });
expect(user.items.food).to.be.empty;
expect(user.stats.exp).to.be.greaterThan(previousExp);
expect(user.stats.gp).to.equal(100);
});
it('gives food', () => {
- let previousExp = user.stats.exp;
+ const previousExp = user.stats.exp;
randomValFns.trueRandom.returns(YIELD_FOOD);
buyArmoire(user);
- expect(user.items.gear.owned).to.eql({weapon_warrior_0: true});
+ expect(user.items.gear.owned).to.eql({ weapon_warrior_0: true });
expect(user.items.food).to.not.be.empty;
expect(user.stats.exp).to.equal(previousExp);
expect(user.stats.gp).to.equal(100);
@@ -113,7 +113,7 @@ describe('shared.ops.buyArmoire', () => {
buyArmoire(user);
expect(user.items.gear.owned).to.eql(getFullArmoire());
- let armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
+ const armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
expect(armoireCount).to.eql(0);
@@ -132,7 +132,7 @@ describe('shared.ops.buyArmoire', () => {
expect(_.size(user.items.gear.owned)).to.equal(2);
- let armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
+ const armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
expect(armoireCount).to.eql(_.size(getFullArmoire()) - 1);
expect(user.items.food).to.be.empty;
@@ -154,7 +154,7 @@ describe('shared.ops.buyArmoire', () => {
expect(_.size(user.items.gear.owned)).to.equal(3);
- let armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
+ const armoireCount = count.remainingGearInSet(user.items.gear.owned, 'armoire');
expect(armoireCount).to.eql(_.size(getFullArmoire()) - 2);
expect(user.stats.gp).to.eql(100);
diff --git a/test/common/ops/buy/buyGem.js b/test/common/ops/buy/buyGem.js
index fc3d00f708..d0a726a86d 100644
--- a/test/common/ops/buy/buyGem.js
+++ b/test/common/ops/buy/buyGem.js
@@ -8,21 +8,21 @@ import {
BadRequest, NotAuthorized,
} from '../../../../website/common/script/libs/errors';
import i18n from '../../../../website/common/script/i18n';
-import {BuyGemOperation} from '../../../../website/common/script/ops/buy/buyGem';
+import { BuyGemOperation } from '../../../../website/common/script/ops/buy/buyGem';
import planGemLimits from '../../../../website/common/script/libs/planGemLimits';
function buyGem (user, req, analytics) {
- let buyOp = new BuyGemOperation(user, req, analytics);
+ const buyOp = new BuyGemOperation(user, req, analytics);
return buyOp.purchase();
}
describe('shared.ops.buyGem', () => {
let user;
- let analytics = {track () {}};
- let goldPoints = 40;
- let gemsBought = 40;
- let userGemAmount = 10;
+ const analytics = { track () {} };
+ const goldPoints = 40;
+ const gemsBought = 40;
+ const userGemAmount = 10;
beforeEach(() => {
user = generateUser({
@@ -45,9 +45,9 @@ describe('shared.ops.buyGem', () => {
context('Gems', () => {
it('purchases gems', () => {
- let [, message] = buyGem(user, {params: {type: 'gems', key: 'gem'}}, analytics);
+ const [, message] = buyGem(user, { params: { type: 'gems', key: 'gem' } }, analytics);
- expect(message).to.equal(i18n.t('plusGem', {count: 1}));
+ expect(message).to.equal(i18n.t('plusGem', { count: 1 }));
expect(user.balance).to.equal(userGemAmount + 0.25);
expect(user.purchased.plan.gemsBought).to.equal(1);
expect(user.stats.gp).to.equal(goldPoints - planGemLimits.convRate);
@@ -55,21 +55,21 @@ describe('shared.ops.buyGem', () => {
});
it('purchases gems with a different language than the default', () => {
- let [, message] = buyGem(user, {params: {type: 'gems', key: 'gem'}, language: 'de'});
+ const [, message] = buyGem(user, { params: { type: 'gems', key: 'gem' }, language: 'de' });
- expect(message).to.equal(i18n.t('plusGem', {count: 1}, 'de'));
+ expect(message).to.equal(i18n.t('plusGem', { count: 1 }, 'de'));
expect(user.balance).to.equal(userGemAmount + 0.25);
expect(user.purchased.plan.gemsBought).to.equal(1);
expect(user.stats.gp).to.equal(goldPoints - planGemLimits.convRate);
});
it('makes bulk purchases of gems', () => {
- let [, message] = buyGem(user, {
- params: {type: 'gems', key: 'gem'},
+ const [, message] = buyGem(user, {
+ params: { type: 'gems', key: 'gem' },
quantity: 2,
});
- expect(message).to.equal(i18n.t('plusGem', {count: 2}));
+ expect(message).to.equal(i18n.t('plusGem', { count: 2 }));
expect(user.balance).to.equal(userGemAmount + 0.50);
expect(user.purchased.plan.gemsBought).to.equal(2);
expect(user.stats.gp).to.equal(goldPoints - planGemLimits.convRate * 2);
@@ -77,9 +77,9 @@ describe('shared.ops.buyGem', () => {
context('Failure conditions', () => {
- it('returns an error when key is not provided', (done) => {
+ it('returns an error when key is not provided', done => {
try {
- buyGem(user, {params: {type: 'gems'}});
+ buyGem(user, { params: { type: 'gems' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('missingKeyParam'));
@@ -87,11 +87,11 @@ describe('shared.ops.buyGem', () => {
}
});
- it('prevents unsubscribed user from buying gems', (done) => {
+ it('prevents unsubscribed user from buying gems', done => {
delete user.purchased.plan.customerId;
try {
- buyGem(user, {params: {type: 'gems', key: 'gem'}});
+ buyGem(user, { params: { type: 'gems', key: 'gem' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('mustSubscribeToPurchaseGems'));
@@ -99,11 +99,11 @@ describe('shared.ops.buyGem', () => {
}
});
- it('prevents user with not enough gold from buying gems', (done) => {
+ it('prevents user with not enough gold from buying gems', done => {
user.stats.gp = 15;
try {
- buyGem(user, {params: {type: 'gems', key: 'gem'}});
+ buyGem(user, { params: { type: 'gems', key: 'gem' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageNotEnoughGold'));
@@ -111,25 +111,25 @@ describe('shared.ops.buyGem', () => {
}
});
- it('prevents user that have reached the conversion cap from buying gems', (done) => {
+ it('prevents user that have reached the conversion cap from buying gems', done => {
user.stats.gp = goldPoints;
user.purchased.plan.gemsBought = gemsBought;
try {
- buyGem(user, {params: {type: 'gems', key: 'gem'}});
+ buyGem(user, { params: { type: 'gems', key: 'gem' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
- expect(err.message).to.equal(i18n.t('reachedGoldToGemCap', {convCap: planGemLimits.convCap}));
+ expect(err.message).to.equal(i18n.t('reachedGoldToGemCap', { convCap: planGemLimits.convCap }));
done();
}
});
- it('prevents user from buying an invalid quantity', (done) => {
+ it('prevents user from buying an invalid quantity', done => {
user.stats.gp = goldPoints;
user.purchased.plan.gemsBought = gemsBought;
try {
- buyGem(user, {params: {type: 'gems', key: 'gem'}, quantity: 'a'});
+ buyGem(user, { params: { type: 'gems', key: 'gem' }, quantity: 'a' });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('invalidQuantity'));
diff --git a/test/common/ops/buy/buyHealthPotion.js b/test/common/ops/buy/buyHealthPotion.js
index 9f04c4d6bb..5ed2df7e19 100644
--- a/test/common/ops/buy/buyHealthPotion.js
+++ b/test/common/ops/buy/buyHealthPotion.js
@@ -10,7 +10,7 @@ import i18n from '../../../../website/common/script/i18n';
describe('shared.ops.buyHealthPotion', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
function buyHealthPotion (_user, _req, _analytics) {
const buyOp = new BuyHealthPotionOperation(_user, _req, _analytics);
@@ -60,7 +60,7 @@ describe('shared.ops.buyHealthPotion', () => {
expect(user.stats.gp).to.eql(175);
});
- it('does not purchase if not enough gp', (done) => {
+ it('does not purchase if not enough gp', done => {
user.stats.hp = 45;
user.stats.gp = 5;
try {
@@ -75,7 +75,7 @@ describe('shared.ops.buyHealthPotion', () => {
}
});
- it('does not purchase if hp is full', (done) => {
+ it('does not purchase if hp is full', done => {
user.stats.hp = 50;
user.stats.gp = 40;
try {
@@ -90,7 +90,7 @@ describe('shared.ops.buyHealthPotion', () => {
}
});
- it('does not allow potion purchases when hp is zero', (done) => {
+ it('does not allow potion purchases when hp is zero', done => {
user.stats.hp = 0;
user.stats.gp = 40;
try {
@@ -105,7 +105,7 @@ describe('shared.ops.buyHealthPotion', () => {
}
});
- it('does not allow potion purchases when hp is negative', (done) => {
+ it('does not allow potion purchases when hp is negative', done => {
user.stats.hp = -8;
user.stats.gp = 40;
try {
diff --git a/test/common/ops/buy/buyMarketGear.js b/test/common/ops/buy/buyMarketGear.js
index a732afa4e0..3b123d5a6c 100644
--- a/test/common/ops/buy/buyMarketGear.js
+++ b/test/common/ops/buy/buyMarketGear.js
@@ -1,27 +1,27 @@
/* eslint-disable camelcase */
import sinon from 'sinon'; // eslint-disable-line no-shadow
+import { defaultsDeep } from 'lodash';
import {
generateUser,
} from '../../../helpers/common.helper';
-import {BuyMarketGearOperation} from '../../../../website/common/script/ops/buy/buyMarketGear';
+import { BuyMarketGearOperation } from '../../../../website/common/script/ops/buy/buyMarketGear';
import shared from '../../../../website/common/script';
import {
BadRequest, NotAuthorized, NotFound,
} from '../../../../website/common/script/libs/errors';
import i18n from '../../../../website/common/script/i18n';
import errorMessage from '../../../../website/common/script/libs/errorMessage';
-import { defaultsDeep } from 'lodash';
function buyGear (user, req, analytics) {
- let buyOp = new BuyMarketGearOperation(user, req, analytics);
+ const buyOp = new BuyMarketGearOperation(user, req, analytics);
return buyOp.purchase();
}
describe('shared.ops.buyMarketGear', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
beforeEach(() => {
user = generateUser({
@@ -56,7 +56,7 @@ describe('shared.ops.buyMarketGear', () => {
it('adds equipment to inventory', () => {
user.stats.gp = 31;
- buyGear(user, {params: {key: 'armor_warrior_1'}}, analytics);
+ buyGear(user, { params: { key: 'armor_warrior_1' } }, analytics);
expect(user.items.gear.owned).to.eql({
weapon_warrior_0: true,
@@ -89,7 +89,7 @@ describe('shared.ops.buyMarketGear', () => {
it('deducts gold from user', () => {
user.stats.gp = 31;
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
expect(user.stats.gp).to.eql(1);
});
@@ -98,7 +98,7 @@ describe('shared.ops.buyMarketGear', () => {
user.stats.gp = 31;
user.preferences.autoEquip = true;
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
expect(user.items.gear.equipped).to.have.property('armor', 'armor_warrior_1');
});
@@ -106,7 +106,7 @@ describe('shared.ops.buyMarketGear', () => {
it('updates the pinnedItems to the next item in the set if one exists', () => {
user.stats.gp = 31;
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
expect(user.pinnedItems).to.deep.include({
type: 'marketGear',
@@ -118,17 +118,17 @@ describe('shared.ops.buyMarketGear', () => {
user.stats.gp = 31;
user.preferences.autoEquip = false;
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
expect(user.items.gear.equipped.property).to.not.equal('armor_warrior_1');
});
- it('does not buyGear equipment twice', (done) => {
+ it('does not buyGear equipment twice', done => {
user.stats.gp = 62;
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
try {
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('equipmentAlreadyOwned'));
@@ -136,12 +136,12 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('does not buy equipment of different class', (done) => {
+ it('does not buy equipment of different class', done => {
user.stats.gp = 82;
user.stats.class = 'warrior';
try {
- buyGear(user, {params: {key: 'weapon_special_winter2018Rogue'}});
+ buyGear(user, { params: { key: 'weapon_special_winter2018Rogue' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('cannotBuyItem'));
@@ -149,11 +149,11 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('does not buy equipment in bulk', (done) => {
+ it('does not buy equipment in bulk', done => {
user.stats.gp = 82;
try {
- buyGear(user, {params: {key: 'armor_warrior_1'}, quantity: 3});
+ buyGear(user, { params: { key: 'armor_warrior_1' }, quantity: 3 });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageNotAbleToBuyInBulk'));
@@ -165,12 +165,12 @@ describe('shared.ops.buyMarketGear', () => {
xit('removes one-handed weapon and shield if auto-equip is on and a two-hander is bought', () => {
user.stats.gp = 100;
user.preferences.autoEquip = true;
- buyGear(user, {params: {key: 'shield_warrior_1'}});
- user.ops.equip({params: {key: 'shield_warrior_1'}});
- buyGear(user, {params: {key: 'weapon_warrior_1'}});
- user.ops.equip({params: {key: 'weapon_warrior_1'}});
+ buyGear(user, { params: { key: 'shield_warrior_1' } });
+ user.ops.equip({ params: { key: 'shield_warrior_1' } });
+ buyGear(user, { params: { key: 'weapon_warrior_1' } });
+ user.ops.equip({ params: { key: 'weapon_warrior_1' } });
- buyGear(user, {params: {key: 'weapon_wizard_1'}});
+ buyGear(user, { params: { key: 'weapon_wizard_1' } });
expect(user.items.gear.equipped).to.have.property('shield', 'shield_base_0');
expect(user.items.gear.equipped).to.have.property('weapon', 'weapon_wizard_1');
@@ -180,22 +180,22 @@ describe('shared.ops.buyMarketGear', () => {
xit('buyGears two-handed equipment but does not automatically remove sword or shield', () => {
user.stats.gp = 100;
user.preferences.autoEquip = false;
- buyGear(user, {params: {key: 'shield_warrior_1'}});
- user.ops.equip({params: {key: 'shield_warrior_1'}});
- buyGear(user, {params: {key: 'weapon_warrior_1'}});
- user.ops.equip({params: {key: 'weapon_warrior_1'}});
+ buyGear(user, { params: { key: 'shield_warrior_1' } });
+ user.ops.equip({ params: { key: 'shield_warrior_1' } });
+ buyGear(user, { params: { key: 'weapon_warrior_1' } });
+ user.ops.equip({ params: { key: 'weapon_warrior_1' } });
- buyGear(user, {params: {key: 'weapon_wizard_1'}});
+ buyGear(user, { params: { key: 'weapon_wizard_1' } });
expect(user.items.gear.equipped).to.have.property('shield', 'shield_warrior_1');
expect(user.items.gear.equipped).to.have.property('weapon', 'weapon_warrior_1');
});
- it('does not buyGear equipment without enough Gold', (done) => {
+ it('does not buyGear equipment without enough Gold', done => {
user.stats.gp = 20;
try {
- buyGear(user, {params: {key: 'armor_warrior_1'}});
+ buyGear(user, { params: { key: 'armor_warrior_1' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageNotEnoughGold'));
@@ -204,7 +204,7 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('returns error when key is not provided', (done) => {
+ it('returns error when key is not provided', done => {
try {
buyGear(user);
} catch (err) {
@@ -214,11 +214,11 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('returns error when item is not found', (done) => {
- let params = {key: 'armor_warrior_notExisting'};
+ it('returns error when item is not found', done => {
+ const params = { key: 'armor_warrior_notExisting' };
try {
- buyGear(user, {params});
+ buyGear(user, { params });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(errorMessage('itemNotFound', params));
@@ -226,9 +226,9 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('does not buyGear equipment without the previous equipment', (done) => {
+ it('does not buyGear equipment without the previous equipment', done => {
try {
- buyGear(user, {params: {key: 'armor_warrior_2'}});
+ buyGear(user, { params: { key: 'armor_warrior_2' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('previousGearNotOwned'));
@@ -236,11 +236,11 @@ describe('shared.ops.buyMarketGear', () => {
}
});
- it('does not buyGear equipment if user does not own prior item in sequence', (done) => {
+ it('does not buyGear equipment if user does not own prior item in sequence', done => {
user.stats.gp = 200;
try {
- buyGear(user, {params: {key: 'armor_warrior_2'}});
+ buyGear(user, { params: { key: 'armor_warrior_2' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('previousGearNotOwned'));
@@ -253,7 +253,7 @@ describe('shared.ops.buyMarketGear', () => {
user.stats.gp = 200;
user.items.gear.owned.head_special_2 = false;
- buyGear(user, {params: {key: 'head_special_2'}});
+ buyGear(user, { params: { key: 'head_special_2' } });
expect(user.items.gear.owned).to.have.property('head_special_2', true);
});
@@ -262,7 +262,7 @@ describe('shared.ops.buyMarketGear', () => {
user.stats.gp = 200;
user.items.gear.owned.shield_armoire_ramHornShield = false;
- buyGear(user, {params: {key: 'shield_armoire_ramHornShield'}});
+ buyGear(user, { params: { key: 'shield_armoire_ramHornShield' } });
expect(user.items.gear.owned).to.have.property('shield_armoire_ramHornShield', true);
});
diff --git a/test/common/ops/buy/buyMysterySet.js b/test/common/ops/buy/buyMysterySet.js
index dca60d7489..6db89cf998 100644
--- a/test/common/ops/buy/buyMysterySet.js
+++ b/test/common/ops/buy/buyMysterySet.js
@@ -14,7 +14,7 @@ import errorMessage from '../../../../website/common/script/libs/errorMessage';
describe('shared.ops.buyMysterySet', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
beforeEach(() => {
user = generateUser({
@@ -35,9 +35,9 @@ describe('shared.ops.buyMysterySet', () => {
context('Mystery Sets', () => {
context('failure conditions', () => {
- it('does not grant mystery sets without Mystic Hourglasses', (done) => {
+ it('does not grant mystery sets without Mystic Hourglasses', done => {
try {
- buyMysterySet(user, {params: {key: '201501'}});
+ buyMysterySet(user, { params: { key: '201501' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('notEnoughHourglasses'));
@@ -46,7 +46,7 @@ describe('shared.ops.buyMysterySet', () => {
}
});
- it('does not grant mystery set that has already been purchased', (done) => {
+ it('does not grant mystery set that has already been purchased', done => {
user.purchased.plan.consecutive.trinkets = 1;
user.items.gear.owned = {
weapon_warrior_0: true,
@@ -57,7 +57,7 @@ describe('shared.ops.buyMysterySet', () => {
};
try {
- buyMysterySet(user, {params: {key: '301404'}});
+ buyMysterySet(user, { params: { key: '301404' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.eql(i18n.t('mysterySetNotFound'));
@@ -66,7 +66,7 @@ describe('shared.ops.buyMysterySet', () => {
}
});
- it('returns error when key is not provided', (done) => {
+ it('returns error when key is not provided', done => {
try {
buyMysterySet(user);
} catch (err) {
@@ -80,7 +80,7 @@ describe('shared.ops.buyMysterySet', () => {
context('successful purchases', () => {
it('buys Steampunk Accessories Set', () => {
user.purchased.plan.consecutive.trinkets = 1;
- buyMysterySet(user, {params: {key: '301404'}}, analytics);
+ buyMysterySet(user, { params: { key: '301404' } }, analytics);
expect(user.purchased.plan.consecutive.trinkets).to.eql(0);
expect(user.items.gear.owned).to.have.property('weapon_warrior_0', true);
diff --git a/test/common/ops/buy/buyQuestGems.js b/test/common/ops/buy/buyQuestGems.js
index 6711165d44..d1c25b0832 100644
--- a/test/common/ops/buy/buyQuestGems.js
+++ b/test/common/ops/buy/buyQuestGems.js
@@ -6,12 +6,12 @@ import i18n from '../../../../website/common/script/i18n';
import {
generateUser,
} from '../../../helpers/common.helper';
-import {BuyQuestWithGemOperation} from '../../../../website/common/script/ops/buy/buyQuestGem';
+import { BuyQuestWithGemOperation } from '../../../../website/common/script/ops/buy/buyQuestGem';
describe('shared.ops.buyQuestGems', () => {
let user;
- let goldPoints = 40;
- let analytics = {track () {}};
+ const goldPoints = 40;
+ const analytics = { track () {} };
function buyQuest (_user, _req, _analytics) {
const buyOp = new BuyQuestWithGemOperation(_user, _req, _analytics);
@@ -20,7 +20,7 @@ describe('shared.ops.buyQuestGems', () => {
}
before(() => {
- user = generateUser({'stats.class': 'rogue'});
+ user = generateUser({ 'stats.class': 'rogue' });
});
beforeEach(() => {
@@ -34,29 +34,29 @@ describe('shared.ops.buyQuestGems', () => {
});
context('successful purchase', () => {
- let userGemAmount = 10;
+ const userGemAmount = 10;
before(() => {
user.balance = userGemAmount;
user.stats.gp = goldPoints;
user.purchased.plan.gemsBought = 0;
user.purchased.plan.customerId = 'customer-id';
- user.pinnedItems.push({type: 'quests', key: 'gryphon'});
+ user.pinnedItems.push({ type: 'quests', key: 'gryphon' });
});
it('purchases quests', () => {
- let key = 'gryphon';
+ const key = 'gryphon';
- buyQuest(user, {params: {key}});
+ buyQuest(user, { params: { key } });
expect(user.items.quests[key]).to.equal(1);
expect(pinnedGearUtils.removeItemByPath.notCalled).to.equal(true);
});
it('if a user\'s count of a quest scroll is negative, it will be reset to 0 before incrementing when they buy a new one.', () => {
- let key = 'dustbunnies';
+ const key = 'dustbunnies';
user.items.quests[key] = -1;
- buyQuest(user, {params: {key}});
+ buyQuest(user, { params: { key } });
expect(user.items.quests[key]).to.equal(1);
expect(pinnedGearUtils.removeItemByPath.notCalled).to.equal(true);
@@ -64,7 +64,7 @@ describe('shared.ops.buyQuestGems', () => {
});
context('bulk purchase', () => {
- let userGemAmount = 10;
+ const userGemAmount = 10;
beforeEach(() => {
user.balance = userGemAmount;
@@ -73,13 +73,13 @@ describe('shared.ops.buyQuestGems', () => {
user.purchased.plan.customerId = 'customer-id';
});
- it('errors when user does not have enough gems', (done) => {
+ it('errors when user does not have enough gems', done => {
user.balance = 1;
- let key = 'gryphon';
+ const key = 'gryphon';
try {
buyQuest(user, {
- params: {key},
+ params: { key },
quantity: 2,
});
} catch (err) {
@@ -90,10 +90,10 @@ describe('shared.ops.buyQuestGems', () => {
});
it('makes bulk purchases of quests', () => {
- let key = 'gryphon';
+ const key = 'gryphon';
buyQuest(user, {
- params: {key},
+ params: { key },
quantity: 3,
});
diff --git a/test/common/ops/buy/buyQuestGold.js b/test/common/ops/buy/buyQuestGold.js
index dec213aa54..f2be81495d 100644
--- a/test/common/ops/buy/buyQuestGold.js
+++ b/test/common/ops/buy/buyQuestGold.js
@@ -1,7 +1,7 @@
import {
generateUser,
} from '../../../helpers/common.helper';
-import {BuyQuestWithGoldOperation} from '../../../../website/common/script/ops/buy/buyQuestGold';
+import { BuyQuestWithGoldOperation } from '../../../../website/common/script/ops/buy/buyQuestGold';
import {
BadRequest,
NotAuthorized,
@@ -12,7 +12,7 @@ import errorMessage from '../../../../website/common/script/libs/errorMessage';
describe('shared.ops.buyQuest', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
function buyQuest (_user, _req, _analytics) {
const buyOp = new BuyQuestWithGoldOperation(_user, _req, _analytics);
@@ -45,10 +45,10 @@ describe('shared.ops.buyQuest', () => {
it('if a user\'s count of a quest scroll is negative, it will be reset to 0 before incrementing when they buy a new one.', () => {
user.stats.gp = 205;
- let key = 'dilatoryDistress1';
+ const key = 'dilatoryDistress1';
user.items.quests[key] = -1;
buyQuest(user, {
- params: {key},
+ params: { key },
}, analytics);
expect(user.items.quests[key]).to.equal(1);
expect(user.stats.gp).to.equal(5);
@@ -74,7 +74,7 @@ describe('shared.ops.buyQuest', () => {
});
});
- it('does not buy a Quest scroll when an invalid quantity is passed', (done) => {
+ it('does not buy a Quest scroll when an invalid quantity is passed', done => {
user.stats.gp = 1000;
try {
buyQuest(user, {
@@ -92,7 +92,7 @@ describe('shared.ops.buyQuest', () => {
}
});
- it('does not buy Quests without enough Gold', (done) => {
+ it('does not buy Quests without enough Gold', done => {
user.stats.gp = 1;
try {
buyQuest(user, {
@@ -109,7 +109,7 @@ describe('shared.ops.buyQuest', () => {
}
});
- it('does not buy nonexistent Quests', (done) => {
+ it('does not buy nonexistent Quests', done => {
user.stats.gp = 9999;
try {
buyQuest(user, {
@@ -119,14 +119,14 @@ describe('shared.ops.buyQuest', () => {
});
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
- expect(err.message).to.equal(errorMessage('questNotFound', {key: 'snarfblatter'}));
+ expect(err.message).to.equal(errorMessage('questNotFound', { key: 'snarfblatter' }));
expect(user.items.quests).to.eql({});
expect(user.stats.gp).to.equal(9999);
done();
}
});
- it('does not buy the Mystery of the Masterclassers', (done) => {
+ it('does not buy the Mystery of the Masterclassers', done => {
try {
buyQuest(user, {
params: {
@@ -142,7 +142,7 @@ describe('shared.ops.buyQuest', () => {
});
- it('does not buy Gem-premium Quests', (done) => {
+ it('does not buy Gem-premium Quests', done => {
user.stats.gp = 9999;
try {
buyQuest(user, {
@@ -152,14 +152,14 @@ describe('shared.ops.buyQuest', () => {
});
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
- expect(err.message).to.equal(i18n.t('questNotGoldPurchasable', {key: 'kraken'}));
+ expect(err.message).to.equal(i18n.t('questNotGoldPurchasable', { key: 'kraken' }));
expect(user.items.quests).to.eql({});
expect(user.stats.gp).to.equal(9999);
done();
}
});
- it('returns error when key is not provided', (done) => {
+ it('returns error when key is not provided', done => {
try {
buyQuest(user);
} catch (err) {
@@ -169,7 +169,7 @@ describe('shared.ops.buyQuest', () => {
}
});
- it('does not buy a quest without completing previous quests', (done) => {
+ it('does not buy a quest without completing previous quests', done => {
try {
buyQuest(user, {
params: {
@@ -178,7 +178,7 @@ describe('shared.ops.buyQuest', () => {
});
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
- expect(err.message).to.equal(i18n.t('mustComplete', {quest: 'dilatoryDistress2'}));
+ expect(err.message).to.equal(i18n.t('mustComplete', { quest: 'dilatoryDistress2' }));
expect(user.items.quests).to.eql({});
done();
}
diff --git a/test/common/ops/buy/buySpell.js b/test/common/ops/buy/buySpell.js
index 02d0bda6a4..83b8008756 100644
--- a/test/common/ops/buy/buySpell.js
+++ b/test/common/ops/buy/buySpell.js
@@ -1,4 +1,4 @@
-import {BuySpellOperation} from '../../../../website/common/script/ops/buy/buySpell';
+import { BuySpellOperation } from '../../../../website/common/script/ops/buy/buySpell';
import {
BadRequest,
NotFound,
@@ -13,7 +13,7 @@ import errorMessage from '../../../../website/common/script/libs/errorMessage';
describe('shared.ops.buySpecialSpell', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
function buySpecialSpell (_user, _req, _analytics) {
const buyOp = new BuySpellOperation(_user, _req, _analytics);
@@ -29,7 +29,7 @@ describe('shared.ops.buySpecialSpell', () => {
analytics.track.restore();
});
- it('throws an error if params.key is missing', (done) => {
+ it('throws an error if params.key is missing', done => {
try {
buySpecialSpell(user);
} catch (err) {
@@ -39,7 +39,7 @@ describe('shared.ops.buySpecialSpell', () => {
}
});
- it('throws an error if the spell doesn\'t exists', (done) => {
+ it('throws an error if the spell doesn\'t exists', done => {
try {
buySpecialSpell(user, {
params: {
@@ -48,12 +48,12 @@ describe('shared.ops.buySpecialSpell', () => {
});
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
- expect(err.message).to.equal(errorMessage('spellNotFound', {spellId: 'notExisting'}));
+ expect(err.message).to.equal(errorMessage('spellNotFound', { spellId: 'notExisting' }));
done();
}
});
- it('throws an error if the user doesn\'t have enough gold', (done) => {
+ it('throws an error if the user doesn\'t have enough gold', done => {
user.stats.gp = 1;
try {
buySpecialSpell(user, {
@@ -70,9 +70,9 @@ describe('shared.ops.buySpecialSpell', () => {
it('buys an item', () => {
user.stats.gp = 11;
- let item = content.special.thankyou;
+ const item = content.special.thankyou;
- let [data, message] = buySpecialSpell(user, {
+ const [data, message] = buySpecialSpell(user, {
params: {
key: 'thankyou',
},
diff --git a/test/common/ops/buy/hourglassPurchase.js b/test/common/ops/buy/hourglassPurchase.js
index 6f9bf50808..a04ad429a3 100644
--- a/test/common/ops/buy/hourglassPurchase.js
+++ b/test/common/ops/buy/hourglassPurchase.js
@@ -9,11 +9,11 @@ import {
generateUser,
} from '../../../helpers/common.helper';
import errorMessage from '../../../../website/common/script/libs/errorMessage';
-import {BuyHourglassMountOperation} from '../../../../website/common/script/ops/buy/buyMount';
+import { BuyHourglassMountOperation } from '../../../../website/common/script/ops/buy/buyMount';
describe('common.ops.hourglassPurchase', () => {
let user;
- let analytics = {track () {}};
+ const analytics = { track () {} };
function buyMount (_user, _req, _analytics) {
const buyOp = new BuyHourglassMountOperation(_user, _req, _analytics);
@@ -31,9 +31,9 @@ describe('common.ops.hourglassPurchase', () => {
});
context('failure conditions', () => {
- it('return error when key is not provided', (done) => {
+ it('return error when key is not provided', done => {
try {
- hourglassPurchase(user, {params: {}});
+ hourglassPurchase(user, { params: {} });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.eql(errorMessage('missingKeyParam'));
@@ -41,9 +41,9 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('returns error when type is not provided', (done) => {
+ it('returns error when type is not provided', done => {
try {
- hourglassPurchase(user, {params: {key: 'Base'}});
+ hourglassPurchase(user, { params: { key: 'Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.eql(errorMessage('missingTypeParam'));
@@ -51,19 +51,19 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('returns error when inccorect type is provided', (done) => {
+ it('returns error when inccorect type is provided', done => {
try {
- hourglassPurchase(user, {params: {type: 'notAType', key: 'MantisShrimp-Base'}});
+ hourglassPurchase(user, { params: { type: 'notAType', key: 'MantisShrimp-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
- expect(err.message).to.eql(i18n.t('typeNotAllowedHourglass', {allowedTypes: _.keys(content.timeTravelStable).toString()}));
+ expect(err.message).to.eql(i18n.t('typeNotAllowedHourglass', { allowedTypes: _.keys(content.timeTravelStable).toString() }));
done();
}
});
- it('does not grant to pets without Mystic Hourglasses', (done) => {
+ it('does not grant to pets without Mystic Hourglasses', done => {
try {
- hourglassPurchase(user, {params: {type: 'pets', key: 'MantisShrimp-Base'}});
+ hourglassPurchase(user, { params: { type: 'pets', key: 'MantisShrimp-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('notEnoughHourglasses'));
@@ -71,9 +71,9 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('does not grant to mounts without Mystic Hourglasses', (done) => {
+ it('does not grant to mounts without Mystic Hourglasses', done => {
try {
- buyMount(user, {params: {key: 'MantisShrimp-Base'}});
+ buyMount(user, { params: { key: 'MantisShrimp-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('notEnoughHourglasses'));
@@ -81,11 +81,11 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('does not grant pet that is not part of the Time Travel Stable', (done) => {
+ it('does not grant pet that is not part of the Time Travel Stable', done => {
user.purchased.plan.consecutive.trinkets = 1;
try {
- hourglassPurchase(user, {params: {type: 'pets', key: 'Wolf-Veteran'}});
+ hourglassPurchase(user, { params: { type: 'pets', key: 'Wolf-Veteran' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('notAllowedHourglass'));
@@ -93,11 +93,11 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('does not grant mount that is not part of the Time Travel Stable', (done) => {
+ it('does not grant mount that is not part of the Time Travel Stable', done => {
user.purchased.plan.consecutive.trinkets = 1;
try {
- buyMount(user, {params: {key: 'Orca-Base'}});
+ buyMount(user, { params: { key: 'Orca-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('notAllowedHourglass'));
@@ -105,14 +105,14 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('does not grant pet that has already been purchased', (done) => {
+ it('does not grant pet that has already been purchased', done => {
user.purchased.plan.consecutive.trinkets = 1;
user.items.pets = {
'MantisShrimp-Base': true,
};
try {
- hourglassPurchase(user, {params: {type: 'pets', key: 'MantisShrimp-Base'}});
+ hourglassPurchase(user, { params: { type: 'pets', key: 'MantisShrimp-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('petsAlreadyOwned'));
@@ -120,14 +120,14 @@ describe('common.ops.hourglassPurchase', () => {
}
});
- it('does not grant mount that has already been purchased', (done) => {
+ it('does not grant mount that has already been purchased', done => {
user.purchased.plan.consecutive.trinkets = 1;
user.items.mounts = {
'MantisShrimp-Base': true,
};
try {
- buyMount(user, {params: {key: 'MantisShrimp-Base'}});
+ buyMount(user, { params: { key: 'MantisShrimp-Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.eql(i18n.t('mountsAlreadyOwned'));
@@ -140,21 +140,21 @@ describe('common.ops.hourglassPurchase', () => {
it('buys a pet', () => {
user.purchased.plan.consecutive.trinkets = 2;
- let [, message] = hourglassPurchase(user, {params: {type: 'pets', key: 'MantisShrimp-Base'}}, analytics);
+ const [, message] = hourglassPurchase(user, { params: { type: 'pets', key: 'MantisShrimp-Base' } }, analytics);
expect(message).to.eql(i18n.t('hourglassPurchase'));
expect(user.purchased.plan.consecutive.trinkets).to.eql(1);
- expect(user.items.pets).to.eql({'MantisShrimp-Base': 5});
+ expect(user.items.pets).to.eql({ 'MantisShrimp-Base': 5 });
expect(analytics.track).to.be.calledOnce;
});
it('buys a mount', () => {
user.purchased.plan.consecutive.trinkets = 2;
- let [, message] = buyMount(user, {params: {key: 'MantisShrimp-Base'}});
+ const [, message] = buyMount(user, { params: { key: 'MantisShrimp-Base' } });
expect(message).to.eql(i18n.t('hourglassPurchase'));
expect(user.purchased.plan.consecutive.trinkets).to.eql(1);
- expect(user.items.mounts).to.eql({'MantisShrimp-Base': true});
+ expect(user.items.mounts).to.eql({ 'MantisShrimp-Base': true });
});
});
});
diff --git a/test/common/ops/buy/purchase.js b/test/common/ops/buy/purchase.js
index 8d7becdb01..c97a8761eb 100644
--- a/test/common/ops/buy/purchase.js
+++ b/test/common/ops/buy/purchase.js
@@ -1,3 +1,5 @@
+import forEach from 'lodash/forEach';
+import moment from 'moment';
import purchase from '../../../../website/common/script/ops/buy/purchase';
import * as pinnedGearUtils from '../../../../website/common/script/ops/pinnedGearUtils';
import {
@@ -9,17 +11,15 @@ import i18n from '../../../../website/common/script/i18n';
import {
generateUser,
} from '../../../helpers/common.helper';
-import forEach from 'lodash/forEach';
-import moment from 'moment';
describe('shared.ops.purchase', () => {
const SEASONAL_FOOD = 'Meat';
let user;
- let goldPoints = 40;
- let analytics = {track () {}};
+ const goldPoints = 40;
+ const analytics = { track () {} };
before(() => {
- user = generateUser({'stats.class': 'rogue'});
+ user = generateUser({ 'stats.class': 'rogue' });
});
beforeEach(() => {
@@ -33,9 +33,9 @@ describe('shared.ops.purchase', () => {
});
context('failure conditions', () => {
- it('returns an error when type is not provided', (done) => {
+ it('returns an error when type is not provided', done => {
try {
- purchase(user, {params: {}});
+ purchase(user, { params: {} });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('typeRequired'));
@@ -44,9 +44,9 @@ describe('shared.ops.purchase', () => {
});
- it('returns error when unknown type is provided', (done) => {
+ it('returns error when unknown type is provided', done => {
try {
- purchase(user, {params: {type: 'randomType', key: 'gem'}});
+ purchase(user, { params: { type: 'randomType', key: 'gem' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('notAccteptedType'));
@@ -54,11 +54,11 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when user attempts to purchase a piece of gear they own', (done) => {
+ it('returns error when user attempts to purchase a piece of gear they own', done => {
user.items.gear.owned['shield_rogue_1'] = true; // eslint-disable-line dot-notation
try {
- purchase(user, {params: {type: 'gear', key: 'shield_rogue_1'}});
+ purchase(user, { params: { type: 'gear', key: 'shield_rogue_1' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('alreadyHave'));
@@ -66,19 +66,19 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when unknown item is requested', (done) => {
+ it('returns error when unknown item is requested', done => {
try {
- purchase(user, {params: {type: 'gear', key: 'randomKey'}});
+ purchase(user, { params: { type: 'gear', key: 'randomKey' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
- expect(err.message).to.equal(i18n.t('contentKeyNotFound', {type: 'gear'}));
+ expect(err.message).to.equal(i18n.t('contentKeyNotFound', { type: 'gear' }));
done();
}
});
- it('returns error when user does not have permission to buy an item', (done) => {
+ it('returns error when user does not have permission to buy an item', done => {
try {
- purchase(user, {params: {type: 'gear', key: 'eyewear_mystery_301405'}});
+ purchase(user, { params: { type: 'gear', key: 'eyewear_mystery_301405' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageNotAvailable'));
@@ -86,9 +86,9 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when user does not have enough gems to buy an item', (done) => {
+ it('returns error when user does not have enough gems to buy an item', done => {
try {
- purchase(user, {params: {type: 'gear', key: 'headAccessory_special_wolfEars'}});
+ purchase(user, { params: { type: 'gear', key: 'headAccessory_special_wolfEars' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('notEnoughGems'));
@@ -97,11 +97,11 @@ describe('shared.ops.purchase', () => {
});
- it('returns error when item is not found', (done) => {
- let params = {key: 'notExisting', type: 'food'};
+ it('returns error when item is not found', done => {
+ const params = { key: 'notExisting', type: 'food' };
try {
- purchase(user, {params});
+ purchase(user, { params });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('contentKeyNotFound', params));
@@ -109,12 +109,12 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when user supplies a non-numeric quantity', (done) => {
- let type = 'eggs';
- let key = 'Wolf';
+ it('returns error when user supplies a non-numeric quantity', done => {
+ const type = 'eggs';
+ const key = 'Wolf';
try {
- purchase(user, {params: {type, key}, quantity: 'jamboree'}, analytics);
+ purchase(user, { params: { type, key }, quantity: 'jamboree' }, analytics);
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('invalidQuantity'));
@@ -122,13 +122,13 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when user supplies a negative quantity', (done) => {
- let type = 'eggs';
- let key = 'Wolf';
+ it('returns error when user supplies a negative quantity', done => {
+ const type = 'eggs';
+ const key = 'Wolf';
user.balance = 10;
try {
- purchase(user, {params: {type, key}, quantity: -2}, analytics);
+ purchase(user, { params: { type, key }, quantity: -2 }, analytics);
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('invalidQuantity'));
@@ -136,13 +136,13 @@ describe('shared.ops.purchase', () => {
}
});
- it('returns error when user supplies a decimal quantity', (done) => {
- let type = 'eggs';
- let key = 'Wolf';
+ it('returns error when user supplies a decimal quantity', done => {
+ const type = 'eggs';
+ const key = 'Wolf';
user.balance = 10;
try {
- purchase(user, {params: {type, key}, quantity: 2.9}, analytics);
+ purchase(user, { params: { type, key }, quantity: 2.9 }, analytics);
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('invalidQuantity'));
@@ -152,25 +152,25 @@ describe('shared.ops.purchase', () => {
});
context('successful purchase', () => {
- let userGemAmount = 10;
+ const userGemAmount = 10;
before(() => {
user.balance = userGemAmount;
user.stats.gp = goldPoints;
user.purchased.plan.gemsBought = 0;
user.purchased.plan.customerId = 'customer-id';
- user.pinnedItems.push({type: 'eggs', key: 'Wolf'});
- user.pinnedItems.push({type: 'hatchingPotions', key: 'Base'});
- user.pinnedItems.push({type: 'food', key: SEASONAL_FOOD});
- user.pinnedItems.push({type: 'gear', key: 'headAccessory_special_tigerEars'});
- user.pinnedItems.push({type: 'bundles', key: 'featheredFriends'});
+ user.pinnedItems.push({ type: 'eggs', key: 'Wolf' });
+ user.pinnedItems.push({ type: 'hatchingPotions', key: 'Base' });
+ user.pinnedItems.push({ type: 'food', key: SEASONAL_FOOD });
+ user.pinnedItems.push({ type: 'gear', key: 'headAccessory_special_tigerEars' });
+ user.pinnedItems.push({ type: 'bundles', key: 'featheredFriends' });
});
it('purchases eggs', () => {
- let type = 'eggs';
- let key = 'Wolf';
+ const type = 'eggs';
+ const key = 'Wolf';
- purchase(user, {params: {type, key}}, analytics);
+ purchase(user, { params: { type, key } }, analytics);
expect(user.items[type][key]).to.equal(1);
expect(pinnedGearUtils.removeItemByPath.notCalled).to.equal(true);
@@ -178,50 +178,50 @@ describe('shared.ops.purchase', () => {
});
it('purchases hatchingPotions', () => {
- let type = 'hatchingPotions';
- let key = 'Base';
+ const type = 'hatchingPotions';
+ const key = 'Base';
- purchase(user, {params: {type, key}});
+ purchase(user, { params: { type, key } });
expect(user.items[type][key]).to.equal(1);
expect(pinnedGearUtils.removeItemByPath.notCalled).to.equal(true);
});
it('purchases food', () => {
- let type = 'food';
- let key = SEASONAL_FOOD;
+ const type = 'food';
+ const key = SEASONAL_FOOD;
- purchase(user, {params: {type, key}});
+ purchase(user, { params: { type, key } });
expect(user.items[type][key]).to.equal(1);
expect(pinnedGearUtils.removeItemByPath.notCalled).to.equal(true);
});
it('purchases gear', () => {
- let type = 'gear';
- let key = 'headAccessory_special_tigerEars';
+ const type = 'gear';
+ const key = 'headAccessory_special_tigerEars';
- purchase(user, {params: {type, key}});
+ purchase(user, { params: { type, key } });
expect(user.items.gear.owned[key]).to.be.true;
expect(pinnedGearUtils.removeItemByPath.calledOnce).to.equal(true);
});
it('purchases quest bundles', () => {
- let startingBalance = user.balance;
- let clock = sandbox.useFakeTimers(moment('2019-05-20').valueOf());
- let type = 'bundles';
- let key = 'featheredFriends';
- let price = 1.75;
- let questList = [
+ const startingBalance = user.balance;
+ const clock = sandbox.useFakeTimers(moment('2019-05-20').valueOf());
+ const type = 'bundles';
+ const key = 'featheredFriends';
+ const price = 1.75;
+ const questList = [
'falcon',
'harpy',
'owl',
];
- purchase(user, {params: {type, key}});
+ purchase(user, { params: { type, key } });
- forEach(questList, (bundledKey) => {
+ forEach(questList, bundledKey => {
expect(user.items.quests[bundledKey]).to.equal(1);
});
@@ -233,7 +233,7 @@ describe('shared.ops.purchase', () => {
});
context('bulk purchase', () => {
- let userGemAmount = 10;
+ const userGemAmount = 10;
beforeEach(() => {
user.balance = userGemAmount;
@@ -242,14 +242,14 @@ describe('shared.ops.purchase', () => {
user.purchased.plan.customerId = 'customer-id';
});
- it('errors when user does not have enough gems', (done) => {
+ it('errors when user does not have enough gems', done => {
user.balance = 1;
- let type = 'eggs';
- let key = 'TigerCub';
+ const type = 'eggs';
+ const key = 'TigerCub';
try {
purchase(user, {
- params: {type, key},
+ params: { type, key },
quantity: 2,
});
} catch (err) {
@@ -260,11 +260,11 @@ describe('shared.ops.purchase', () => {
});
it('makes bulk purchases of eggs', () => {
- let type = 'eggs';
- let key = 'TigerCub';
+ const type = 'eggs';
+ const key = 'TigerCub';
purchase(user, {
- params: {type, key},
+ params: { type, key },
quantity: 2,
});
diff --git a/test/common/ops/changeClass.js b/test/common/ops/changeClass.js
index f4a4f9c451..4b1d31ffd7 100644
--- a/test/common/ops/changeClass.js
+++ b/test/common/ops/changeClass.js
@@ -19,10 +19,10 @@ describe('shared.ops.changeClass', () => {
user.stats.flagSelected = false;
});
- it('user is not level 10', (done) => {
+ it('user is not level 10', done => {
user.stats.lvl = 9;
try {
- changeClass(user, {query: {class: 'rogue'}});
+ changeClass(user, { query: { class: 'rogue' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('lvl10ChangeClass'));
@@ -30,12 +30,12 @@ describe('shared.ops.changeClass', () => {
}
});
- it('req.query.class is an invalid class', (done) => {
+ it('req.query.class is an invalid class', done => {
user.flags.classSelected = false;
user.preferences.disableClasses = false;
try {
- changeClass(user, {query: {class: 'cellist'}});
+ changeClass(user, { query: { class: 'cellist' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('invalidClass'));
@@ -44,13 +44,13 @@ describe('shared.ops.changeClass', () => {
});
context('req.query.class is a valid class', () => {
- it('errors if user.stats.flagSelected is true and user.balance < 0.75', (done) => {
+ it('errors if user.stats.flagSelected is true and user.balance < 0.75', done => {
user.flags.classSelected = true;
user.preferences.disableClasses = false;
user.balance = 0;
try {
- changeClass(user, {query: {class: 'rogue'}});
+ changeClass(user, { query: { class: 'rogue' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('notEnoughGems'));
@@ -63,7 +63,7 @@ describe('shared.ops.changeClass', () => {
user.items.gear.owned.weapon_healer_3 = true;
user.items.gear.equipped.weapon = 'weapon_healer_3';
- let [data] = changeClass(user, {query: {class: 'rogue'}});
+ const [data] = changeClass(user, { query: { class: 'rogue' } });
expect(data).to.eql({
preferences: user.preferences,
stats: user.stats,
@@ -92,7 +92,7 @@ describe('shared.ops.changeClass', () => {
user.stats.int = 4;
user.flags.classSelected = true;
- let [data] = changeClass(user);
+ const [data] = changeClass(user);
expect(data).to.eql({
preferences: user.preferences,
stats: user.stats,
@@ -112,7 +112,7 @@ describe('shared.ops.changeClass', () => {
});
context('has user.preferences.disableClasses !== true', () => {
- it('and less than 3 gems', (done) => {
+ it('and less than 3 gems', done => {
user.balance = 0.5;
try {
changeClass(user);
@@ -132,7 +132,7 @@ describe('shared.ops.changeClass', () => {
user.stats.int = 4;
user.flags.classSelected = true;
- let [data] = changeClass(user);
+ const [data] = changeClass(user);
expect(data).to.eql({
preferences: user.preferences,
stats: user.stats,
diff --git a/test/common/ops/disableClasses.js b/test/common/ops/disableClasses.js
index 60bd3998ab..0f7f6dc5bd 100644
--- a/test/common/ops/disableClasses.js
+++ b/test/common/ops/disableClasses.js
@@ -18,7 +18,7 @@ describe('shared.ops.disableClasses', () => {
user.preferences.autoAllocate = false;
user.stats.points = 2;
- let [data] = disableClasses(user);
+ const [data] = disableClasses(user);
expect(data).to.eql({
preferences: user.preferences,
stats: user.stats,
diff --git a/test/common/ops/equip.js b/test/common/ops/equip.js
index f983891306..c9ac38f15e 100644
--- a/test/common/ops/equip.js
+++ b/test/common/ops/equip.js
@@ -28,58 +28,58 @@ describe('shared.ops.equip', () => {
},
},
},
- stats: {gp: 200},
+ stats: { gp: 200 },
});
});
context('Gear', () => {
it('should not send a message if a weapon is equipped while only having zero or one weapons equipped', () => {
- equip(user, {params: {key: 'weapon_warrior_1'}});
+ equip(user, { params: { key: 'weapon_warrior_1' } });
// one-handed to one-handed
- let [, message] = equip(user, {params: {key: 'weapon_warrior_2'}});
+ let [, message] = equip(user, { params: { key: 'weapon_warrior_2' } });
expect(message).to.not.exist;
// one-handed to two-handed
- [, message] = equip(user, {params: {key: 'weapon_wizard_1'}});
+ [, message] = equip(user, { params: { key: 'weapon_wizard_1' } });
expect(message).to.not.exist;
// two-handed to two-handed
- [, message] = equip(user, {params: {key: 'weapon_wizard_2'}});
+ [, message] = equip(user, { params: { key: 'weapon_wizard_2' } });
expect(message).to.not.exist;
// two-handed to one-handed
- [, message] = equip(user, {params: {key: 'weapon_warrior_2'}});
+ [, message] = equip(user, { params: { key: 'weapon_warrior_2' } });
expect(message).to.not.exist;
});
it('should send messages if equipping a two-hander causes the off-hander to be unequipped', () => {
- equip(user, {params: {key: 'weapon_warrior_1'}});
- equip(user, {params: {key: 'shield_warrior_1'}});
+ equip(user, { params: { key: 'weapon_warrior_1' } });
+ equip(user, { params: { key: 'shield_warrior_1' } });
// equipping two-hander
- let [data, message] = equip(user, {params: {key: 'weapon_wizard_1'}});
- let weapon = content.gear.flat.weapon_wizard_1;
- let item = content.gear.flat.shield_warrior_1;
+ const [data, message] = equip(user, { params: { key: 'weapon_wizard_1' } });
+ const weapon = content.gear.flat.weapon_wizard_1;
+ const item = content.gear.flat.shield_warrior_1;
- let res = {data, message};
+ const res = { data, message };
expect(res).to.eql({
- message: i18n.t('messageTwoHandedEquip', {twoHandedText: weapon.text(), offHandedText: item.text()}),
+ message: i18n.t('messageTwoHandedEquip', { twoHandedText: weapon.text(), offHandedText: item.text() }),
data: user.items,
});
});
it('should send messages if equipping an off-hand item causes a two-handed weapon to be unequipped', () => {
// equipping two-hander
- equip(user, {params: {key: 'weapon_wizard_1'}});
- let weapon = content.gear.flat.weapon_wizard_1;
- let shield = content.gear.flat.shield_warrior_1;
+ equip(user, { params: { key: 'weapon_wizard_1' } });
+ const weapon = content.gear.flat.weapon_wizard_1;
+ const shield = content.gear.flat.shield_warrior_1;
- let [data, message] = equip(user, {params: {key: 'shield_warrior_1'}});
+ const [data, message] = equip(user, { params: { key: 'shield_warrior_1' } });
- let res = {data, message};
+ const res = { data, message };
expect(res).to.eql({
- message: i18n.t('messageTwoHandedUnequip', {twoHandedText: weapon.text(), offHandedText: shield.text()}),
+ message: i18n.t('messageTwoHandedUnequip', { twoHandedText: weapon.text(), offHandedText: shield.text() }),
data: user.items,
});
});
diff --git a/test/common/ops/feed.js b/test/common/ops/feed.js
index 241fe0fbbc..b00e9bdcd7 100644
--- a/test/common/ops/feed.js
+++ b/test/common/ops/feed.js
@@ -19,7 +19,7 @@ describe('shared.ops.feed', () => {
});
context('failure conditions', () => {
- it('does not allow feeding without specifying pet and food', (done) => {
+ it('does not allow feeding without specifying pet and food', done => {
try {
feed(user);
} catch (err) {
@@ -29,9 +29,9 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding if pet name format is invalid', (done) => {
+ it('does not allow feeding if pet name format is invalid', done => {
try {
- feed(user, {params: {pet: 'invalid', food: 'food'}});
+ feed(user, { params: { pet: 'invalid', food: 'food' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(errorMessage('invalidPetName'));
@@ -39,9 +39,9 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding if food does not exist', (done) => {
+ it('does not allow feeding if food does not exist', done => {
try {
- feed(user, {params: {pet: 'Wolf-Red', food: 'invalid food name'}});
+ feed(user, { params: { pet: 'Wolf-Red', food: 'invalid food name' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(errorMessage('invalidFoodName'));
@@ -49,9 +49,9 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding if pet is not owned', (done) => {
+ it('does not allow feeding if pet is not owned', done => {
try {
- feed(user, {params: {pet: 'Wolf-Red', food: 'Meat'}});
+ feed(user, { params: { pet: 'Wolf-Red', food: 'Meat' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('messagePetNotFound'));
@@ -59,10 +59,10 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding if food is not owned', (done) => {
+ it('does not allow feeding if food is not owned', done => {
user.items.pets['Wolf-Base'] = 5;
try {
- feed(user, {params: {pet: 'Wolf-Base', food: 'Meat'}});
+ feed(user, { params: { pet: 'Wolf-Base', food: 'Meat' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('messageFoodNotFound'));
@@ -70,11 +70,11 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding of special pets', (done) => {
+ it('does not allow feeding of special pets', done => {
user.items.pets['Wolf-Veteran'] = 5;
user.items.food.Meat = 1;
try {
- feed(user, {params: {pet: 'Wolf-Veteran', food: 'Meat'}});
+ feed(user, { params: { pet: 'Wolf-Veteran', food: 'Meat' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageCannotFeedPet'));
@@ -82,12 +82,12 @@ describe('shared.ops.feed', () => {
}
});
- it('does not allow feeding of mounts', (done) => {
+ it('does not allow feeding of mounts', done => {
user.items.pets['Wolf-Base'] = -1;
user.items.mounts['Wolf-Base'] = true;
user.items.food.Meat = 1;
try {
- feed(user, {params: {pet: 'Wolf-Base', food: 'Meat'}});
+ feed(user, { params: { pet: 'Wolf-Base', food: 'Meat' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageAlreadyMount'));
@@ -101,9 +101,9 @@ describe('shared.ops.feed', () => {
user.items.pets['Wolf-Base'] = 5;
user.items.food.Saddle = 2;
user.items.currentPet = 'Wolf-Base';
- let pet = content.petInfo['Wolf-Base'];
+ const pet = content.petInfo['Wolf-Base'];
- let [data, message] = feed(user, {params: {pet: 'Wolf-Base', food: 'Saddle'}});
+ const [data, message] = feed(user, { params: { pet: 'Wolf-Base', food: 'Saddle' } });
expect(data).to.eql(user.items.pets['Wolf-Base']);
expect(message).to.eql(i18n.t('messageEvolve', {
egg: pet.text(),
@@ -119,10 +119,10 @@ describe('shared.ops.feed', () => {
user.items.pets['Wolf-Base'] = 5;
user.items.food.Meat = 2;
- let food = content.food.Meat;
- let pet = content.petInfo['Wolf-Base'];
+ const food = content.food.Meat;
+ const pet = content.petInfo['Wolf-Base'];
- let [data, message] = feed(user, {params: {pet: 'Wolf-Base', food: 'Meat'}});
+ const [data, message] = feed(user, { params: { pet: 'Wolf-Base', food: 'Meat' } });
expect(data).to.eql(user.items.pets['Wolf-Base']);
expect(message).to.eql(i18n.t('messageLikesFood', {
egg: pet.text(),
@@ -137,10 +137,10 @@ describe('shared.ops.feed', () => {
user.items.pets['Wolf-Spooky'] = 5;
user.items.food.Milk = 2;
- let food = content.food.Milk;
- let pet = content.petInfo['Wolf-Spooky'];
+ const food = content.food.Milk;
+ const pet = content.petInfo['Wolf-Spooky'];
- let [data, message] = feed(user, {params: {pet: 'Wolf-Spooky', food: 'Milk'}});
+ const [data, message] = feed(user, { params: { pet: 'Wolf-Spooky', food: 'Milk' } });
expect(data).to.eql(user.items.pets['Wolf-Spooky']);
expect(message).to.eql(i18n.t('messageLikesFood', {
egg: pet.text(),
@@ -155,10 +155,10 @@ describe('shared.ops.feed', () => {
user.items.pets['Wolf-Base'] = 5;
user.items.food.Milk = 2;
- let food = content.food.Milk;
- let pet = content.petInfo['Wolf-Base'];
+ const food = content.food.Milk;
+ const pet = content.petInfo['Wolf-Base'];
- let [data, message] = feed(user, {params: {pet: 'Wolf-Base', food: 'Milk'}});
+ const [data, message] = feed(user, { params: { pet: 'Wolf-Base', food: 'Milk' } });
expect(data).to.eql(user.items.pets['Wolf-Base']);
expect(message).to.eql(i18n.t('messageDontEnjoyFood', {
egg: pet.text(),
@@ -183,7 +183,7 @@ describe('shared.ops.feed', () => {
'Cactus-Base': true,
'BearCub-Base': true,
};
- feed(user, {params: {pet: 'Wolf-Spooky', food: 'Milk'}});
+ feed(user, { params: { pet: 'Wolf-Spooky', food: 'Milk' } });
expect(user.achievements.allYourBase).to.eql(true);
});
@@ -201,7 +201,7 @@ describe('shared.ops.feed', () => {
'Cactus-Desert': true,
'BearCub-Desert': true,
};
- feed(user, {params: {pet: 'Wolf-Spooky', food: 'Milk'}});
+ feed(user, { params: { pet: 'Wolf-Spooky', food: 'Milk' } });
expect(user.achievements.aridAuthority).to.eql(true);
});
@@ -210,9 +210,9 @@ describe('shared.ops.feed', () => {
user.items.food.Milk = 2;
user.items.currentPet = 'Wolf-Base';
- let pet = content.petInfo['Wolf-Base'];
+ const pet = content.petInfo['Wolf-Base'];
- let [data, message] = feed(user, {params: {pet: 'Wolf-Base', food: 'Milk'}});
+ const [data, message] = feed(user, { params: { pet: 'Wolf-Base', food: 'Milk' } });
expect(data).to.eql(user.items.pets['Wolf-Base']);
expect(message).to.eql(i18n.t('messageEvolve', {
egg: pet.text(),
diff --git a/test/common/ops/hatch.js b/test/common/ops/hatch.js
index b1459ba9d9..ba57f7e194 100644
--- a/test/common/ops/hatch.js
+++ b/test/common/ops/hatch.js
@@ -30,12 +30,12 @@ describe('shared.ops.hatch', () => {
}
});
- it('does not allow hatching if user lacks specified egg', (done) => {
+ it('does not allow hatching if user lacks specified egg', done => {
user.items.eggs.Wolf = 1;
user.items.hatchingPotions.Base = 1;
user.items.pets = {};
try {
- hatch(user, {params: {egg: 'Dragon', hatchingPotion: 'Base'}});
+ hatch(user, { params: { egg: 'Dragon', hatchingPotion: 'Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('messageMissingEggPotion'));
@@ -46,12 +46,12 @@ describe('shared.ops.hatch', () => {
}
});
- it('does not allow hatching if user lacks specified hatching potion', (done) => {
+ it('does not allow hatching if user lacks specified hatching potion', done => {
user.items.eggs.Wolf = 1;
user.items.hatchingPotions.Base = 1;
user.items.pets = {};
try {
- hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Golden'}});
+ hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Golden' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
expect(err.message).to.equal(i18n.t('messageMissingEggPotion'));
@@ -62,50 +62,50 @@ describe('shared.ops.hatch', () => {
}
});
- it('does not allow hatching if user already owns target pet', (done) => {
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Base: 1};
- user.items.pets = {'Wolf-Base': 10};
+ it('does not allow hatching if user already owns target pet', done => {
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Base: 1 };
+ user.items.pets = { 'Wolf-Base': 10 };
try {
- hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Base'}});
+ hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Base' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('messageAlreadyPet'));
- expect(user.items.pets).to.eql({'Wolf-Base': 10});
- expect(user.items.eggs).to.eql({Wolf: 1});
- expect(user.items.hatchingPotions).to.eql({Base: 1});
+ expect(user.items.pets).to.eql({ 'Wolf-Base': 10 });
+ expect(user.items.eggs).to.eql({ Wolf: 1 });
+ expect(user.items.hatchingPotions).to.eql({ Base: 1 });
done();
}
});
- it('does not allow hatching quest pet egg using premium potion', (done) => {
- user.items.eggs = {Cheetah: 1};
- user.items.hatchingPotions = {Spooky: 1};
+ it('does not allow hatching quest pet egg using premium potion', done => {
+ user.items.eggs = { Cheetah: 1 };
+ user.items.hatchingPotions = { Spooky: 1 };
user.items.pets = {};
try {
- hatch(user, {params: {egg: 'Cheetah', hatchingPotion: 'Spooky'}});
+ hatch(user, { params: { egg: 'Cheetah', hatchingPotion: 'Spooky' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('messageInvalidEggPotionCombo'));
expect(user.items.pets).to.be.empty;
- expect(user.items.eggs).to.eql({Cheetah: 1});
- expect(user.items.hatchingPotions).to.eql({Spooky: 1});
+ expect(user.items.eggs).to.eql({ Cheetah: 1 });
+ expect(user.items.hatchingPotions).to.eql({ Spooky: 1 });
done();
}
});
- it('does not allow hatching quest pet egg using wacky potion', (done) => {
- user.items.eggs = {Bunny: 1};
- user.items.hatchingPotions = {Veggie: 1};
+ it('does not allow hatching quest pet egg using wacky potion', done => {
+ user.items.eggs = { Bunny: 1 };
+ user.items.hatchingPotions = { Veggie: 1 };
user.items.pets = {};
try {
- hatch(user, {params: {egg: 'Bunny', hatchingPotion: 'Veggie'}});
+ hatch(user, { params: { egg: 'Bunny', hatchingPotion: 'Veggie' } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('messageInvalidEggPotionCombo'));
expect(user.items.pets).to.be.empty;
- expect(user.items.eggs).to.eql({Bunny: 1});
- expect(user.items.hatchingPotions).to.eql({Veggie: 1});
+ expect(user.items.eggs).to.eql({ Bunny: 1 });
+ expect(user.items.hatchingPotions).to.eql({ Veggie: 1 });
done();
}
});
@@ -113,51 +113,51 @@ describe('shared.ops.hatch', () => {
context('successful hatching', () => {
it('hatches a basic pet', () => {
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Base: 1};
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Base: 1 };
user.items.pets = {};
- let [data, message] = hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Base'}});
+ const [data, message] = hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Base' } });
expect(message).to.equal(i18n.t('messageHatched'));
expect(data).to.eql(user.items);
- expect(user.items.pets).to.eql({'Wolf-Base': 5});
- expect(user.items.eggs).to.eql({Wolf: 0});
- expect(user.items.hatchingPotions).to.eql({Base: 0});
+ expect(user.items.pets).to.eql({ 'Wolf-Base': 5 });
+ expect(user.items.eggs).to.eql({ Wolf: 0 });
+ expect(user.items.hatchingPotions).to.eql({ Base: 0 });
});
it('hatches a quest pet', () => {
- user.items.eggs = {Cheetah: 1};
- user.items.hatchingPotions = {Base: 1};
+ user.items.eggs = { Cheetah: 1 };
+ user.items.hatchingPotions = { Base: 1 };
user.items.pets = {};
- let [data, message] = hatch(user, {params: {egg: 'Cheetah', hatchingPotion: 'Base'}});
+ const [data, message] = hatch(user, { params: { egg: 'Cheetah', hatchingPotion: 'Base' } });
expect(message).to.equal(i18n.t('messageHatched'));
expect(data).to.eql(user.items);
- expect(user.items.pets).to.eql({'Cheetah-Base': 5});
- expect(user.items.eggs).to.eql({Cheetah: 0});
- expect(user.items.hatchingPotions).to.eql({Base: 0});
+ expect(user.items.pets).to.eql({ 'Cheetah-Base': 5 });
+ expect(user.items.eggs).to.eql({ Cheetah: 0 });
+ expect(user.items.hatchingPotions).to.eql({ Base: 0 });
});
it('hatches a premium pet', () => {
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Spooky: 1};
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Spooky: 1 };
user.items.pets = {};
- let [data, message] = hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Spooky'}});
+ const [data, message] = hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Spooky' } });
expect(message).to.equal(i18n.t('messageHatched'));
expect(data).to.eql(user.items);
- expect(user.items.pets).to.eql({'Wolf-Spooky': 5});
- expect(user.items.eggs).to.eql({Wolf: 0});
- expect(user.items.hatchingPotions).to.eql({Spooky: 0});
+ expect(user.items.pets).to.eql({ 'Wolf-Spooky': 5 });
+ expect(user.items.eggs).to.eql({ Wolf: 0 });
+ expect(user.items.hatchingPotions).to.eql({ Spooky: 0 });
});
it('hatches a pet previously raised to a mount', () => {
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Base: 1};
- user.items.pets = {'Wolf-Base': -1};
- let [data, message] = hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Base'}});
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Base: 1 };
+ user.items.pets = { 'Wolf-Base': -1 };
+ const [data, message] = hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Base' } });
expect(message).to.eql(i18n.t('messageHatched'));
expect(data).to.eql(user.items);
- expect(user.items.pets).to.eql({'Wolf-Base': 5});
- expect(user.items.eggs).to.eql({Wolf: 0});
- expect(user.items.hatchingPotions).to.eql({Base: 0});
+ expect(user.items.pets).to.eql({ 'Wolf-Base': 5 });
+ expect(user.items.eggs).to.eql({ Wolf: 0 });
+ expect(user.items.hatchingPotions).to.eql({ Base: 0 });
});
it('awards Back to Basics achievement', () => {
@@ -172,9 +172,9 @@ describe('shared.ops.hatch', () => {
'Cactus-Base': 15,
'BearCub-Base': 5,
};
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Spooky: 1};
- hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Spooky'}});
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Spooky: 1 };
+ hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Spooky' } });
expect(user.achievements.backToBasics).to.eql(true);
});
@@ -190,9 +190,9 @@ describe('shared.ops.hatch', () => {
'Cactus-Desert': 15,
'BearCub-Desert': 5,
};
- user.items.eggs = {Wolf: 1};
- user.items.hatchingPotions = {Spooky: 1};
- hatch(user, {params: {egg: 'Wolf', hatchingPotion: 'Spooky'}});
+ user.items.eggs = { Wolf: 1 };
+ user.items.hatchingPotions = { Spooky: 1 };
+ hatch(user, { params: { egg: 'Wolf', hatchingPotion: 'Spooky' } });
expect(user.achievements.dustDevil).to.eql(true);
});
});
diff --git a/test/common/ops/openMysteryItem.js b/test/common/ops/openMysteryItem.js
index e828129457..511c2e52b8 100644
--- a/test/common/ops/openMysteryItem.js
+++ b/test/common/ops/openMysteryItem.js
@@ -15,7 +15,7 @@ describe('shared.ops.openMysteryItem', () => {
user = generateUser();
});
- it('returns error when item key is empty', (done) => {
+ it('returns error when item key is empty', done => {
try {
openMysteryItem(user);
} catch (err) {
@@ -26,17 +26,17 @@ describe('shared.ops.openMysteryItem', () => {
});
it('opens mystery item', () => {
- let mysteryItemKey = 'eyewear_special_summerRogue';
+ const mysteryItemKey = 'eyewear_special_summerRogue';
user.purchased.plan.mysteryItems = [mysteryItemKey];
- user.notifications.push({type: 'NEW_MYSTERY_ITEMS', data: {items: [mysteryItemKey]}});
+ user.notifications.push({ type: 'NEW_MYSTERY_ITEMS', data: { items: [mysteryItemKey] } });
expect(user.notifications.length).to.equal(1);
- let [data, message] = openMysteryItem(user);
+ const [data, message] = openMysteryItem(user);
expect(user.items.gear.owned[mysteryItemKey]).to.be.true;
expect(message).to.equal(i18n.t('mysteryItemOpened'));
- let item = _.cloneDeep(content.gear.flat[mysteryItemKey]);
+ const item = _.cloneDeep(content.gear.flat[mysteryItemKey]);
item.text = content.gear.flat[mysteryItemKey].text();
expect(data).to.eql(item);
expect(user.notifications.length).to.equal(0);
diff --git a/test/common/ops/pinnedGearUtils.js b/test/common/ops/pinnedGearUtils.js
index e45e60a729..b6ea4e0758 100644
--- a/test/common/ops/pinnedGearUtils.js
+++ b/test/common/ops/pinnedGearUtils.js
@@ -1,7 +1,7 @@
import {
generateUser,
} from '../../helpers/common.helper';
-import {addPinnedGear} from '../../../website/common/script/ops/pinnedGearUtils';
+import { addPinnedGear } from '../../../website/common/script/ops/pinnedGearUtils';
describe('shared.ops.pinnedGearUtils.addPinnedGear', () => {
let user;
diff --git a/test/common/ops/readCard.js b/test/common/ops/readCard.js
index d6d249e1f4..261708c2cb 100644
--- a/test/common/ops/readCard.js
+++ b/test/common/ops/readCard.js
@@ -10,7 +10,7 @@ import {
describe('shared.ops.readCard', () => {
let user;
- let cardType = 'greeting';
+ const cardType = 'greeting';
beforeEach(() => {
user = generateUser();
@@ -18,7 +18,7 @@ describe('shared.ops.readCard', () => {
user.flags.cardReceived = true;
});
- it('returns an error when cardType is not provided', (done) => {
+ it('returns an error when cardType is not provided', done => {
try {
readCard(user);
} catch (err) {
@@ -28,9 +28,9 @@ describe('shared.ops.readCard', () => {
}
});
- it('returns an error when unknown cardType is provided', (done) => {
+ it('returns an error when unknown cardType is provided', done => {
try {
- readCard(user, {params: {cardType: 'randomCardType'}});
+ readCard(user, { params: { cardType: 'randomCardType' } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('cardTypeNotAllowed'));
@@ -41,13 +41,13 @@ describe('shared.ops.readCard', () => {
it('reads a card', () => {
user.notifications.push({
type: 'CARD_RECEIVED',
- data: {card: cardType},
+ data: { card: cardType },
});
const initialNotificationNuber = user.notifications.length;
- let [, message] = readCard(user, {params: {cardType: 'greeting'}});
+ const [, message] = readCard(user, { params: { cardType: 'greeting' } });
- expect(message).to.equal(i18n.t('readCard', {cardType}));
+ expect(message).to.equal(i18n.t('readCard', { cardType }));
expect(user.items.special[`${cardType}Received`]).to.be.empty;
expect(user.flags.cardReceived).to.be.false;
expect(user.notifications.length).to.equal(initialNotificationNuber - 1);
diff --git a/test/common/ops/rebirth.js b/test/common/ops/rebirth.js
index 65014e3cb4..0cc9218daa 100644
--- a/test/common/ops/rebirth.js
+++ b/test/common/ops/rebirth.js
@@ -14,8 +14,8 @@ import {
describe('shared.ops.rebirth', () => {
let user;
- let animal = 'Wolf-Base';
- let userStats = ['per', 'int', 'con', 'str', 'points', 'gp', 'exp', 'mp'];
+ const animal = 'Wolf-Base';
+ const userStats = ['per', 'int', 'con', 'str', 'points', 'gp', 'exp', 'mp'];
let tasks = [];
beforeEach(() => {
@@ -24,7 +24,7 @@ describe('shared.ops.rebirth', () => {
tasks = [generateHabit(), generateDaily(), generateTodo(), generateReward()];
});
- it('returns an error when user balance is too low and user is less than max level', (done) => {
+ it('returns an error when user balance is too low and user is less than max level', done => {
user.balance = 0;
try {
@@ -37,7 +37,7 @@ describe('shared.ops.rebirth', () => {
});
it('rebirths a user with enough gems', () => {
- let [, message] = rebirth(user);
+ const [, message] = rebirth(user);
expect(message).to.equal(i18n.t('rebirthComplete'));
});
@@ -46,7 +46,7 @@ describe('shared.ops.rebirth', () => {
user.balance = 0;
user.stats.lvl = MAX_LEVEL;
- let [, message] = rebirth(user);
+ const [, message] = rebirth(user);
expect(message).to.equal(i18n.t('rebirthComplete'));
expect(user.flags.lastFreeRebirth).to.exist;
@@ -56,7 +56,7 @@ describe('shared.ops.rebirth', () => {
user.balance = 0;
user.stats.lvl = MAX_LEVEL + 1;
- let [, message] = rebirth(user);
+ const [, message] = rebirth(user);
expect(message).to.equal(i18n.t('rebirthComplete'));
});
@@ -65,7 +65,7 @@ describe('shared.ops.rebirth', () => {
user.stats.lvl = MAX_LEVEL + 1;
user.flags.lastFreeRebirth = new Date();
- let [, message] = rebirth(user);
+ const [, message] = rebirth(user);
expect(message).to.equal(i18n.t('rebirthComplete'));
expect(user.balance).to.equal(0);
@@ -98,7 +98,7 @@ describe('shared.ops.rebirth', () => {
});
it('resets a user\'s buffs', () => {
- user.stats.buffs = {test: 'test'};
+ user.stats.buffs = { test: 'test' };
rebirth(user);
@@ -123,21 +123,21 @@ describe('shared.ops.rebirth', () => {
it('resets a user\'s stats', () => {
user.stats.class = 'rouge';
- _.each(userStats, function setUsersStats (value) {
+ _.each(userStats, value => {
user.stats[value] = 10;
});
rebirth(user);
- _.each(userStats, function resetUserStats (value) {
+ _.each(userStats, value => {
user.stats[value] = 0;
});
});
it('retains a user\'s gear', () => {
- let prevGearEquipped = user.items.gear.equipped;
- let prevGearCostume = user.items.gear.costume;
- let prevPrefCostume = user.preferences.costume;
+ const prevGearEquipped = user.items.gear.equipped;
+ const prevGearCostume = user.items.gear.costume;
+ const prevPrefCostume = user.preferences.costume;
rebirth(user);
@@ -148,7 +148,7 @@ describe('shared.ops.rebirth', () => {
it('retains a user\'s gear owned', () => {
user.items.gear.owned.weapon_warrior_1 = true; // eslint-disable-line camelcase
- let prevGearOwned = user.items.gear.owned;
+ const prevGearOwned = user.items.gear.owned;
rebirth(user);
@@ -176,7 +176,7 @@ describe('shared.ops.rebirth', () => {
user.flags.dropsEnabled = true;
user.flags.classSelected = true;
user.flags.rebirthEnabled = true;
- user.flags.levelDrops = {test: 'test'};
+ user.flags.levelDrops = { test: 'test' };
rebirth(user);
@@ -228,7 +228,8 @@ describe('shared.ops.rebirth', () => {
it('always increments rebirth achievements when level is MAX_LEVEL', () => {
user.stats.lvl = MAX_LEVEL;
user.achievements.rebirths = 1;
- user.achievements.rebirthLevel = MAX_LEVEL + 1; // this value is not actually possible (actually capped at MAX_LEVEL) but makes a good test
+ // this value is not actually possible (actually capped at MAX_LEVEL) but makes a good test
+ user.achievements.rebirthLevel = MAX_LEVEL + 1;
rebirth(user);
@@ -239,7 +240,8 @@ describe('shared.ops.rebirth', () => {
it('always increments rebirth achievements when level is greater than MAX_LEVEL', () => {
user.stats.lvl = MAX_LEVEL + 1;
user.achievements.rebirths = 1;
- user.achievements.rebirthLevel = MAX_LEVEL + 2; // this value is not actually possible (actually capped at MAX_LEVEL) but makes a good test
+ // this value is not actually possible (actually capped at MAX_LEVEL) but makes a good test
+ user.achievements.rebirthLevel = MAX_LEVEL + 2;
rebirth(user);
diff --git a/test/common/ops/releaseBoth.js b/test/common/ops/releaseBoth.js
index 3d2c910075..006a467b3d 100644
--- a/test/common/ops/releaseBoth.js
+++ b/test/common/ops/releaseBoth.js
@@ -10,19 +10,19 @@ import {
describe('shared.ops.releaseBoth', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
beforeEach(() => {
user = generateUser();
- for (let p in content.pets) {
+ Object.keys(content.pets).forEach(p => {
user.items.pets[p] = content.pets[p];
user.items.pets[p] = 5;
- }
+ });
- for (let m in content.pets) {
+ Object.keys(content.pets).forEach(m => {
user.items.mounts[m] = content.pets[m];
user.items.mounts[m] = true;
- }
+ });
user.items.currentMount = animal;
user.items.currentPet = animal;
@@ -30,7 +30,7 @@ describe('shared.ops.releaseBoth', () => {
user.achievements.triadBingo = true;
});
- xit('returns an error when user balance is too low and user does not have triadBingo', (done) => {
+ xit('returns an error when user balance is too low and user does not have triadBingo', done => {
user.balance = 0;
try {
@@ -42,7 +42,7 @@ describe('shared.ops.releaseBoth', () => {
}
});
- it('returns an error when user does not have all pets', (done) => {
+ it('returns an error when user does not have all pets', done => {
const petKeys = Object.keys(user.items.pets);
delete user.items.pets[petKeys[0]];
@@ -59,7 +59,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('grants triad bingo with gems', () => {
- let message = releaseBoth(user)[1];
+ const message = releaseBoth(user)[1];
expect(message).to.equal(i18n.t('mountsAndPetsReleased'));
expect(user.achievements.triadBingoCount).to.equal(1);
@@ -70,23 +70,23 @@ describe('shared.ops.releaseBoth', () => {
user.achievements.triadBingo = 1;
user.achievements.triadBingoCount = 1;
- let message = releaseBoth(user)[1];
+ const message = releaseBoth(user)[1];
expect(message).to.equal(i18n.t('mountsAndPetsReleased'));
expect(user.achievements.triadBingoCount).to.equal(2);
});
it('does not grant triad bingo if any pet has not been previously found', () => {
- let triadBingoCountBeforeRelease = user.achievements.triadBingoCount;
+ const triadBingoCountBeforeRelease = user.achievements.triadBingoCount;
user.items.pets[animal] = -1;
- let message = releaseBoth(user)[1];
+ const message = releaseBoth(user)[1];
expect(message).to.equal(i18n.t('mountsAndPetsReleased'));
expect(user.achievements.triadBingoCount).to.equal(triadBingoCountBeforeRelease);
});
it('releases pets', () => {
- let message = releaseBoth(user)[1];
+ const message = releaseBoth(user)[1];
expect(message).to.equal(i18n.t('mountsAndPetsReleased'));
expect(user.items.pets[animal]).to.equal(0);
@@ -94,7 +94,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('does not increment beastMasterCount if any pet is level 0 (released)', () => {
- let beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
+ const beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
user.items.pets[animal] = 0;
try {
releaseBoth(user);
@@ -104,7 +104,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('does not increment beastMasterCount if any pet is missing (null)', () => {
- let beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
+ const beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
user.items.pets[animal] = null;
try {
@@ -115,7 +115,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('does not increment beastMasterCount if any pet is missing (undefined)', () => {
- let beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
+ const beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
delete user.items.pets[animal];
try {
@@ -126,14 +126,14 @@ describe('shared.ops.releaseBoth', () => {
});
it('releases mounts', () => {
- let message = releaseBoth(user)[1];
+ const message = releaseBoth(user)[1];
expect(message).to.equal(i18n.t('mountsAndPetsReleased'));
expect(user.items.mounts[animal]).to.equal(null);
});
it('does not increase mountMasterCount achievement if mount is missing (null)', () => {
- let mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
+ const mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
user.items.mounts[animal] = null;
try {
@@ -144,7 +144,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('does not increase mountMasterCount achievement if mount is missing (undefined)', () => {
- let mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
+ const mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
delete user.items.mounts[animal];
try {
@@ -155,7 +155,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('removes drop currentPet', () => {
- let petInfo = content.petInfo[user.items.currentPet];
+ const petInfo = content.petInfo[user.items.currentPet];
expect(petInfo.type).to.equal('drop');
releaseBoth(user);
@@ -164,7 +164,7 @@ describe('shared.ops.releaseBoth', () => {
});
it('removes drop currentMount', () => {
- let mountInfo = content.mountInfo[user.items.currentMount];
+ const mountInfo = content.mountInfo[user.items.currentMount];
expect(mountInfo.type).to.equal('drop');
releaseBoth(user);
@@ -172,15 +172,15 @@ describe('shared.ops.releaseBoth', () => {
});
it('leaves non-drop pets and mounts equipped', () => {
- let questAnimal = 'Gryphon-Base';
+ const questAnimal = 'Gryphon-Base';
user.items.currentMount = questAnimal;
user.items.currentPet = questAnimal;
user.items.pets[questAnimal] = 5;
user.items.mounts[questAnimal] = true;
- let petInfo = content.petInfo[user.items.currentPet];
+ const petInfo = content.petInfo[user.items.currentPet];
expect(petInfo.type).to.not.equal('drop');
- let mountInfo = content.mountInfo[user.items.currentMount];
+ const mountInfo = content.mountInfo[user.items.currentMount];
expect(mountInfo.type).to.not.equal('drop');
releaseBoth(user);
diff --git a/test/common/ops/releaseMounts.js b/test/common/ops/releaseMounts.js
index 816d5f035d..10ec71f23b 100644
--- a/test/common/ops/releaseMounts.js
+++ b/test/common/ops/releaseMounts.js
@@ -10,20 +10,20 @@ import {
describe('shared.ops.releaseMounts', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
beforeEach(() => {
user = generateUser();
- for (let k in content.pets) {
+ Object.keys(content.pets).forEach(k => {
user.items.mounts[k] = content.pets[k];
user.items.mounts[k] = true;
- }
+ });
user.items.currentMount = animal;
user.balance = 1;
});
- it('returns an error when user balance is too low', (done) => {
+ it('returns an error when user balance is too low', done => {
user.balance = 0;
try {
@@ -35,7 +35,7 @@ describe('shared.ops.releaseMounts', () => {
}
});
- it('returns an error when user does not have all pets', (done) => {
+ it('returns an error when user does not have all pets', done => {
const mountsKeys = Object.keys(user.items.mounts);
delete user.items.mounts[mountsKeys[0]];
@@ -49,14 +49,14 @@ describe('shared.ops.releaseMounts', () => {
});
it('releases mounts', () => {
- let message = releaseMounts(user)[1];
+ const message = releaseMounts(user)[1];
expect(message).to.equal(i18n.t('mountsReleased'));
expect(user.items.mounts[animal]).to.equal(null);
});
it('removes drop currentMount', () => {
- let mountInfo = content.mountInfo[user.items.currentMount];
+ const mountInfo = content.mountInfo[user.items.currentMount];
expect(mountInfo.type).to.equal('drop');
releaseMounts(user);
@@ -64,11 +64,11 @@ describe('shared.ops.releaseMounts', () => {
});
it('leaves non-drop mount equipped', () => {
- let questAnimal = 'Gryphon-Base';
+ const questAnimal = 'Gryphon-Base';
user.items.currentMount = questAnimal;
user.items.mounts[questAnimal] = true;
- let mountInfo = content.mountInfo[user.items.currentMount];
+ const mountInfo = content.mountInfo[user.items.currentMount];
expect(mountInfo.type).to.not.equal('drop');
releaseMounts(user);
@@ -81,7 +81,7 @@ describe('shared.ops.releaseMounts', () => {
});
it('does not increase mountMasterCount achievement if mount is missing (null)', () => {
- let mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
+ const mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
user.items.mounts[animal] = null;
try {
@@ -92,7 +92,7 @@ describe('shared.ops.releaseMounts', () => {
});
it('does not increase mountMasterCount achievement if mount is missing (undefined)', () => {
- let mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
+ const mountMasterCountBeforeRelease = user.achievements.mountMasterCount;
delete user.items.mounts[animal];
try {
diff --git a/test/common/ops/releasePets.js b/test/common/ops/releasePets.js
index 97089607d3..a333fc41ab 100644
--- a/test/common/ops/releasePets.js
+++ b/test/common/ops/releasePets.js
@@ -10,20 +10,20 @@ import {
describe('shared.ops.releasePets', () => {
let user;
- let animal = 'Wolf-Base';
+ const animal = 'Wolf-Base';
beforeEach(() => {
user = generateUser();
- for (let k in content.pets) {
+ Object.keys(content.pets).forEach(k => {
user.items.pets[k] = content.pets[k];
user.items.pets[k] = 5;
- }
+ });
user.items.currentPet = animal;
user.balance = 1;
});
- it('returns an error when user balance is too low', (done) => {
+ it('returns an error when user balance is too low', done => {
user.balance = 0;
try {
@@ -35,7 +35,7 @@ describe('shared.ops.releasePets', () => {
}
});
- it('returns an error when user does not have all pets', (done) => {
+ it('returns an error when user does not have all pets', done => {
const petKeys = Object.keys(user.items.pets);
delete user.items.pets[petKeys[0]];
@@ -49,14 +49,14 @@ describe('shared.ops.releasePets', () => {
});
it('releases pets', () => {
- let message = releasePets(user)[1];
+ const message = releasePets(user)[1];
expect(message).to.equal(i18n.t('petsReleased'));
expect(user.items.pets[animal]).to.equal(0);
});
it('removes drop currentPet', () => {
- let petInfo = content.petInfo[user.items.currentPet];
+ const petInfo = content.petInfo[user.items.currentPet];
expect(petInfo.type).to.equal('drop');
releasePets(user);
@@ -64,11 +64,11 @@ describe('shared.ops.releasePets', () => {
});
it('leaves non-drop pets equipped', () => {
- let questAnimal = 'Gryphon-Base';
+ const questAnimal = 'Gryphon-Base';
user.items.currentPet = questAnimal;
user.items.pets[questAnimal] = 5;
- let petInfo = content.petInfo[user.items.currentPet];
+ const petInfo = content.petInfo[user.items.currentPet];
expect(petInfo.type).to.not.equal('drop');
releasePets(user);
@@ -99,7 +99,7 @@ describe('shared.ops.releasePets', () => {
});
it('does not increment beastMasterCount if any pet is missing (null)', () => {
- let beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
+ const beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
user.items.pets[animal] = null;
try {
@@ -110,7 +110,7 @@ describe('shared.ops.releasePets', () => {
});
it('does not increment beastMasterCount if any pet is missing (undefined)', () => {
- let beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
+ const beastMasterCountBeforeRelease = user.achievements.beastMasterCount;
delete user.items.pets[animal];
try {
diff --git a/test/common/ops/reroll.js b/test/common/ops/reroll.js
index 8cf7123d11..15020c8aa4 100644
--- a/test/common/ops/reroll.js
+++ b/test/common/ops/reroll.js
@@ -19,7 +19,7 @@ describe('shared.ops.reroll', () => {
tasks = [generateDaily(), generateReward()];
});
- it('returns an error when user balance is too low', (done) => {
+ it('returns an error when user balance is too low', done => {
user.balance = 0;
try {
@@ -32,7 +32,7 @@ describe('shared.ops.reroll', () => {
});
it('rerolls a user with enough gems', () => {
- let [, message] = reroll(user);
+ const [, message] = reroll(user);
expect(message).to.equal(i18n.t('fortifyComplete'));
});
diff --git a/test/common/ops/reset.js b/test/common/ops/reset.js
index 17dea701c2..7ba6c117c4 100644
--- a/test/common/ops/reset.js
+++ b/test/common/ops/reset.js
@@ -16,10 +16,10 @@ describe('shared.ops.reset', () => {
user = generateUser();
user.balance = 2;
- let habit = generateHabit();
- let todo = generateTodo();
- let daily = generateDaily();
- let reward = generateReward();
+ const habit = generateHabit();
+ const todo = generateTodo();
+ const daily = generateDaily();
+ const reward = generateReward();
user.tasksOrder.habits = [habit._id];
user.tasksOrder.todos = [todo._id];
@@ -31,7 +31,7 @@ describe('shared.ops.reset', () => {
it('resets a user', () => {
- let [, message] = reset(user);
+ const [, message] = reset(user);
expect(message).to.equal(i18n.t('resetComplete'));
});
diff --git a/test/common/ops/revive.js b/test/common/ops/revive.js
index b4e0ce2846..5000687076 100644
--- a/test/common/ops/revive.js
+++ b/test/common/ops/revive.js
@@ -18,7 +18,7 @@ describe('shared.ops.revive', () => {
user.stats.hp = 0;
});
- it('returns an error when user is not dead', (done) => {
+ it('returns an error when user is not dead', done => {
user.stats.hp = 10;
try {
@@ -56,28 +56,26 @@ describe('shared.ops.revive', () => {
});
it('it decreases a random stat from str, con, per, int by one', () => {
- let stats = ['str', 'con', 'per', 'int'];
+ const stats = ['str', 'con', 'per', 'int'];
- _.each(stats, (s) => {
+ _.each(stats, s => {
user.stats[s] = 1;
});
revive(user);
- let statSum = _.reduce(stats, (m, k) => {
- return m + user.stats[k];
- }, 0);
+ const statSum = _.reduce(stats, (m, k) => m + user.stats[k], 0);
expect(statSum).to.equal(3);
});
it('removes a random item from user gear owned', () => {
- let weaponKey = 'weapon_warrior_0';
+ const weaponKey = 'weapon_warrior_0';
user.items.gear.owned[weaponKey] = true;
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text() }));
expect(user.items.gear.owned[weaponKey]).to.be.false;
});
@@ -96,67 +94,67 @@ describe('shared.ops.revive', () => {
weapon_warrior_0: true,
};
- let weaponKey = 'weapon_warrior_0';
+ const weaponKey = 'weapon_warrior_0';
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text() }));
expect(user.items.gear.owned[weaponKey]).to.be.false;
});
it('does not remove items of a different class', () => {
- let weaponKey = 'weapon_wizard_1';
+ const weaponKey = 'weapon_wizard_1';
user.items.gear.owned[weaponKey] = true;
- let [, message] = revive(user);
+ const [, message] = revive(user);
expect(message).to.equal('');
expect(user.items.gear.owned[weaponKey]).to.be.true;
});
it('removes "special" items', () => {
- let weaponKey = 'weapon_special_1';
+ const weaponKey = 'weapon_special_1';
user.items.gear.owned[weaponKey] = true;
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text() }));
expect(user.items.gear.owned[weaponKey]).to.be.false;
});
it('removes "armoire" items', () => {
- let weaponKey = 'armor_armoire_goldenToga';
+ const weaponKey = 'armor_armoire_goldenToga';
user.items.gear.owned[weaponKey] = true;
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: content.gear.flat[weaponKey].text() }));
expect(user.items.gear.owned[weaponKey]).to.be.false;
});
it('dequips lost item from user if user had it equipped', () => {
- let weaponKey = 'weapon_warrior_0';
- let itemToLose = content.gear.flat[weaponKey];
+ const weaponKey = 'weapon_warrior_0';
+ const itemToLose = content.gear.flat[weaponKey];
user.items.gear.owned[weaponKey] = true;
user.items.gear.equipped[itemToLose.type] = itemToLose.key;
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: itemToLose.text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: itemToLose.text() }));
expect(user.items.gear.equipped[itemToLose.type]).to.equal(`${itemToLose.type}_base_0`);
});
it('dequips lost item from user costume if user was using it in costume', () => {
- let weaponKey = 'weapon_warrior_0';
- let itemToLose = content.gear.flat[weaponKey];
+ const weaponKey = 'weapon_warrior_0';
+ const itemToLose = content.gear.flat[weaponKey];
user.items.gear.owned[weaponKey] = true;
user.items.gear.costume[itemToLose.type] = itemToLose.key;
- let [, message] = revive(user);
+ const [, message] = revive(user);
- expect(message).to.equal(i18n.t('messageLostItem', { itemText: itemToLose.text()}));
+ expect(message).to.equal(i18n.t('messageLostItem', { itemText: itemToLose.text() }));
expect(user.items.gear.costume[itemToLose.type]).to.equal(`${itemToLose.type}_base_0`);
});
});
diff --git a/test/common/ops/scoreTask.test.js b/test/common/ops/scoreTask.test.js
index c157a929e1..2526a57fc9 100644
--- a/test/common/ops/scoreTask.test.js
+++ b/test/common/ops/scoreTask.test.js
@@ -13,11 +13,11 @@ import {
} from '../../../website/common/script/libs/errors';
import crit from '../../../website/common/script/fns/crit';
-let EPSILON = 0.0001; // negligible distance between datapoints
+const EPSILON = 0.0001; // negligible distance between datapoints
-let beforeAfter = () => {
- let beforeUser = generateUser();
- let afterUser = _.cloneDeep(beforeUser);
+const beforeAfter = () => {
+ const beforeUser = generateUser();
+ const afterUser = _.cloneDeep(beforeUser);
return {
beforeUser,
@@ -25,7 +25,7 @@ let beforeAfter = () => {
};
};
-let expectGainedPoints = (beforeUser, afterUser, beforeTask, afterTask) => {
+const expectGainedPoints = (beforeUser, afterUser, beforeTask, afterTask) => {
expect(afterUser.stats.hp).to.eql(50);
expect(afterUser.stats.exp).to.be.greaterThan(beforeUser.stats.exp);
expect(afterUser.stats.gp).to.be.greaterThan(beforeUser.stats.gp);
@@ -35,15 +35,15 @@ let expectGainedPoints = (beforeUser, afterUser, beforeTask, afterTask) => {
}
};
-let expectClosePoints = (beforeUser, afterUser, beforeTask, task) => {
+const expectClosePoints = (beforeUser, afterUser, beforeTask, task) => {
expect(Math.abs(afterUser.stats.exp - beforeUser.stats.exp)).to.be.lessThan(EPSILON);
expect(Math.abs(afterUser.stats.gp - beforeUser.stats.gp)).to.be.lessThan(EPSILON);
expect(Math.abs(task.value - beforeTask.value)).to.be.lessThan(EPSILON);
};
function expectRoughlyEqualDates (date1, date2) {
- date1 = date1.valueOf();
- date2 = date2.valueOf();
+ date1 = date1.valueOf(); // eslint-disable-line no-param-reassign
+ date2 = date2.valueOf(); // eslint-disable-line no-param-reassign
expect(date1).to.be.within(date2 - 100, date2 + 100);
}
@@ -54,8 +54,8 @@ describe('shared.ops.scoreTask', () => {
ref = beforeAfter();
});
- it('throws an error when scoring a reward if user does not have enough gold', (done) => {
- let reward = generateReward({ userId: ref.afterUser._id, text: 'some reward', value: 100 });
+ it('throws an error when scoring a reward if user does not have enough gold', done => {
+ const reward = generateReward({ userId: ref.afterUser._id, text: 'some reward', value: 100 });
try {
scoreTask({ user: ref.afterUser, task: reward });
} catch (err) {
@@ -66,14 +66,14 @@ describe('shared.ops.scoreTask', () => {
});
it('completes when the task direction is up', () => {
- let task = generateTodo({ userId: ref.afterUser._id, text: 'todo to complete', cron: false });
+ const task = generateTodo({ userId: ref.afterUser._id, text: 'todo to complete', cron: false });
scoreTask({ user: ref.afterUser, task, direction: 'up' });
expect(task.completed).to.eql(true);
expectRoughlyEqualDates(task.dateCompleted, new Date());
});
it('uncompletes when the task direction is down', () => {
- let task = generateTodo({ userId: ref.afterUser._id, text: 'todo to complete', cron: false });
+ const task = generateTodo({ userId: ref.afterUser._id, text: 'todo to complete', cron: false });
scoreTask({ user: ref.afterUser, task, direction: 'down' });
expect(task.completed).to.eql(false);
expect(task.dateCompleted).to.not.exist;
@@ -88,19 +88,23 @@ describe('shared.ops.scoreTask', () => {
});
it('works', () => {
- let delta1, delta2, delta3;
-
- delta1 = scoreTask({ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false });
+ const delta1 = scoreTask({
+ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false,
+ });
ref = beforeAfter();
habit = generateHabit({ userId: ref.afterUser._id, text: 'some habit' });
- delta2 = scoreTask({ user: ref.afterUser, task: habit, direction: 'up', times: 4, cron: false });
+ const delta2 = scoreTask({
+ user: ref.afterUser, task: habit, direction: 'up', times: 4, cron: false,
+ });
ref = beforeAfter();
habit = generateHabit({ userId: ref.afterUser._id, text: 'some habit' });
- delta3 = scoreTask({ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false });
+ const delta3 = scoreTask({
+ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false,
+ });
expect(Math.abs(delta1 - delta2)).to.be.greaterThan(EPSILON);
expect(Math.abs(delta1 - delta3)).to.be.lessThan(EPSILON);
@@ -108,58 +112,62 @@ describe('shared.ops.scoreTask', () => {
});
it('checks that the streak parameters affects the score', () => {
- let task = generateDaily({ userId: ref.afterUser._id, text: 'task to check streak' });
- scoreTask({ user: ref.afterUser, task, direction: 'up', cron: false });
- scoreTask({ user: ref.afterUser, task, direction: 'up', cron: false });
+ const task = generateDaily({ userId: ref.afterUser._id, text: 'task to check streak' });
+ scoreTask({
+ user: ref.afterUser, task, direction: 'up', cron: false,
+ });
+ scoreTask({
+ user: ref.afterUser, task, direction: 'up', cron: false,
+ });
expect(task.streak).to.eql(2);
});
describe('verifies that 21-day streak achievements are given/removed correctly', () => {
- let initialStreakCount = 20; // 1 before the streak achievement is awarded
+ const initialStreakCount = 20; // 1 before the streak achievement is awarded
beforeEach(() => {
ref = beforeAfter();
});
it('awards the first streak achievement', () => {
- let task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: initialStreakCount });
+ const task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task, direction: 'up' });
expect(ref.afterUser.achievements.streak).to.equal(1);
});
it('increments the streak achievement for a second streak', () => {
- let task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
+ const task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task: task1, direction: 'up' });
- let task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: initialStreakCount });
+ const task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task: task2, direction: 'up' });
expect(ref.afterUser.achievements.streak).to.equal(2);
});
it('removes the first streak achievement when unticking a Daily', () => {
- let task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: initialStreakCount });
+ const task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task, direction: 'up' });
scoreTask({ user: ref.afterUser, task, direction: 'down' });
expect(ref.afterUser.achievements.streak).to.equal(0);
});
it('decrements a multiple streak achievement when unticking a Daily', () => {
- let task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
+ const task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task: task1, direction: 'up' });
- let task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: initialStreakCount });
+ const task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task: task2, direction: 'up' });
scoreTask({ user: ref.afterUser, task: task2, direction: 'down' });
expect(ref.afterUser.achievements.streak).to.equal(1);
});
it('does not give a streak achievement for a streak of zero', () => {
- let task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: -1 });
+ const task = generateDaily({ userId: ref.afterUser._id, text: 'some daily', streak: -1 });
scoreTask({ user: ref.afterUser, task, direction: 'up' });
expect(ref.afterUser.achievements.streak).to.equal(0);
});
it('does not remove a streak achievement when unticking a Daily gives a streak of zero', () => {
- let task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
+ const task1 = generateDaily({ userId: ref.afterUser._id, text: 'first daily', streak: initialStreakCount });
scoreTask({ user: ref.afterUser, task: task1, direction: 'up' });
- let task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: 1 });
+ const task2 = generateDaily({ userId: ref.afterUser._id, text: 'second daily', streak: 1 });
scoreTask({ user: ref.afterUser, task: task2, direction: 'down' });
expect(ref.afterUser.achievements.streak).to.equal(1);
});
@@ -168,8 +176,10 @@ describe('shared.ops.scoreTask', () => {
describe('scores', () => {
let options = {};
let habit;
- let freshDaily, daily;
- let freshTodo, todo;
+ let freshDaily; let
+ daily;
+ let freshTodo; let
+ todo;
beforeEach(() => {
ref = beforeAfter(options);
@@ -190,21 +200,25 @@ describe('shared.ops.scoreTask', () => {
});
it('critical hits', () => {
- let normalUser = ref.beforeUser;
+ const normalUser = ref.beforeUser;
expect(normalUser.party.quest.progress.up).to.eql(0);
normalUser.party.quest.key = 'gryphon';
- let critUser = ref.afterUser;
+ const critUser = ref.afterUser;
expect(critUser.party.quest.progress.up).to.eql(0);
critUser.party.quest.key = 'gryphon';
- let normalTask = todo;
- let critTask = freshTodo;
+ const normalTask = todo;
+ const critTask = freshTodo;
- scoreTask({ user: normalUser, task: normalTask, direction: 'up', cron: false });
- let normalTaskDelta = normalUser.party.quest.progress.up;
+ scoreTask({
+ user: normalUser, task: normalTask, direction: 'up', cron: false,
+ });
+ const normalTaskDelta = normalUser.party.quest.progress.up;
sandbox.stub(crit, 'crit').returns(1.5);
- scoreTask({ user: critUser, task: critTask, direction: 'up', cron: false });
- let critTaskDelta = critUser.party.quest.progress.up;
+ scoreTask({
+ user: critUser, task: critTask, direction: 'up', cron: false,
+ });
+ const critTaskDelta = critUser.party.quest.progress.up;
crit.crit.restore();
expect(critUser.stats.hp).to.eql(normalUser.stats.hp);
@@ -219,20 +233,26 @@ describe('shared.ops.scoreTask', () => {
expect(ref.afterUser.party.quest.progress.up).to.eql(0);
ref.afterUser.party.quest.key = 'gryphon';
- scoreTask({ user: ref.afterUser, task: habit, direction: 'up', cron: false });
- let firstTaskDelta = ref.afterUser.party.quest.progress.up;
+ scoreTask({
+ user: ref.afterUser, task: habit, direction: 'up', cron: false,
+ });
+ const firstTaskDelta = ref.afterUser.party.quest.progress.up;
expect(firstTaskDelta).to.be.greaterThan(0);
expect(ref.afterUser._tmp.quest.progressDelta).to.eql(firstTaskDelta);
- scoreTask({ user: ref.afterUser, task: habit, direction: 'up', cron: false });
- let secondTaskDelta = ref.afterUser.party.quest.progress.up - firstTaskDelta;
+ scoreTask({
+ user: ref.afterUser, task: habit, direction: 'up', cron: false,
+ });
+ const secondTaskDelta = ref.afterUser.party.quest.progress.up - firstTaskDelta;
expect(secondTaskDelta).to.be.greaterThan(0);
expect(ref.afterUser._tmp.quest.progressDelta).to.eql(secondTaskDelta);
});
it('does not modify stats when task need approval', () => {
todo.group.approval.required = true;
- options = { user: ref.afterUser, task: todo, direction: 'up', times: 5, cron: false };
+ options = {
+ user: ref.afterUser, task: todo, direction: 'up', times: 5, cron: false,
+ };
scoreTask(options);
expect(ref.afterUser.stats.hp).to.eql(50);
@@ -242,7 +262,9 @@ describe('shared.ops.scoreTask', () => {
context('habits', () => {
it('up', () => {
- options = { user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false };
+ options = {
+ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false,
+ };
scoreTask(options);
expect(habit.history.length).to.eql(1);
@@ -256,16 +278,20 @@ describe('shared.ops.scoreTask', () => {
// not supported anymore
it('does not add score notes to task', () => {
- let scoreNotesString = 'scoreNotes';
+ const scoreNotesString = 'scoreNotes';
habit.scoreNotes = scoreNotesString;
- options = { user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false };
+ options = {
+ user: ref.afterUser, task: habit, direction: 'up', times: 5, cron: false,
+ };
scoreTask(options);
expect(habit.history[0].scoreNotes).to.eql(undefined);
});
it('down', () => {
- scoreTask({user: ref.afterUser, task: habit, direction: 'down', times: 5, cron: false}, {});
+ scoreTask({
+ user: ref.afterUser, task: habit, direction: 'down', times: 5, cron: false,
+ }, {});
expect(habit.history.length).to.eql(1);
expect(habit.value).to.be.lessThan(0);
@@ -280,16 +306,16 @@ describe('shared.ops.scoreTask', () => {
context('dailys', () => {
it('up', () => {
expect(daily.completed).to.not.eql(true);
- scoreTask({user: ref.afterUser, task: daily, direction: 'up'});
+ scoreTask({ user: ref.afterUser, task: daily, direction: 'up' });
expectGainedPoints(ref.beforeUser, ref.afterUser, freshDaily, daily);
expect(daily.completed).to.eql(true);
expect(daily.history.length).to.eql(1);
});
it('up, down', () => {
- scoreTask({user: ref.afterUser, task: daily, direction: 'up'});
+ scoreTask({ user: ref.afterUser, task: daily, direction: 'up' });
expect(daily.history.length).to.eql(1);
- scoreTask({user: ref.afterUser, task: daily, direction: 'down'});
+ scoreTask({ user: ref.afterUser, task: daily, direction: 'down' });
expect(daily.history.length).to.eql(0);
expectClosePoints(ref.beforeUser, ref.afterUser, freshDaily, daily);
});
@@ -297,20 +323,20 @@ describe('shared.ops.scoreTask', () => {
it('sets completed = false on direction = down', () => {
daily.completed = true;
expect(daily.completed).to.not.eql(false);
- scoreTask({user: ref.afterUser, task: daily, direction: 'down'});
+ scoreTask({ user: ref.afterUser, task: daily, direction: 'down' });
expect(daily.completed).to.eql(false);
});
});
context('todos', () => {
it('up', () => {
- scoreTask({user: ref.afterUser, task: todo, direction: 'up'});
+ scoreTask({ user: ref.afterUser, task: todo, direction: 'up' });
expectGainedPoints(ref.beforeUser, ref.afterUser, freshTodo, todo);
});
it('up, down', () => {
- scoreTask({user: ref.afterUser, task: todo, direction: 'up'});
- scoreTask({user: ref.afterUser, task: todo, direction: 'down'});
+ scoreTask({ user: ref.afterUser, task: todo, direction: 'up' });
+ scoreTask({ user: ref.afterUser, task: todo, direction: 'down' });
expectClosePoints(ref.beforeUser, ref.afterUser, freshTodo, todo);
});
});
diff --git a/test/common/ops/sell.js b/test/common/ops/sell.js
index 2f1d9b86d1..fbba69dd48 100644
--- a/test/common/ops/sell.js
+++ b/test/common/ops/sell.js
@@ -12,16 +12,16 @@ import content from '../../../website/common/script/content/index';
describe('shared.ops.sell', () => {
let user;
- let type = 'eggs';
- let key = 'Wolf';
- let acceptedTypes = ['eggs', 'hatchingPotions', 'food'];
+ const type = 'eggs';
+ const key = 'Wolf';
+ const acceptedTypes = ['eggs', 'hatchingPotions', 'food'];
beforeEach(() => {
user = generateUser();
user.items[type][key] = 1;
});
- it('returns an error when type is not provided', (done) => {
+ it('returns an error when type is not provided', done => {
try {
sell(user);
} catch (err) {
@@ -31,9 +31,9 @@ describe('shared.ops.sell', () => {
}
});
- it('returns an error when key is not provided', (done) => {
+ it('returns an error when key is not provided', done => {
try {
- sell(user, {params: { type } });
+ sell(user, { params: { type } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
expect(err.message).to.equal(i18n.t('missingKeyParam'));
@@ -41,56 +41,56 @@ describe('shared.ops.sell', () => {
}
});
- it('returns an error when non-sellable type is provided', (done) => {
- let nonSellableType = 'nonSellableType';
+ it('returns an error when non-sellable type is provided', done => {
+ const nonSellableType = 'nonSellableType';
try {
- sell(user, {params: { type: nonSellableType, key } });
+ sell(user, { params: { type: nonSellableType, key } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
- expect(err.message).to.equal(i18n.t('typeNotSellable', {acceptedTypes: acceptedTypes.join(', ')}));
+ expect(err.message).to.equal(i18n.t('typeNotSellable', { acceptedTypes: acceptedTypes.join(', ') }));
done();
}
});
- it('returns an error when key is not found with type provided', (done) => {
- let fakeKey = 'fakeKey';
+ it('returns an error when key is not found with type provided', done => {
+ const fakeKey = 'fakeKey';
try {
- sell(user, {params: { type, key: fakeKey } });
+ sell(user, { params: { type, key: fakeKey } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
- expect(err.message).to.equal(i18n.t('userItemsKeyNotFound', {type}));
+ expect(err.message).to.equal(i18n.t('userItemsKeyNotFound', { type }));
done();
}
});
- it('returns an error when the requested amount is above the available amount', (done) => {
+ it('returns an error when the requested amount is above the available amount', done => {
try {
- sell(user, {params: { type, key }, query: {amount: 2} });
+ sell(user, { params: { type, key }, query: { amount: 2 } });
} catch (err) {
expect(err).to.be.an.instanceof(NotFound);
- expect(err.message).to.equal(i18n.t('userItemsNotEnough', {type}));
+ expect(err.message).to.equal(i18n.t('userItemsNotEnough', { type }));
done();
}
});
- it('returns an error when the requested amount is negative', (done) => {
+ it('returns an error when the requested amount is negative', done => {
try {
- sell(user, {params: { type, key }, query: {amount: -42} });
+ sell(user, { params: { type, key }, query: { amount: -42 } });
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
- expect(err.message).to.equal(i18n.t('positiveAmountRequired', {type}));
+ expect(err.message).to.equal(i18n.t('positiveAmountRequired', { type }));
done();
}
});
- it('returns error when trying to sell Saddle', (done) => {
+ it('returns error when trying to sell Saddle', done => {
const foodType = 'food';
const saddleKey = 'Saddle';
user.items[foodType][saddleKey] = 1;
try {
- sell(user, {params: {type: foodType, key: saddleKey}});
+ sell(user, { params: { type: foodType, key: saddleKey } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('foodSaddleSellWarningNote'));
@@ -99,13 +99,13 @@ describe('shared.ops.sell', () => {
});
it('reduces item count from user', () => {
- sell(user, {params: { type, key } });
+ sell(user, { params: { type, key } });
expect(user.items[type][key]).to.equal(0);
});
it('increases user\'s gold', () => {
- sell(user, {params: { type, key } });
+ sell(user, { params: { type, key } });
expect(user.stats.gp).to.equal(content[type][key].value);
});
diff --git a/test/common/ops/sleep.js b/test/common/ops/sleep.js
index 0a0ef835f7..9926a6ea4e 100644
--- a/test/common/ops/sleep.js
+++ b/test/common/ops/sleep.js
@@ -5,13 +5,13 @@ import {
describe('shared.ops.sleep', () => {
it('toggles user.preferences.sleep', () => {
- let user = generateUser();
+ const user = generateUser();
- let [res] = sleep(user);
+ const [res] = sleep(user);
expect(res).to.eql(true);
expect(user.preferences.sleep).to.equal(true);
- let [res2] = sleep(user);
+ const [res2] = sleep(user);
expect(res2).to.eql(false);
expect(user.preferences.sleep).to.equal(false);
});
diff --git a/test/common/ops/spells.js b/test/common/ops/spells.js
index 58d3965a7f..939b7caab5 100644
--- a/test/common/ops/spells.js
+++ b/test/common/ops/spells.js
@@ -16,13 +16,13 @@ describe('shared.ops.spells', () => {
user = generateUser();
});
- it('returns an error when healer tries to cast Healing Light with full health', (done) => {
+ it('returns an error when healer tries to cast Healing Light with full health', done => {
user.stats.class = 'healer';
user.stats.lvl = 11;
user.stats.hp = 50;
user.stats.mp = 200;
- let spell = spells.healer.heal;
+ const spell = spells.healer.heal;
try {
spell.cast(user);
@@ -35,4 +35,4 @@ describe('shared.ops.spells', () => {
done();
}
});
-});
\ No newline at end of file
+});
diff --git a/test/common/ops/stats/allocate.js b/test/common/ops/stats/allocate.js
index 62e162f55a..568b0500ce 100644
--- a/test/common/ops/stats/allocate.js
+++ b/test/common/ops/stats/allocate.js
@@ -20,19 +20,19 @@ describe('shared.ops.allocate', () => {
});
});
- it('throws an error if an invalid attribute is supplied', (done) => {
+ it('throws an error if an invalid attribute is supplied', done => {
try {
allocate(user, {
- query: {stat: 'notValid'},
+ query: { stat: 'notValid' },
});
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
- expect(err.message).to.equal(errorMessage('invalidAttribute', {attr: 'notValid'}));
+ expect(err.message).to.equal(errorMessage('invalidAttribute', { attr: 'notValid' }));
done();
}
});
- it('throws an error if the user is below lvl 10', (done) => {
+ it('throws an error if the user is below lvl 10', done => {
user.stats.lvl = 9;
try {
allocate(user);
@@ -43,7 +43,7 @@ describe('shared.ops.allocate', () => {
}
});
- it('throws an error if the user hasn\'t selected class', (done) => {
+ it('throws an error if the user hasn\'t selected class', done => {
user.flags.classSelected = false;
try {
allocate(user);
@@ -54,7 +54,7 @@ describe('shared.ops.allocate', () => {
}
});
- it('throws an error if the user has disabled classes', (done) => {
+ it('throws an error if the user has disabled classes', done => {
user.preferences.disableClasses = true;
try {
allocate(user);
@@ -65,7 +65,7 @@ describe('shared.ops.allocate', () => {
}
});
- it('throws an error if the user doesn\'t have attribute points', (done) => {
+ it('throws an error if the user doesn\'t have attribute points', done => {
try {
allocate(user);
} catch (err) {
@@ -85,7 +85,7 @@ describe('shared.ops.allocate', () => {
it('allocates attribute points', () => {
expect(user.stats.con).to.equal(0);
user.stats.points = 1;
- allocate(user, {query: {stat: 'con'}});
+ allocate(user, { query: { stat: 'con' } });
expect(user.stats.con).to.equal(1);
expect(user.stats.points).to.equal(0);
});
@@ -94,7 +94,7 @@ describe('shared.ops.allocate', () => {
expect(user.stats.int).to.equal(0);
expect(user.stats.mp).to.equal(10);
user.stats.points = 1;
- allocate(user, {query: {stat: 'int'}});
+ allocate(user, { query: { stat: 'int' } });
expect(user.stats.int).to.equal(1);
expect(user.stats.mp).to.equal(11);
});
diff --git a/test/common/ops/stats/allocateBulk.js b/test/common/ops/stats/allocateBulk.js
index 1a46c82214..7a81d37ce1 100644
--- a/test/common/ops/stats/allocateBulk.js
+++ b/test/common/ops/stats/allocateBulk.js
@@ -20,7 +20,7 @@ describe('shared.ops.allocateBulk', () => {
});
});
- it('throws an error if an invalid attribute is supplied', (done) => {
+ it('throws an error if an invalid attribute is supplied', done => {
try {
allocateBulk(user, {
body: {
@@ -32,12 +32,12 @@ describe('shared.ops.allocateBulk', () => {
});
} catch (err) {
expect(err).to.be.an.instanceof(BadRequest);
- expect(err.message).to.equal(errorMessage('invalidAttribute', {attr: 'invalid'}));
+ expect(err.message).to.equal(errorMessage('invalidAttribute', { attr: 'invalid' }));
done();
}
});
- it('throws an error if the stats are not supplied', (done) => {
+ it('throws an error if the stats are not supplied', done => {
try {
allocateBulk(user);
} catch (err) {
@@ -47,7 +47,7 @@ describe('shared.ops.allocateBulk', () => {
}
});
- it('throws an error if the user is below lvl 10', (done) => {
+ it('throws an error if the user is below lvl 10', done => {
user.stats.lvl = 9;
try {
allocateBulk(user, {
@@ -65,7 +65,7 @@ describe('shared.ops.allocateBulk', () => {
}
});
- it('throws an error if the user hasn\'t selected class', (done) => {
+ it('throws an error if the user hasn\'t selected class', done => {
user.flags.classSelected = false;
try {
allocateBulk(user, {
@@ -83,7 +83,7 @@ describe('shared.ops.allocateBulk', () => {
}
});
- it('throws an error if the user has disabled classes', (done) => {
+ it('throws an error if the user has disabled classes', done => {
user.preferences.disableClasses = true;
try {
allocateBulk(user, {
@@ -101,7 +101,7 @@ describe('shared.ops.allocateBulk', () => {
}
});
- it('throws an error if the user doesn\'t have attribute points', (done) => {
+ it('throws an error if the user doesn\'t have attribute points', done => {
try {
allocateBulk(user, {
body: {
@@ -118,7 +118,7 @@ describe('shared.ops.allocateBulk', () => {
}
});
- it('throws an error if the user doesn\'t have enough attribute points', (done) => {
+ it('throws an error if the user doesn\'t have enough attribute points', done => {
user.stats.points = 1;
try {
allocateBulk(user, {
diff --git a/test/common/ops/stats/allocateNow.js b/test/common/ops/stats/allocateNow.js
index d9f1baacb3..746646120e 100644
--- a/test/common/ops/stats/allocateNow.js
+++ b/test/common/ops/stats/allocateNow.js
@@ -18,7 +18,7 @@ describe('shared.ops.allocateNow', () => {
user.stats.str = 9;
user.preferences.allocationMode = 'flat';
- let [data] = allocateNow(user);
+ const [data] = allocateNow(user);
expect(user.stats.points).to.equal(0);
expect(user.stats.con).to.equal(9);
diff --git a/test/common/ops/unlock.js b/test/common/ops/unlock.js
index 0ea3cb9b8c..5087534b48 100644
--- a/test/common/ops/unlock.js
+++ b/test/common/ops/unlock.js
@@ -10,18 +10,18 @@ import {
describe('shared.ops.unlock', () => {
let user;
- let unlockPath = 'shirt.convict,shirt.cross,shirt.fire,shirt.horizon,shirt.ocean,shirt.purple,shirt.rainbow,shirt.redblue,shirt.thunder,shirt.tropical,shirt.zombie';
- let unlockGearSetPath = 'items.gear.owned.headAccessory_special_bearEars,items.gear.owned.headAccessory_special_cactusEars,items.gear.owned.headAccessory_special_foxEars,items.gear.owned.headAccessory_special_lionEars,items.gear.owned.headAccessory_special_pandaEars,items.gear.owned.headAccessory_special_pigEars,items.gear.owned.headAccessory_special_tigerEars,items.gear.owned.headAccessory_special_wolfEars';
- let backgroundUnlockPath = 'background.giant_florals';
- let unlockCost = 1.25;
- let usersStartingGems = 5;
+ const unlockPath = 'shirt.convict,shirt.cross,shirt.fire,shirt.horizon,shirt.ocean,shirt.purple,shirt.rainbow,shirt.redblue,shirt.thunder,shirt.tropical,shirt.zombie';
+ const unlockGearSetPath = 'items.gear.owned.headAccessory_special_bearEars,items.gear.owned.headAccessory_special_cactusEars,items.gear.owned.headAccessory_special_foxEars,items.gear.owned.headAccessory_special_lionEars,items.gear.owned.headAccessory_special_pandaEars,items.gear.owned.headAccessory_special_pigEars,items.gear.owned.headAccessory_special_tigerEars,items.gear.owned.headAccessory_special_wolfEars';
+ const backgroundUnlockPath = 'background.giant_florals';
+ const unlockCost = 1.25;
+ const usersStartingGems = 5;
beforeEach(() => {
user = generateUser();
user.balance = usersStartingGems;
});
- it('returns an error when path is not provided', (done) => {
+ it('returns an error when path is not provided', done => {
try {
unlock(user);
} catch (err) {
@@ -31,11 +31,11 @@ describe('shared.ops.unlock', () => {
}
});
- it('returns an error when user balance is too low', (done) => {
+ it('returns an error when user balance is too low', done => {
user.balance = 0;
try {
- unlock(user, {query: {path: unlockPath}});
+ unlock(user, { query: { path: unlockPath } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('notEnoughGems'));
@@ -43,10 +43,10 @@ describe('shared.ops.unlock', () => {
}
});
- it('returns an error when user already owns a full set', (done) => {
+ it('returns an error when user already owns a full set', done => {
try {
- unlock(user, {query: {path: unlockPath}});
- unlock(user, {query: {path: unlockPath}});
+ unlock(user, { query: { path: unlockPath } });
+ unlock(user, { query: { path: unlockPath } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('alreadyUnlocked'));
@@ -55,10 +55,10 @@ describe('shared.ops.unlock', () => {
});
// disabled untill fully implemente
- xit('returns an error when user already owns items in a full set', (done) => {
+ xit('returns an error when user already owns items in a full set', done => {
try {
- unlock(user, {query: {path: unlockPath}});
- unlock(user, {query: {path: unlockPath}});
+ unlock(user, { query: { path: unlockPath } });
+ unlock(user, { query: { path: unlockPath } });
} catch (err) {
expect(err).to.be.an.instanceof(NotAuthorized);
expect(err.message).to.equal(i18n.t('alreadyUnlocked'));
@@ -69,9 +69,9 @@ describe('shared.ops.unlock', () => {
it('equips an item already owned', () => {
expect(user.purchased.background.giant_florals).to.not.exist;
- unlock(user, {query: {path: backgroundUnlockPath}});
- let afterBalance = user.balance;
- let response = unlock(user, {query: {path: backgroundUnlockPath}});
+ unlock(user, { query: { path: backgroundUnlockPath } });
+ const afterBalance = user.balance;
+ const response = unlock(user, { query: { path: backgroundUnlockPath } });
expect(user.balance).to.equal(afterBalance); // do not bill twice
expect(response.message).to.not.exist;
@@ -81,10 +81,10 @@ describe('shared.ops.unlock', () => {
it('un-equips an item already equipped', () => {
expect(user.purchased.background.giant_florals).to.not.exist;
- unlock(user, {query: {path: backgroundUnlockPath}}); // unlock
- let afterBalance = user.balance;
- unlock(user, {query: {path: backgroundUnlockPath}}); // equip
- let response = unlock(user, {query: {path: backgroundUnlockPath}});
+ unlock(user, { query: { path: backgroundUnlockPath } }); // unlock
+ const afterBalance = user.balance;
+ unlock(user, { query: { path: backgroundUnlockPath } }); // equip
+ const response = unlock(user, { query: { path: backgroundUnlockPath } });
expect(user.balance).to.equal(afterBalance); // do not bill twice
expect(response.message).to.not.exist;
@@ -92,28 +92,28 @@ describe('shared.ops.unlock', () => {
});
it('unlocks a full set', () => {
- let [, message] = unlock(user, {query: {path: unlockPath}});
+ const [, message] = unlock(user, { query: { path: unlockPath } });
expect(message).to.equal(i18n.t('unlocked'));
expect(user.purchased.shirt.convict).to.be.true;
});
it('unlocks a full set of gear', () => {
- let [, message] = unlock(user, {query: {path: unlockGearSetPath}});
+ const [, message] = unlock(user, { query: { path: unlockGearSetPath } });
expect(message).to.equal(i18n.t('unlocked'));
expect(user.items.gear.owned.headAccessory_special_wolfEars).to.be.true;
});
it('unlocks a an item', () => {
- let [, message] = unlock(user, {query: {path: backgroundUnlockPath}});
+ const [, message] = unlock(user, { query: { path: backgroundUnlockPath } });
expect(message).to.equal(i18n.t('unlocked'));
expect(user.purchased.background.giant_florals).to.be.true;
});
it('reduces a user\'s balance', () => {
- let [, message] = unlock(user, {query: {path: unlockPath}});
+ const [, message] = unlock(user, { query: { path: unlockPath } });
expect(message).to.equal(i18n.t('unlocked'));
expect(user.balance).to.equal(usersStartingGems - unlockCost);
diff --git a/test/common/ops/updateTask.js b/test/common/ops/updateTask.js
index e9aa88f550..c1fbc7c8e2 100644
--- a/test/common/ops/updateTask.js
+++ b/test/common/ops/updateTask.js
@@ -5,8 +5,8 @@ import {
describe('shared.ops.updateTask', () => {
it('updates a task', () => {
- let now = new Date();
- let habit = generateHabit({
+ const now = new Date();
+ const habit = generateHabit({
tags: [
'123',
'456',
@@ -19,7 +19,7 @@ describe('shared.ops.updateTask', () => {
}],
});
- let [res] = updateTask(habit, {
+ const [res] = updateTask(habit, {
body: {
text: 'updated',
id: '123',
diff --git a/test/common/shouldDo.test.js b/test/common/shouldDo.test.js
index dedcaa4951..f7505d20f3 100644
--- a/test/common/shouldDo.test.js
+++ b/test/common/shouldDo.test.js
@@ -1,9 +1,10 @@
-import { shouldDo, DAY_MAPPING } from '../../website/common/script/cron';
import moment from 'moment';
+import { shouldDo, DAY_MAPPING } from '../../website/common/script/cron';
import 'moment-recur';
describe('shouldDo', () => {
- let day, dailyTask;
+ let day; let
+ dailyTask;
let options = {};
let nextDue = [];
@@ -29,9 +30,9 @@ describe('shouldDo', () => {
});
it('returns false if task type is not a daily', () => {
- expect(shouldDo(day, {type: 'todo'})).to.equal(false);
- expect(shouldDo(day, {type: 'habit'})).to.equal(false);
- expect(shouldDo(day, {type: 'reward'})).to.equal(false);
+ expect(shouldDo(day, { type: 'todo' })).to.equal(false);
+ expect(shouldDo(day, { type: 'habit' })).to.equal(false);
+ expect(shouldDo(day, { type: 'reward' })).to.equal(false);
});
it('returns false if startDate is in the future', () => {
@@ -51,12 +52,12 @@ describe('shouldDo', () => {
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
- it('returns true if Start Date is today', () => {
+ it('returns true if Start Date is today', () => {
dailyTask.startDate = moment().toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
- it('returns false if Start Date is after today', () => {
+ it('returns false if Start Date is after today', () => {
dailyTask.startDate = moment().add(1, 'days').toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(false);
});
@@ -79,14 +80,16 @@ describe('shouldDo', () => {
it('returns true if the user\'s current time is after start date and Custom Day Start', () => {
options.dayStart = 4;
- day = moment().zone(options.timezoneOffset).startOf('day').add(6, 'hours').toDate();
+ day = moment().zone(options.timezoneOffset).startOf('day').add(6, 'hours')
+ .toDate();
dailyTask.startDate = moment().zone(options.timezoneOffset).startOf('day').toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
it('returns false if the user\'s current time is before Custom Day Start', () => {
options.dayStart = 8;
- day = moment().zone(options.timezoneOffset).startOf('day').add(2, 'hours').toDate();
+ day = moment().zone(options.timezoneOffset).startOf('day').add(2, 'hours')
+ .toDate();
dailyTask.startDate = moment().zone(options.timezoneOffset).startOf('day').toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(false);
});
@@ -102,20 +105,22 @@ describe('shouldDo', () => {
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
- it('returns true if Start Date is today', () => {
+ it('returns true if Start Date is today', () => {
dailyTask.startDate = moment().startOf('day').toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
it('returns true if the user\'s current time is after Custom Day Start', () => {
options.dayStart = 4;
- day = moment().zone(options.timezoneOffset).startOf('day').add(6, 'hours').toDate();
+ day = moment().zone(options.timezoneOffset).startOf('day').add(6, 'hours')
+ .toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(true);
});
it('returns false if the user\'s current time is before Custom Day Start', () => {
options.dayStart = 8;
- day = moment().zone(options.timezoneOffset).startOf('day').add(2, 'hours').toDate();
+ day = moment().zone(options.timezoneOffset).startOf('day').add(2, 'hours')
+ .toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(false);
});
});
@@ -335,11 +340,11 @@ describe('shouldDo', () => {
m: false,
};
- for (let weekday of [0, 1, 2, 3, 4, 5, 6]) {
+ [0, 1, 2, 3, 4, 5, 6].forEach(weekday => {
day = moment().day(weekday).toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(false);
- }
+ });
});
it('returns false and ignore malformed repeat object', () => {
@@ -354,11 +359,11 @@ describe('shouldDo', () => {
errors: 'errors',
};
- for (let weekday of [0, 1, 2, 3, 4, 5, 6]) {
+ [0, 1, 2, 3, 4, 5, 6].forEach(weekday => {
day = moment().day(weekday).toDate();
expect(shouldDo(day, dailyTask, options)).to.equal(false);
- }
+ });
});
it('returns false if day of the week does not match and active on the day it matches', () => {
@@ -372,7 +377,8 @@ describe('shouldDo', () => {
m: false,
};
- for (let weekday of [0, 1, 2, 3, 4, 5, 6]) {
+
+ [0, 1, 2, 3, 4, 5, 6].forEach(weekday => {
day = moment().add(1, 'weeks').day(weekday).toDate();
if (weekday === 4) {
@@ -380,7 +386,7 @@ describe('shouldDo', () => {
} else {
expect(shouldDo(day, dailyTask, options)).to.equal(false);
}
- }
+ });
});
it('returns true if Daily on matching days of the week', () => {
@@ -599,7 +605,7 @@ describe('shouldDo', () => {
day = moment();
dailyTask.repeat[DAY_MAPPING[day.day()]] = true;
dailyTask.everyX = 3;
- let tomorrow = day.add(2, 'weeks').day(day.day()).toDate();
+ const tomorrow = day.add(2, 'weeks').day(day.day()).toDate();
expect(shouldDo(tomorrow, dailyTask, options)).to.equal(false);
});
@@ -618,14 +624,14 @@ describe('shouldDo', () => {
day = moment();
dailyTask.repeat[DAY_MAPPING[day.day()]] = true;
dailyTask.everyX = 3;
- let threeWeeksFromTodayPlusOne = day.add(1, 'day').add(3, 'weeks').toDate();
+ const threeWeeksFromTodayPlusOne = day.add(1, 'day').add(3, 'weeks').toDate();
expect(shouldDo(threeWeeksFromTodayPlusOne, dailyTask, options)).to.equal(false);
});
it('activates Daily on matching week', () => {
dailyTask.everyX = 3;
- let threeWeeksFromToday = moment().add(3, 'weeks').toDate();
+ const threeWeeksFromToday = moment().add(3, 'weeks').toDate();
expect(shouldDo(threeWeeksFromToday, dailyTask, options)).to.equal(true);
});
@@ -733,9 +739,9 @@ describe('shouldDo', () => {
it('leaves daily inactive if not day of the month', () => {
dailyTask.everyX = 1;
dailyTask.frequency = 'monthly';
- let today = moment();
+ const today = moment();
dailyTask.daysOfMonth = [today.date()];
- let tomorrow = today.add(1, 'day').toDate();
+ const tomorrow = today.add(1, 'day').toDate();
expect(shouldDo(tomorrow, dailyTask, options)).to.equal(false);
});
@@ -753,9 +759,9 @@ describe('shouldDo', () => {
it('leaves daily inactive if not on date of the x month', () => {
dailyTask.everyX = 2;
dailyTask.frequency = 'monthly';
- let today = moment();
+ const today = moment();
dailyTask.daysOfMonth = [today.date()];
- let tomorrow = today.add(2, 'months').add(1, 'day').toDate();
+ const tomorrow = today.add(2, 'months').add(1, 'day').toDate();
expect(shouldDo(tomorrow, dailyTask, options)).to.equal(false);
});
@@ -920,9 +926,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-27');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-27');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
@@ -944,8 +950,8 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-05-27T17:34:40.000Z');
- let week = today.monthWeek();
+ const today = moment('2017-05-27T17:34:40.000Z');
+ const week = today.monthWeek();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.everyX = 1;
@@ -966,9 +972,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-27:00:00.000-00:00');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-27:00:00.000-00:00');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
@@ -990,9 +996,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-26:00:00.000-00:00');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-26:00:00.000-00:00');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
@@ -1015,9 +1021,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-27:00:00.000-00:00');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-27:00:00.000-00:00');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
@@ -1040,9 +1046,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-27:00:00.000-00:00');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-27:00:00.000-00:00');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
@@ -1066,9 +1072,9 @@ describe('shouldDo', () => {
m: false,
};
- let today = moment('2017-01-27');
- let week = today.monthWeek();
- let dayOfWeek = today.day();
+ const today = moment('2017-01-27');
+ const week = today.monthWeek();
+ const dayOfWeek = today.day();
dailyTask.startDate = today.toDate();
dailyTask.weeksOfMonth = [week];
dailyTask.repeat[DAY_MAPPING[dayOfWeek]] = true;
diff --git a/test/common/statHelpers.test.js b/test/common/statHelpers.test.js
index 5fe7005b58..0e8ee24a03 100644
--- a/test/common/statHelpers.test.js
+++ b/test/common/statHelpers.test.js
@@ -42,7 +42,7 @@ describe('helper functions used in stat calculations', () => {
describe('toNextLevel', () => {
it('increases Experience target from one level to the next', () => {
- _.times(110, (level) => {
+ _.times(110, level => {
expect(tnl(level + 1)).to.be.greaterThan(tnl(level));
});
});
@@ -62,7 +62,8 @@ describe('helper functions used in stat calculations', () => {
});
it('provides a different curve if a halfway point is defined', () => {
- expect(diminishingReturns(BONUS, MAXIMUM, HALFWAY)).to.not.eql(diminishingReturns(BONUS, MAXIMUM));
+ expect(diminishingReturns(BONUS, MAXIMUM, HALFWAY))
+ .to.not.eql(diminishingReturns(BONUS, MAXIMUM));
});
});
});
diff --git a/test/common/test_helper.js b/test/common/test_helper.js
index 7b9ba2beff..32fdf835ec 100644
--- a/test/common/test_helper.js
+++ b/test/common/test_helper.js
@@ -1,59 +1,27 @@
/* eslint-disable prefer-template, no-shadow, func-names */
-let expect = require('expect.js');
+const expect = require('expect.js');
module.exports.addCustomMatchers = function () {
- let Assertion;
-
- Assertion = expect.Assertion;
+ const { Assertion } = expect;
Assertion.prototype.toHaveGP = function (gp) {
- let actual;
-
- actual = this.obj.stats.gp;
- return this.assert(actual === gp, () => {
- return 'expected user to have ' + gp + ' gp, but got ' + actual;
- }, () => {
- return 'expected user to not have ' + gp + ' gp';
- });
+ const actual = this.obj.stats.gp;
+ return this.assert(actual === gp, () => 'expected user to have ' + gp + ' gp, but got ' + actual, () => 'expected user to not have ' + gp + ' gp');
};
Assertion.prototype.toHaveHP = function (hp) {
- let actual;
-
- actual = this.obj.stats.hp;
- return this.assert(actual === hp, () => {
- return 'expected user to have ' + hp + ' hp, but got ' + actual;
- }, () => {
- return 'expected user to not have ' + hp + ' hp';
- });
+ const actual = this.obj.stats.hp;
+ return this.assert(actual === hp, () => 'expected user to have ' + hp + ' hp, but got ' + actual, () => 'expected user to not have ' + hp + ' hp');
};
Assertion.prototype.toHaveExp = function (exp) {
- let actual;
-
- actual = this.obj.stats.exp;
- return this.assert(actual === exp, () => {
- return 'expected user to have ' + exp + ' experience points, but got ' + actual;
- }, () => {
- return 'expected user to not have ' + exp + ' experience points';
- });
+ const actual = this.obj.stats.exp;
+ return this.assert(actual === exp, () => 'expected user to have ' + exp + ' experience points, but got ' + actual, () => 'expected user to not have ' + exp + ' experience points');
};
Assertion.prototype.toHaveLevel = function (lvl) {
- let actual;
-
- actual = this.obj.stats.lvl;
- return this.assert(actual === lvl, () => {
- return 'expected user to be level ' + lvl + ', but got ' + actual;
- }, () => {
- return 'expected user to not be level ' + lvl;
- });
+ const actual = this.obj.stats.lvl;
+ return this.assert(actual === lvl, () => 'expected user to be level ' + lvl + ', but got ' + actual, () => 'expected user to not be level ' + lvl);
};
Assertion.prototype.toHaveMaxMP = function (mp) {
- let actual;
-
- actual = this.obj._statsComputed.maxMP;
- return this.assert(actual === mp, () => {
- return 'expected user to have ' + mp + ' max mp, but got ' + actual;
- }, () => {
- return 'expected user to not have ' + mp + ' max mp';
- });
+ const actual = this.obj._statsComputed.maxMP;
+ return this.assert(actual === mp, () => 'expected user to have ' + mp + ' max mp, but got ' + actual, () => 'expected user to not have ' + mp + ' max mp');
};
};
diff --git a/test/content/eggs.test.js b/test/content/eggs.test.js
index 7f7c1479ed..cb0e173579 100644
--- a/test/content/eggs.test.js
+++ b/test/content/eggs.test.js
@@ -7,12 +7,12 @@ import {
import * as eggs from '../../website/common/script/content/eggs';
-describe('eggs', () => {
- describe('all', () => {
+describe('eggs', () => {
+ describe('all', () => {
it('is a combination of drop and quest eggs', () => {
- let dropNumber = Object.keys(eggs.drops).length;
- let questNumber = Object.keys(eggs.quests).length;
- let allNumber = Object.keys(eggs.all).length;
+ const dropNumber = Object.keys(eggs.drops).length;
+ const questNumber = Object.keys(eggs.quests).length;
+ const allNumber = Object.keys(eggs.all).length;
expect(allNumber).to.be.greaterThan(0);
expect(allNumber).to.equal(dropNumber + questNumber);
diff --git a/test/content/faq.js b/test/content/faq.js
index a71c9b2b91..96df559f55 100644
--- a/test/content/faq.js
+++ b/test/content/faq.js
@@ -5,24 +5,24 @@ import {
import faq from '../../website/common/script/content/faq';
-const {questions, stillNeedHelp} = faq;
+const { questions, stillNeedHelp } = faq;
describe('FAQ Locales', () => {
describe('Questions', () => {
it('has a valid questions', () => {
- each(questions, (question) => {
+ each(questions, question => {
expectValidTranslationString(question.question);
});
});
it('has a valid ios answers', () => {
- each(questions, (question) => {
+ each(questions, question => {
expectValidTranslationString(question.ios);
});
});
it('has a valid web answers', () => {
- each(questions, (question) => {
+ each(questions, question => {
expectValidTranslationString(question.web);
});
});
diff --git a/test/content/gear.js b/test/content/gear.js
index 386432ce41..49c6fe0e87 100644
--- a/test/content/gear.js
+++ b/test/content/gear.js
@@ -1,8 +1,8 @@
/* eslint-disable camelcase */
+import { each, camelCase } from 'lodash';
import {
expectValidTranslationString,
} from '../helpers/content.helper';
-import { each, camelCase } from 'lodash';
import gearData from '../../website/common/script/content/gear';
import * as backerGear from '../../website/common/script/content/gear/sets/special/special-backer';
@@ -16,7 +16,7 @@ describe('Gear', () => {
each(piece, (items, klass) => {
context(`${klass} ${gearType}s`, () => {
it('have a value of at least 0 for each stat', () => {
- each(items, (gear) => {
+ each(items, gear => {
expect(gear.con).to.be.at.least(0);
expect(gear.int).to.be.at.least(0);
expect(gear.per).to.be.at.least(0);
@@ -25,26 +25,26 @@ describe('Gear', () => {
});
it('have a purchase value of at least 0', () => {
- each(items, (gear) => {
+ each(items, gear => {
expect(gear.value).to.be.at.least(0);
});
});
it('has a canBuy function', () => {
- each(items, (gear) => {
+ each(items, gear => {
expect(gear.canBuy).to.be.a('function');
});
});
it('have valid translation strings for text and notes', () => {
- each(items, (gear) => {
+ each(items, gear => {
expectValidTranslationString(gear.text);
expectValidTranslationString(gear.notes);
});
});
it('has a set attribue', () => {
- each(items, (gear) => {
+ each(items, gear => {
expect(gear.set).to.exist;
});
});
@@ -63,7 +63,7 @@ describe('Gear', () => {
};
});
- let cases = {
+ const cases = {
armor_special_0: 45,
armor_special_2: 300,
head_special_0: 45,
@@ -75,7 +75,7 @@ describe('Gear', () => {
each(cases, (tierRequirement, key) => {
context(key, () => {
- let camelCaseKey = camelCase(key);
+ const camelCaseKey = camelCase(key);
it(`canOwn returns true if user has a backer tier of ${tierRequirement} or higher`, () => {
user.backer.tier = tierRequirement;
@@ -112,7 +112,7 @@ describe('Gear', () => {
};
});
- let cases = {
+ const cases = {
armor_special_1: 2,
head_special_1: 3,
shield_special_1: 5,
@@ -121,7 +121,7 @@ describe('Gear', () => {
each(cases, (tierRequirement, key) => {
context(key, () => {
- let camelCaseKey = camelCase(key);
+ const camelCaseKey = camelCase(key);
it(`canOwn returns true if user has a contributor tier of ${tierRequirement} or higher`, () => {
user.contributor.level = tierRequirement;
diff --git a/test/content/hatching-potions.test.js b/test/content/hatching-potions.test.js
index f18d04923e..a4e31d7b91 100644
--- a/test/content/hatching-potions.test.js
+++ b/test/content/hatching-potions.test.js
@@ -7,13 +7,13 @@ import {
import * as hatchingPotions from '../../website/common/script/content/hatching-potions';
-describe('hatchingPotions', () => {
- describe('all', () => {
+describe('hatchingPotions', () => {
+ describe('all', () => {
it('is a combination of drop, premium, and wacky potions', () => {
- let dropNumber = Object.keys(hatchingPotions.drops).length;
- let premiumNumber = Object.keys(hatchingPotions.premium).length;
- let wackyNumber = Object.keys(hatchingPotions.wacky).length;
- let allNumber = Object.keys(hatchingPotions.all).length;
+ const dropNumber = Object.keys(hatchingPotions.drops).length;
+ const premiumNumber = Object.keys(hatchingPotions.premium).length;
+ const wackyNumber = Object.keys(hatchingPotions.wacky).length;
+ const allNumber = Object.keys(hatchingPotions.all).length;
expect(allNumber).to.be.greaterThan(0);
expect(allNumber).to.equal(dropNumber + premiumNumber + wackyNumber);
diff --git a/test/content/mysterySets.test.js b/test/content/mysterySets.test.js
index 97e9c31be8..777a6e2bbb 100644
--- a/test/content/mysterySets.test.js
+++ b/test/content/mysterySets.test.js
@@ -1,4 +1,4 @@
-import {each} from 'lodash';
+import { each } from 'lodash';
import {
expectValidTranslationString,
} from '../helpers/content.helper';
@@ -7,7 +7,7 @@ import mysterySets from '../../website/common/script/content/mystery-sets';
describe('Mystery Sets', () => {
it('has a valid text string', () => {
- each(mysterySets, (set) => {
+ each(mysterySets, set => {
expectValidTranslationString(set.text);
});
});
diff --git a/test/content/stable.test.js b/test/content/stable.test.js
index 007cbea84f..3266cb7f47 100644
--- a/test/content/stable.test.js
+++ b/test/content/stable.test.js
@@ -10,13 +10,13 @@ import * as stable from '../../website/common/script/content/stable';
import * as eggs from '../../website/common/script/content/eggs';
import * as potions from '../../website/common/script/content/hatching-potions';
-describe('stable', () => {
+describe('stable', () => {
describe('dropPets', () => {
it('contains a pet for each drop potion * each drop egg', () => {
- let numberOfDropPotions = Object.keys(potions.drops).length;
- let numberOfDropEggs = Object.keys(eggs.drops).length;
- let numberOfDropPets = Object.keys(stable.dropPets).length;
- let expectedTotal = numberOfDropPotions * numberOfDropEggs;
+ const numberOfDropPotions = Object.keys(potions.drops).length;
+ const numberOfDropEggs = Object.keys(eggs.drops).length;
+ const numberOfDropPets = Object.keys(stable.dropPets).length;
+ const expectedTotal = numberOfDropPotions * numberOfDropEggs;
expect(numberOfDropPets).to.be.greaterThan(0);
expect(numberOfDropPets).to.equal(expectedTotal);
@@ -25,10 +25,10 @@ describe('stable', () => {
describe('questPets', () => {
it('contains a pet for each drop potion * each quest egg', () => {
- let numberOfDropPotions = Object.keys(potions.drops).length;
- let numberOfQuestEggs = Object.keys(eggs.quests).length;
- let numberOfQuestPets = Object.keys(stable.questPets).length;
- let expectedTotal = numberOfDropPotions * numberOfQuestEggs;
+ const numberOfDropPotions = Object.keys(potions.drops).length;
+ const numberOfQuestEggs = Object.keys(eggs.quests).length;
+ const numberOfQuestPets = Object.keys(stable.questPets).length;
+ const expectedTotal = numberOfDropPotions * numberOfQuestEggs;
expect(numberOfQuestPets).to.be.greaterThan(0);
expect(numberOfQuestPets).to.equal(expectedTotal);
@@ -37,10 +37,10 @@ describe('stable', () => {
describe('premiumPets', () => {
it('contains a pet for each premium potion * each drop egg', () => {
- let numberOfPremiumPotions = Object.keys(potions.premium).length;
- let numberOfDropEggs = Object.keys(eggs.drops).length;
- let numberOfPremiumPets = Object.keys(stable.premiumPets).length;
- let expectedTotal = numberOfPremiumPotions * numberOfDropEggs;
+ const numberOfPremiumPotions = Object.keys(potions.premium).length;
+ const numberOfDropEggs = Object.keys(eggs.drops).length;
+ const numberOfPremiumPets = Object.keys(stable.premiumPets).length;
+ const expectedTotal = numberOfPremiumPotions * numberOfDropEggs;
expect(numberOfPremiumPets).to.be.greaterThan(0);
expect(numberOfPremiumPets).to.equal(expectedTotal);
@@ -49,10 +49,10 @@ describe('stable', () => {
describe('wackyPets', () => {
it('contains a pet for each wacky potion * each drop egg', () => {
- let numberOfWackyPotions = Object.keys(potions.wacky).length;
- let numberOfDropEggs = Object.keys(eggs.drops).length;
- let numberOfWackyPets = Object.keys(stable.wackyPets).length;
- let expectedTotal = numberOfWackyPotions * numberOfDropEggs;
+ const numberOfWackyPotions = Object.keys(potions.wacky).length;
+ const numberOfDropEggs = Object.keys(eggs.drops).length;
+ const numberOfWackyPets = Object.keys(stable.wackyPets).length;
+ const expectedTotal = numberOfWackyPotions * numberOfDropEggs;
expect(numberOfWackyPets).to.be.greaterThan(0);
expect(numberOfWackyPets).to.equal(expectedTotal);
@@ -61,8 +61,8 @@ describe('stable', () => {
describe('specialPets', () => {
it('each value is a valid translation string', () => {
- each(stable.specialPets, (pet) => {
- let string = t(pet);
+ each(stable.specialPets, pet => {
+ const string = t(pet);
expectValidTranslationString(string);
});
});
@@ -70,10 +70,10 @@ describe('stable', () => {
describe('dropMounts', () => {
it('contains a mount for each drop potion * each drop egg', () => {
- let numberOfDropPotions = Object.keys(potions.drops).length;
- let numberOfDropEggs = Object.keys(eggs.drops).length;
- let numberOfDropMounts = Object.keys(stable.dropMounts).length;
- let expectedTotal = numberOfDropPotions * numberOfDropEggs;
+ const numberOfDropPotions = Object.keys(potions.drops).length;
+ const numberOfDropEggs = Object.keys(eggs.drops).length;
+ const numberOfDropMounts = Object.keys(stable.dropMounts).length;
+ const expectedTotal = numberOfDropPotions * numberOfDropEggs;
expect(numberOfDropMounts).to.be.greaterThan(0);
expect(numberOfDropMounts).to.equal(expectedTotal);
@@ -82,10 +82,10 @@ describe('stable', () => {
describe('questMounts', () => {
it('contains a mount for each drop potion * each quest egg', () => {
- let numberOfDropPotions = Object.keys(potions.drops).length;
- let numberOfQuestEggs = Object.keys(eggs.quests).length;
- let numberOfQuestMounts = Object.keys(stable.questMounts).length;
- let expectedTotal = numberOfDropPotions * numberOfQuestEggs;
+ const numberOfDropPotions = Object.keys(potions.drops).length;
+ const numberOfQuestEggs = Object.keys(eggs.quests).length;
+ const numberOfQuestMounts = Object.keys(stable.questMounts).length;
+ const expectedTotal = numberOfDropPotions * numberOfQuestEggs;
expect(numberOfQuestMounts).to.be.greaterThan(0);
expect(numberOfQuestMounts).to.equal(expectedTotal);
@@ -94,10 +94,10 @@ describe('stable', () => {
describe('premiumMounts', () => {
it('contains a mount for each premium potion * each drop egg', () => {
- let numberOfPremiumPotions = Object.keys(potions.premium).length;
- let numberOfDropEggs = Object.keys(eggs.drops).length;
- let numberOfPremiumMounts = Object.keys(stable.premiumMounts).length;
- let expectedTotal = numberOfPremiumPotions * numberOfDropEggs;
+ const numberOfPremiumPotions = Object.keys(potions.premium).length;
+ const numberOfDropEggs = Object.keys(eggs.drops).length;
+ const numberOfPremiumMounts = Object.keys(stable.premiumMounts).length;
+ const expectedTotal = numberOfPremiumPotions * numberOfDropEggs;
expect(numberOfPremiumMounts).to.be.greaterThan(0);
expect(numberOfPremiumMounts).to.equal(expectedTotal);
@@ -106,24 +106,26 @@ describe('stable', () => {
describe('specialMounts', () => {
it('each value is a valid translation string', () => {
- each(stable.specialMounts, (mount) => {
- let string = t(mount);
+ each(stable.specialMounts, mount => {
+ const string = t(mount);
expectValidTranslationString(string);
});
});
});
- describe('petInfo', () => {
+ describe('petInfo', () => {
it('contains an entry for all pets', () => {
- let dropNumber = Object.keys(stable.dropPets).length;
- let questNumber = Object.keys(stable.questPets).length;
- let specialNumber = Object.keys(stable.specialPets).length;
- let premiumNumber = Object.keys(stable.premiumPets).length;
- let wackyNumber = Object.keys(stable.wackyPets).length;
- let allNumber = Object.keys(stable.petInfo).length;
+ const dropNumber = Object.keys(stable.dropPets).length;
+ const questNumber = Object.keys(stable.questPets).length;
+ const specialNumber = Object.keys(stable.specialPets).length;
+ const premiumNumber = Object.keys(stable.premiumPets).length;
+ const wackyNumber = Object.keys(stable.wackyPets).length;
+ const allNumber = Object.keys(stable.petInfo).length;
expect(allNumber).to.be.greaterThan(0);
- expect(allNumber).to.equal(dropNumber + questNumber + specialNumber + premiumNumber + wackyNumber);
+ expect(allNumber).to.equal(
+ dropNumber + questNumber + specialNumber + premiumNumber + wackyNumber,
+ );
});
it('contains basic information about each pet', () => {
@@ -135,13 +137,13 @@ describe('stable', () => {
});
});
- describe('mountInfo', () => {
+ describe('mountInfo', () => {
it('contains an entry for all mounts', () => {
- let dropNumber = Object.keys(stable.dropMounts).length;
- let questNumber = Object.keys(stable.questMounts).length;
- let specialNumber = Object.keys(stable.specialMounts).length;
- let premiumNumber = Object.keys(stable.premiumMounts).length;
- let allNumber = Object.keys(stable.mountInfo).length;
+ const dropNumber = Object.keys(stable.dropMounts).length;
+ const questNumber = Object.keys(stable.questMounts).length;
+ const specialNumber = Object.keys(stable.specialMounts).length;
+ const premiumNumber = Object.keys(stable.premiumMounts).length;
+ const allNumber = Object.keys(stable.mountInfo).length;
expect(allNumber).to.be.greaterThan(0);
expect(allNumber).to.equal(dropNumber + questNumber + specialNumber + premiumNumber);
diff --git a/test/content/translator.js b/test/content/translator.js
index fee9d37672..9bb0e87ed3 100644
--- a/test/content/translator.js
+++ b/test/content/translator.js
@@ -1,14 +1,14 @@
-import {STRING_ERROR_MSG, STRING_DOES_NOT_EXIST_MSG} from '../helpers/content.helper';
+import { STRING_ERROR_MSG, STRING_DOES_NOT_EXIST_MSG } from '../helpers/content.helper';
import translator from '../../website/common/script/content/translation';
describe('Translator', () => {
it('returns error message if string is not properly formatted', () => {
- let improperlyFormattedString = translator('petName', {attr: 0})();
+ const improperlyFormattedString = translator('petName', { attr: 0 })();
expect(improperlyFormattedString).to.match(STRING_ERROR_MSG);
});
it('returns an error message if string does not exist', () => {
- let stringDoesNotExist = translator('stringDoesNotExist')();
+ const stringDoesNotExist = translator('stringDoesNotExist')();
expect(stringDoesNotExist).to.match(STRING_DOES_NOT_EXIST_MSG);
});
});
diff --git a/test/helpers/api-integration/api-classes.js b/test/helpers/api-integration/api-classes.js
index f914d0d3a5..83f458f23d 100644
--- a/test/helpers/api-integration/api-classes.js
+++ b/test/helpers/api-integration/api-classes.js
@@ -1,17 +1,18 @@
/* eslint-disable no-use-before-define */
+/* eslint-disable max-classes-per-file */
import moment from 'moment';
-import { requester } from './requester';
-import {
- getDocument as getDocumentFromMongo,
- updateDocument as updateDocumentInMongo,
- unsetDocument as unsetDocumentInMongo,
-} from '../mongo';
import {
assign,
each,
isEmpty,
set,
} from 'lodash';
+import { requester } from './requester';
+import {
+ getDocument as getDocumentFromMongo,
+ updateDocument as updateDocumentInMongo,
+ unsetDocument as unsetDocumentInMongo,
+} from '../mongo';
class ApiObject {
constructor (options) {
@@ -20,7 +21,7 @@ class ApiObject {
async update (options) {
if (isEmpty(options)) {
- return;
+ return null;
}
await updateDocumentInMongo(this._docType, this, options);
@@ -32,7 +33,7 @@ class ApiObject {
async unset (options) {
if (isEmpty(options)) {
- return;
+ return null;
}
await unsetDocumentInMongo(this._docType, this, options);
@@ -43,7 +44,7 @@ class ApiObject {
}
async sync () {
- let updatedDoc = await getDocumentFromMongo(this._docType, this);
+ const updatedDoc = await getDocumentFromMongo(this._docType, this);
assign(this, updatedDoc);
@@ -57,7 +58,7 @@ export class ApiUser extends ApiObject {
this._docType = 'users';
- let _requester = requester(this);
+ const _requester = requester(this);
this.get = _requester.get;
this.post = _requester.post;
@@ -74,10 +75,10 @@ export class ApiGroup extends ApiObject {
}
async addChat (chat) {
- let group = this;
+ const group = this;
if (!chat) {
- chat = {
+ chat = { // eslint-disable-line no-param-reassign
id: 'Test_ID',
text: 'Test message',
flagCount: 0,
@@ -91,13 +92,13 @@ export class ApiGroup extends ApiObject {
};
}
- let update = { chat };
+ const update = { chat };
- return await this.update(update);
+ return this.update(update);
}
async createCancelledSubscription () {
- let update = {
+ const update = {
purchased: {
plan: {
customerId: 'example-customer',
@@ -106,7 +107,7 @@ export class ApiGroup extends ApiObject {
},
};
- return await this.update(update);
+ return this.update(update);
}
}
diff --git a/test/helpers/api-integration/external-server.js b/test/helpers/api-integration/external-server.js
index 33991240f8..b947db3f11 100644
--- a/test/helpers/api-integration/external-server.js
+++ b/test/helpers/api-integration/external-server.js
@@ -1,22 +1,22 @@
-'use strict';
-let express = require('express');
-let uuid = require('uuid');
-let bodyParser = require('body-parser');
-let app = express();
-let server = require('http').createServer(app);
+const express = require('express');
+const uuid = require('uuid');
+const bodyParser = require('body-parser');
+
+const app = express();
+const server = require('http').createServer(app);
const PORT = process.env.TEST_WEBHOOK_APP_PORT || 3099; // eslint-disable-line no-process-env
-let webhookData = {};
+const webhookData = {};
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(bodyParser.json());
-app.post('/webhooks/:id', function (req, res) {
- let id = req.params.id;
+app.post('/webhooks/:id', (req, res) => {
+ const { id } = req.params;
if (!webhookData[id]) {
webhookData[id] = [];
@@ -29,9 +29,9 @@ app.post('/webhooks/:id', function (req, res) {
// Helps close down server from within mocha test
// See http://stackoverflow.com/a/37054753/2601552
-let sockets = {};
-server.on('connection', (socket) => {
- let id = uuid.v4();
+const sockets = {};
+server.on('connection', socket => {
+ const id = uuid.v4();
sockets[id] = socket;
socket.once('close', () => {
@@ -40,16 +40,16 @@ server.on('connection', (socket) => {
});
function start () {
- return new Promise((resolve) => {
+ return new Promise(resolve => {
server.listen(PORT, resolve);
});
}
function close () {
- return new Promise((resolve) => {
+ return new Promise(resolve => {
server.close(resolve);
- Object.keys(sockets).forEach((socket) => {
+ Object.keys(sockets).forEach(socket => {
sockets[socket].end();
});
});
diff --git a/test/helpers/api-integration/requester.js b/test/helpers/api-integration/requester.js
index 2b18de8bac..a01aa1e227 100644
--- a/test/helpers/api-integration/requester.js
+++ b/test/helpers/api-integration/requester.js
@@ -10,8 +10,9 @@ let apiVersion;
// Sets up an object that can make all REST requests
// If a user is passed in, the uuid and api token of
// the user are used to make the requests
-export function requester (user = {}, additionalSets = {}) {
- additionalSets = cloneDeep(additionalSets); // cloning because it could be modified later to set cookie
+export function requester (user = {}, additionalSets = {}) { // eslint-disable-line import/prefer-default-export, max-len
+ // cloning because it could be modified later to set cookie
+ additionalSets = cloneDeep(additionalSets); // eslint-disable-line no-param-reassign
return {
get: _requestMaker(user, 'get', additionalSets),
@@ -21,58 +22,64 @@ export function requester (user = {}, additionalSets = {}) {
};
}
-requester.setApiVersion = (version) => {
+requester.setApiVersion = version => {
apiVersion = version;
};
function _requestMaker (user, method, additionalSets = {}) {
if (!apiVersion) throw new Error('apiVersion not set');
- return (route, send, query) => {
- return new Promise((resolve, reject) => {
- let url = `http://localhost:${API_TEST_SERVER_PORT}`;
+ return (route, send, query) => new Promise((resolve, reject) => {
+ let url = `http://localhost:${API_TEST_SERVER_PORT}`;
- // do not prefix with api/apiVersion requests to top level routes like dataexport, payments and emails
- if (route.indexOf('/email') === 0 || route.indexOf('/export') === 0 || route.indexOf('/paypal') === 0 || route.indexOf('/amazon') === 0 || route.indexOf('/stripe') === 0 || route.indexOf('/qr-code') === 0) {
- url += `${route}`;
- } else {
- url += `/api/${apiVersion}${route}`;
- }
+ // do not prefix with api/apiVersion requests to top level routes
+ // like dataexport, payments and emails
+ if (
+ route.indexOf('/email') === 0
+ || route.indexOf('/export') === 0
+ || route.indexOf('/paypal') === 0
+ || route.indexOf('/amazon') === 0
+ || route.indexOf('/stripe') === 0
+ || route.indexOf('/qr-code') === 0
+ ) {
+ url += `${route}`;
+ } else {
+ url += `/api/${apiVersion}${route}`;
+ }
- let request = superagent[method](url)
- .accept('application/json');
-
- if (user && user._id && user.apiToken) {
- request
- .set('x-api-user', user._id)
- .set('x-api-key', user.apiToken);
- }
-
- if (!isEmpty(additionalSets)) {
- request.set(additionalSets);
- }
+ const request = superagent[method](url)
+ .accept('application/json');
+ if (user && user._id && user.apiToken) {
request
- .query(query)
- .send(send)
- .end((err, response) => {
- if (err) {
- if (!err.response) return reject(err);
+ .set('x-api-user', user._id)
+ .set('x-api-key', user.apiToken);
+ }
- let parsedError = _parseError(err);
+ if (!isEmpty(additionalSets)) {
+ request.set(additionalSets);
+ }
- return reject(parsedError);
- }
+ request
+ .query(query)
+ .send(send)
+ .end((err, response) => {
+ if (err) {
+ if (!err.response) return reject(err);
- resolve(_parseRes(response));
- });
- });
- };
+ const parsedError = _parseError(err);
+
+ return reject(parsedError);
+ }
+
+ return resolve(_parseRes(response));
+ });
+ });
}
function _parseRes (res) {
- let contentType = res.headers['content-type'] || '';
- let contentDisposition = res.headers['content-disposition'] || '';
+ const contentType = res.headers['content-type'] || '';
+ const contentDisposition = res.headers['content-disposition'] || '';
if (contentType.indexOf('json') === -1) { // not a json response
return res.text;
@@ -84,16 +91,17 @@ function _parseRes (res) {
if (apiVersion === 'v2') {
return res.body;
- } else if (apiVersion === 'v3' || apiVersion === 'v4') {
+ } if (apiVersion === 'v3' || apiVersion === 'v4') {
if (res.body.message) {
return {
data: res.body.data,
message: res.body.message,
};
- } else {
- return res.body.data;
}
+ return res.body.data;
}
+
+ return null;
}
function _parseError (err) {
diff --git a/test/helpers/api-integration/v3/index.js b/test/helpers/api-integration/v3/index.js
index 8ec89f9313..44f6dd179d 100644
--- a/test/helpers/api-integration/v3/index.js
+++ b/test/helpers/api-integration/v3/index.js
@@ -1,13 +1,14 @@
/* eslint-disable no-use-before-define */
// Import requester function, set it up for v3, export it
import { requester } from '../requester';
-requester.setApiVersion('v3');
-export { requester };
import server from '../external-server';
+
+requester.setApiVersion('v3');
+export { requester };
export { server };
export { translate } from '../../translate';
export { checkExistence, getProperty, resetHabiticaDB } from '../../mongo';
-export * from './object-generators';
+export * from './object-generators';
export { sleep } from '../../sleep';
diff --git a/test/helpers/api-integration/v3/object-generators.js b/test/helpers/api-integration/v3/object-generators.js
index fc06344c9e..e713c1084c 100644
--- a/test/helpers/api-integration/v3/object-generators.js
+++ b/test/helpers/api-integration/v3/object-generators.js
@@ -20,18 +20,18 @@ import * as Tasks from '../../../../website/server/models/task';
// Example: generateUser({}, { username: 'TestName' }) adds user
// with the 'TestName' username.
export async function generateUser (update = {}, overrides = {}) {
- let username = overrides.username || (Date.now() + generateUUID()).substring(0, 20);
- let password = overrides.password || 'password';
- let email = overrides.email || `${username}@example.com`;
+ const username = overrides.username || (Date.now() + generateUUID()).substring(0, 20);
+ const password = overrides.password || 'password';
+ const email = overrides.email || `${username}@example.com`;
- let user = await requester().post('/user/auth/local/register', {
+ const user = await requester().post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let apiUser = new ApiUser(user);
+ const apiUser = new ApiUser(user);
await apiUser.update(update);
@@ -39,29 +39,29 @@ export async function generateUser (update = {}, overrides = {}) {
}
export async function generateHabit (update = {}) {
- let type = 'habit';
- let task = new Tasks[type](update);
+ const type = 'habit';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateDaily (update = {}) {
- let type = 'daily';
- let task = new Tasks[type](update);
+ const type = 'daily';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateReward (update = {}) {
- let type = 'reward';
- let task = new Tasks[type](update);
+ const type = 'reward';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateTodo (update = {}) {
- let type = 'todo';
- let task = new Tasks[type](update);
+ const type = 'todo';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
@@ -75,8 +75,8 @@ export async function generateGroup (leader, details = {}, update = {}) {
details.privacy = details.privacy || 'private';
details.name = details.name || 'test group';
- let group = await leader.post('/groups', details);
- let apiGroup = new ApiGroup(group);
+ const group = await leader.post('/groups', details);
+ const apiGroup = new ApiGroup(group);
await apiGroup.update(update);
@@ -86,7 +86,8 @@ export async function generateGroup (leader, details = {}, update = {}) {
// This is generate group + the ability to create
// real users to populate it. The settings object
// takes in:
-// members: Number - the number of group members to create. Defaults to 0. Does not include group leader.
+// members: Number - the number of group members to create.
+// Defaults to 0. Does not include group leader.
// inivtes: Number - the number of users to create and invite to the group. Defaults to 0.
// groupDetails: Object - how to initialize the group
// leaderDetails: Object - defaults for the leader, defaults with a gem balance so the user
@@ -98,42 +99,36 @@ export async function generateGroup (leader, details = {}, update = {}) {
// leader: the leader user object
// group: the group object
export async function createAndPopulateGroup (settings = {}) {
- let numberOfMembers = settings.members || 0;
- let numberOfInvites = settings.invites || 0;
- let groupDetails = settings.groupDetails;
- let leaderDetails = settings.leaderDetails || { balance: 10 };
+ const numberOfMembers = settings.members || 0;
+ const numberOfInvites = settings.invites || 0;
+ const { groupDetails } = settings;
+ const leaderDetails = settings.leaderDetails || { balance: 10 };
- let groupLeader = await generateUser(leaderDetails);
- let group = await generateGroup(groupLeader, groupDetails);
+ const groupLeader = await generateUser(leaderDetails);
+ const group = await generateGroup(groupLeader, groupDetails);
const groupMembershipTypes = {
- party: { 'party._id': group._id},
+ party: { 'party._id': group._id },
guild: { guilds: [group._id] },
};
- let members = await Promise.all(
- times(numberOfMembers, () => {
- return generateUser(groupMembershipTypes[group.type]);
- })
+ const members = await Promise.all(
+ times(numberOfMembers, () => generateUser(groupMembershipTypes[group.type])),
);
- await group.update({ memberCount: numberOfMembers + 1});
+ await group.update({ memberCount: numberOfMembers + 1 });
- let invitees = await Promise.all(
- times(numberOfInvites, () => {
- return generateUser();
- })
+ const invitees = await Promise.all(
+ times(numberOfInvites, () => generateUser()),
);
- let invitationPromises = invitees.map((invitee) => {
- return groupLeader.post(`/groups/${group._id}/invite`, {
- uuids: [invitee._id],
- });
- });
+ const invitationPromises = invitees.map(invitee => groupLeader.post(`/groups/${group._id}/invite`, {
+ uuids: [invitee._id],
+ }));
await Promise.all(invitationPromises);
- await Promise.all(invitees.map((invitee) => invitee.sync()));
+ await Promise.all(invitees.map(invitee => invitee.sync()));
return {
groupLeader,
@@ -155,8 +150,8 @@ export async function generateChallenge (challengeCreator, group, details = {},
details.prize = details.prize || 0;
details.official = details.official || false;
- let challenge = await challengeCreator.post('/challenges', details);
- let apiChallenge = new ApiChallenge(challenge);
+ const challenge = await challengeCreator.post('/challenges', details);
+ const apiChallenge = new ApiChallenge(challenge);
await apiChallenge.update(update);
diff --git a/test/helpers/api-integration/v4/index.js b/test/helpers/api-integration/v4/index.js
index ff8d48e5ec..fad9fe4556 100644
--- a/test/helpers/api-integration/v4/index.js
+++ b/test/helpers/api-integration/v4/index.js
@@ -1,13 +1,14 @@
/* eslint-disable no-use-before-define */
// Import requester function, set it up for v4, export it
import { requester } from '../requester';
-requester.setApiVersion('v4');
-export { requester };
import server from '../external-server';
+
+requester.setApiVersion('v4');
+export { requester };
export { server };
export { translate } from '../../translate';
export { checkExistence, getProperty, resetHabiticaDB } from '../../mongo';
-export * from './object-generators';
+export * from './object-generators';
export { sleep } from '../../sleep';
diff --git a/test/helpers/api-integration/v4/object-generators.js b/test/helpers/api-integration/v4/object-generators.js
index 1c215de361..99030f834f 100644
--- a/test/helpers/api-integration/v4/object-generators.js
+++ b/test/helpers/api-integration/v4/object-generators.js
@@ -14,18 +14,18 @@ import * as Tasks from '../../../../website/server/models/task';
// , you can do so by passing in the full path as a string:
// { 'items.eggs.Wolf': 10 }
export async function generateUser (update = {}) {
- let username = (Date.now() + generateUUID()).substring(0, 20);
- let password = 'password';
- let email = `${username}@example.com`;
+ const username = (Date.now() + generateUUID()).substring(0, 20);
+ const password = 'password';
+ const email = `${username}@example.com`;
- let user = await requester().post('/user/auth/local/register', {
+ const user = await requester().post('/user/auth/local/register', {
username,
email,
password,
confirmPassword: password,
});
- let apiUser = new ApiUser(user);
+ const apiUser = new ApiUser(user);
await apiUser.update(update);
@@ -33,29 +33,29 @@ export async function generateUser (update = {}) {
}
export async function generateHabit (update = {}) {
- let type = 'habit';
- let task = new Tasks[type](update);
+ const type = 'habit';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateDaily (update = {}) {
- let type = 'daily';
- let task = new Tasks[type](update);
+ const type = 'daily';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateReward (update = {}) {
- let type = 'reward';
- let task = new Tasks[type](update);
+ const type = 'reward';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
export async function generateTodo (update = {}) {
- let type = 'todo';
- let task = new Tasks[type](update);
+ const type = 'todo';
+ const task = new Tasks[type](update);
await task.save({ validateBeforeSave: false });
return task;
}
@@ -69,8 +69,8 @@ export async function generateGroup (leader, details = {}, update = {}) {
details.privacy = details.privacy || 'private';
details.name = details.name || 'test group';
- let group = await leader.post('/groups', details);
- let apiGroup = new ApiGroup(group);
+ const group = await leader.post('/groups', details);
+ const apiGroup = new ApiGroup(group);
await apiGroup.update(update);
@@ -80,7 +80,8 @@ export async function generateGroup (leader, details = {}, update = {}) {
// This is generate group + the ability to create
// real users to populate it. The settings object
// takes in:
-// members: Number - the number of group members to create. Defaults to 0. Does not include group leader.
+// members: Number - the number of group members to create.
+// Defaults to 0. Does not include group leader.
// inivtes: Number - the number of users to create and invite to the group. Defaults to 0.
// groupDetails: Object - how to initialize the group
// leaderDetails: Object - defaults for the leader, defaults with a gem balance so the user
@@ -92,42 +93,36 @@ export async function generateGroup (leader, details = {}, update = {}) {
// leader: the leader user object
// group: the group object
export async function createAndPopulateGroup (settings = {}) {
- let numberOfMembers = settings.members || 0;
- let numberOfInvites = settings.invites || 0;
- let groupDetails = settings.groupDetails;
- let leaderDetails = settings.leaderDetails || { balance: 10 };
+ const numberOfMembers = settings.members || 0;
+ const numberOfInvites = settings.invites || 0;
+ const { groupDetails } = settings;
+ const leaderDetails = settings.leaderDetails || { balance: 10 };
- let groupLeader = await generateUser(leaderDetails);
- let group = await generateGroup(groupLeader, groupDetails);
+ const groupLeader = await generateUser(leaderDetails);
+ const group = await generateGroup(groupLeader, groupDetails);
const groupMembershipTypes = {
- party: { 'party._id': group._id},
+ party: { 'party._id': group._id },
guild: { guilds: [group._id] },
};
- let members = await Promise.all(
- times(numberOfMembers, () => {
- return generateUser(groupMembershipTypes[group.type]);
- })
+ const members = await Promise.all(
+ times(numberOfMembers, () => generateUser(groupMembershipTypes[group.type])),
);
- await group.update({ memberCount: numberOfMembers + 1});
+ await group.update({ memberCount: numberOfMembers + 1 });
- let invitees = await Promise.all(
- times(numberOfInvites, () => {
- return generateUser();
- })
+ const invitees = await Promise.all(
+ times(numberOfInvites, () => generateUser()),
);
- let invitationPromises = invitees.map((invitee) => {
- return groupLeader.post(`/groups/${group._id}/invite`, {
- uuids: [invitee._id],
- });
- });
+ const invitationPromises = invitees.map(invitee => groupLeader.post(`/groups/${group._id}/invite`, {
+ uuids: [invitee._id],
+ }));
await Promise.all(invitationPromises);
- await Promise.all(invitees.map((invitee) => invitee.sync()));
+ await Promise.all(invitees.map(invitee => invitee.sync()));
return {
groupLeader,
@@ -149,8 +144,8 @@ export async function generateChallenge (challengeCreator, group, details = {},
details.prize = details.prize || 0;
details.official = details.official || false;
- let challenge = await challengeCreator.post('/challenges', details);
- let apiChallenge = new ApiChallenge(challenge);
+ const challenge = await challengeCreator.post('/challenges', details);
+ const apiChallenge = new ApiChallenge(challenge);
await apiChallenge.update(update);
diff --git a/test/helpers/api-unit.helper.js b/test/helpers/api-unit.helper.js
index b43389bf21..6ca56abb5c 100644
--- a/test/helpers/api-unit.helper.js
+++ b/test/helpers/api-unit.helper.js
@@ -1,16 +1,17 @@
import '../../website/server/libs/i18n';
import mongoose from 'mongoose';
import defaultsDeep from 'lodash/defaultsDeep';
+import moment from 'moment';
import { model as User } from '../../website/server/models/user';
import { model as Group } from '../../website/server/models/group';
import { model as Challenge } from '../../website/server/models/challenge';
import mongo from './mongo'; // eslint-disable-line
-import moment from 'moment';
import i18n from '../../website/common/script/i18n';
import * as Tasks from '../../website/server/models/task';
+
export { translationCheck } from './translate';
-afterEach((done) => {
+afterEach(done => {
sandbox.restore();
mongoose.connection.dropDatabase(done);
});
@@ -30,7 +31,7 @@ export function generateChallenge (options = {}) {
}
export function generateRes (options = {}) {
- let defaultRes = {
+ const defaultRes = {
json: sandbox.stub(),
locals: {
user: generateUser(options.localsUser),
@@ -51,7 +52,7 @@ export function generateRes (options = {}) {
}
export function generateReq (options = {}) {
- let defaultReq = {
+ const defaultReq = {
body: {},
query: {},
headers: {},
@@ -71,43 +72,43 @@ export function generateNext (func) {
}
export function generateHistory (days) {
- let history = [];
- let now = Number(moment().toDate());
+ const history = [];
+ const now = Number(moment().toDate());
while (days > 0) {
history.push({
value: days,
date: Number(moment(now).subtract(days, 'days').toDate()),
});
- days--;
+ days -= 1; // eslint-disable-line no-param-reassign
}
return history;
}
export function generateTodo (user) {
- let todo = {
+ const todo = {
text: 'test todo',
type: 'todo',
value: 0,
completed: false,
};
- let task = new Tasks.todo(Tasks.Task.sanitize(todo)); // eslint-disable-line new-cap
+ const task = new Tasks.todo(Tasks.Task.sanitize(todo)); // eslint-disable-line new-cap
task.userId = user._id;
return task;
}
export function generateDaily (user) {
- let daily = {
+ const daily = {
text: 'test daily',
type: 'daily',
value: 0,
completed: false,
};
- let task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
+ const task = new Tasks.daily(Tasks.Task.sanitize(daily)); // eslint-disable-line new-cap
task.userId = user._id;
return task;
@@ -117,7 +118,7 @@ export function defer () {
let resolve;
let reject;
- let promise = new Promise((resolveParam, rejectParam) => {
+ const promise = new Promise((resolveParam, rejectParam) => {
resolve = resolveParam;
reject = rejectParam;
});
diff --git a/test/helpers/common.helper.js b/test/helpers/common.helper.js
index f594e15cd0..4a079a5530 100644
--- a/test/helpers/common.helper.js
+++ b/test/helpers/common.helper.js
@@ -7,35 +7,36 @@ import {
RewardSchema,
TodoSchema,
} from '../../website/server/models/task';
-export {translate} from './translate';
+
+export { translate } from './translate';
export function generateUser (options = {}) {
- let user = new User(options).toObject();
+ const user = new User(options).toObject();
return user;
}
export function generateDaily (options = {}) {
- let Daily = mongoose.model('Daily', DailySchema);
+ const Daily = mongoose.model('Daily', DailySchema);
return new Daily(options).toObject();
}
export function generateHabit (options = {}) {
- let Habit = mongoose.model('Habit', HabitSchema);
+ const Habit = mongoose.model('Habit', HabitSchema);
return new Habit(options).toObject();
}
export function generateReward (options = {}) {
- let Reward = mongoose.model('Reward', RewardSchema);
+ const Reward = mongoose.model('Reward', RewardSchema);
return new Reward(options).toObject();
}
export function generateTodo (options = {}) {
- let Todo = mongoose.model('Todo', TodoSchema);
+ const Todo = mongoose.model('Todo', TodoSchema);
return new Todo(options).toObject();
}
diff --git a/test/helpers/content.helper.js b/test/helpers/content.helper.js
index 0470f04114..6bed9dd27d 100644
--- a/test/helpers/content.helper.js
+++ b/test/helpers/content.helper.js
@@ -1,5 +1,6 @@
-require('./globals.helper');
import i18n from '../../website/common/script/i18n';
+
+require('./globals.helper');
i18n.translations = require('../../website/server/libs/i18n').translations;
export const STRING_ERROR_MSG = /^Error processing the string ".*". Please see Help > Report a Bug.$/;
@@ -8,7 +9,7 @@ export const STRING_DOES_NOT_EXIST_MSG = /^String '.*' not found.$/;
export function expectValidTranslationString (attribute) {
expect(attribute).to.be.a('function');
- let translatedString = attribute();
+ const translatedString = attribute();
expect(translatedString.trim()).to.not.be.empty;
expect(translatedString).to.not.contain('function func(lang)');
diff --git a/test/helpers/globals.helper.js b/test/helpers/globals.helper.js
index c59e27ed4f..960149e7db 100644
--- a/test/helpers/globals.helper.js
+++ b/test/helpers/globals.helper.js
@@ -9,11 +9,14 @@ global._ = require('lodash');
global.chai = require('chai');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));
+
global.expect = chai.expect;
global.sinon = require('sinon');
-let sinonStubPromise = require('sinon-stub-promise');
+const sinonStubPromise = require('sinon-stub-promise');
+
sinonStubPromise(global.sinon);
global.sandbox = sinon.createSandbox();
const setupNconf = require('../../website/server/libs/setupNconf');
+
setupNconf('./config.json.example');
diff --git a/test/helpers/mongo.js b/test/helpers/mongo.js
index ca2af9ce45..701f553ece 100644
--- a/test/helpers/mongo.js
+++ b/test/helpers/mongo.js
@@ -1,20 +1,20 @@
import mongoose from 'mongoose';
-import { TAVERN_ID } from '../../website/server/models/group';
import { get } from 'lodash';
+import { TAVERN_ID } from '../../website/server/models/group';
// Useful for checking things that have been deleted,
// but you no longer have access to,
// like private parties or users
export async function checkExistence (collectionName, id) {
return new Promise((resolve, reject) => {
- let collection = mongoose.connection.db.collection(collectionName);
+ const collection = mongoose.connection.db.collection(collectionName);
- collection.find({_id: id}, {_id: 1}).limit(1).toArray((findError, docs) => {
+ collection.find({ _id: id }, { _id: 1 }).limit(1).toArray((findError, docs) => {
if (findError) return reject(findError);
- let exists = docs.length > 0;
+ const exists = docs.length > 0;
- resolve(exists);
+ return resolve(exists);
});
});
}
@@ -23,12 +23,12 @@ export async function checkExistence (collectionName, id) {
// and thus unavailable to the client
export async function getProperty (collectionName, id, path) {
return new Promise((resolve, reject) => {
- let collection = mongoose.connection.db.collection(collectionName);
+ const collection = mongoose.connection.db.collection(collectionName);
- collection.find({_id: id}, {[path]: 1}).limit(1).toArray((findError, docs) => {
+ collection.find({ _id: id }, { [path]: 1 }).limit(1).toArray((findError, docs) => {
if (findError) return reject(findError);
- resolve(get(docs[0], path));
+ return resolve(get(docs[0], path));
});
});
}
@@ -37,17 +37,17 @@ export async function getProperty (collectionName, id, path) {
// resets the db to an empty state and creates a tavern document
export async function resetHabiticaDB () {
return new Promise((resolve, reject) => {
- mongoose.connection.dropDatabase((dbErr) => {
+ mongoose.connection.dropDatabase(dbErr => {
if (dbErr) return reject(dbErr);
- let groups = mongoose.connection.db.collection('groups');
- let users = mongoose.connection.db.collection('users');
+ const groups = mongoose.connection.db.collection('groups');
+ const users = mongoose.connection.db.collection('users');
- users.count({_id: '7bde7864-ebc5-4ee2-a4b7-1070d464cdb0'}, (err, count) => {
+ return users.count({ _id: '7bde7864-ebc5-4ee2-a4b7-1070d464cdb0' }, (err, count) => {
if (err) return reject(err);
if (count > 0) return resolve();
// create the leader for the tavern
- users.insertOne({
+ return users.insertOne({
_id: '7bde7864-ebc5-4ee2-a4b7-1070d464cdb0',
apiToken: TAVERN_ID,
auth: {
@@ -59,15 +59,15 @@ export async function resetHabiticaDB () {
passwordHashMethod: 'bcrypt',
},
},
- }, (insertErr) => {
+ }, insertErr => {
if (insertErr) return reject(insertErr);
// For some mysterious reason after a dropDatabase there can still be a group...
- groups.count({_id: TAVERN_ID}, (err2, count2) => {
+ return groups.count({ _id: TAVERN_ID }, (err2, count2) => {
if (err2) return reject(err2);
if (count2 > 0) return resolve();
- groups.insertOne({
+ return groups.insertOne({
_id: TAVERN_ID,
chat: [],
leader: '7bde7864-ebc5-4ee2-a4b7-1070d464cdb0', // Siena Leslie
@@ -75,10 +75,10 @@ export async function resetHabiticaDB () {
type: 'guild',
privacy: 'public',
memberCount: 0,
- }, (insertErr2) => {
+ }, insertErr2 => {
if (insertErr2) return reject(insertErr2);
- resolve();
+ return resolve();
});
});
});
@@ -88,10 +88,10 @@ export async function resetHabiticaDB () {
}
export async function updateDocument (collectionName, doc, update) {
- let collection = mongoose.connection.db.collection(collectionName);
+ const collection = mongoose.connection.db.collection(collectionName);
- return new Promise((resolve) => {
- collection.updateOne({ _id: doc._id }, { $set: update }, (updateErr) => {
+ return new Promise(resolve => {
+ collection.updateOne({ _id: doc._id }, { $set: update }, updateErr => {
if (updateErr) throw new Error(`Error updating ${collectionName}: ${updateErr}`);
resolve();
});
@@ -101,10 +101,10 @@ export async function updateDocument (collectionName, doc, update) {
// Unset a property in the database.
// Useful for testing.
export async function unsetDocument (collectionName, doc, update) {
- let collection = mongoose.connection.db.collection(collectionName);
+ const collection = mongoose.connection.db.collection(collectionName);
- return new Promise((resolve) => {
- collection.updateOne({ _id: doc._id }, { $unset: update }, (updateErr) => {
+ return new Promise(resolve => {
+ collection.updateOne({ _id: doc._id }, { $unset: update }, updateErr => {
if (updateErr) throw new Error(`Error updating ${collectionName}: ${updateErr}`);
resolve();
});
@@ -112,9 +112,9 @@ export async function unsetDocument (collectionName, doc, update) {
}
export async function getDocument (collectionName, doc) {
- let collection = mongoose.connection.db.collection(collectionName);
+ const collection = mongoose.connection.db.collection(collectionName);
- return new Promise((resolve) => {
+ return new Promise(resolve => {
collection.findOne({ _id: doc._id }, (lookupErr, found) => {
if (lookupErr) throw new Error(`Error looking up ${collectionName}: ${lookupErr}`);
resolve(found);
@@ -122,18 +122,16 @@ export async function getDocument (collectionName, doc) {
});
}
-before((done) => {
- mongoose.connection.on('open', (err) => {
+before(done => {
+ mongoose.connection.on('open', err => {
if (err) return done(err);
- resetHabiticaDB()
+ return resetHabiticaDB()
.then(() => done())
.catch(done);
});
});
-after((done) => {
- mongoose.connection.dropDatabase((err) => {
- if (err) return done(err);
- mongoose.connection.close(done);
- });
-});
+after(done => mongoose.connection.dropDatabase(err => {
+ if (err) return done(err);
+ return mongoose.connection.close(done);
+}));
diff --git a/test/helpers/sleep.js b/test/helpers/sleep.js
index 74acac27a9..deafe66fbb 100644
--- a/test/helpers/sleep.js
+++ b/test/helpers/sleep.js
@@ -1 +1 @@
-export { default as sleep } from '../../website/server/libs/sleep';
\ No newline at end of file
+export { default as sleep } from '../../website/server/libs/sleep'; // eslint-disable-line import/prefer-default-export
diff --git a/test/helpers/translate.js b/test/helpers/translate.js
index c12e97c147..1e2eab2b99 100644
--- a/test/helpers/translate.js
+++ b/test/helpers/translate.js
@@ -1,4 +1,5 @@
import i18n from '../../website/common/script/i18n';
+
i18n.translations = require('../../website/server/libs/i18n').translations;
const STRING_ERROR_MSG = 'Error processing the string. Please see Help > Report a Bug.';
@@ -8,7 +9,7 @@ const STRING_DOES_NOT_EXIST_MSG = /^String '.*' not found.$/;
// That way, if the translated string changes, the test
// will not break. NOTE: it checks against errors with string as well.
export function translate (key, variables, language) {
- let translatedString = i18n.t(key, variables, language);
+ const translatedString = i18n.t(key, variables, language);
expect(translatedString).to.not.be.empty;
expect(translatedString).to.not.eql(STRING_ERROR_MSG);
diff --git a/test/sanity/no-duplicate-translation-keys.js b/test/sanity/no-duplicate-translation-keys.js
index c5fff4ecff..eafa09db90 100644
--- a/test/sanity/no-duplicate-translation-keys.js
+++ b/test/sanity/no-duplicate-translation-keys.js
@@ -1,21 +1,20 @@
-'use strict';
-let glob = require('glob').sync;
+const glob = require('glob').sync;
describe('Locales files', () => {
it('do not contain duplicates of any keys', () => {
- let translationFiles = glob('./website/common/locales/en/*.json');
+ const translationFiles = glob('./website/common/locales/en/*.json');
if (translationFiles.length === 0) {
throw new Error('Could not find any files in ./website/common/locales/en/*.json');
}
- let keys = {};
+ const keys = {};
- translationFiles.forEach((file) => {
- let json = require(`../.${file}`); // eslint-disable-line global-require
+ translationFiles.forEach(file => {
+ const json = require(`../.${file}`); // eslint-disable-line global-require, import/no-dynamic-require
- Object.keys(json).forEach((key) => {
+ Object.keys(json).forEach(key => {
if (keys[key]) {
throw new Error(`${key} in ${file} already exists in ${keys[key]}.`);
}
diff --git a/test/sanity/use-proper-babel-path.js b/test/sanity/use-proper-babel-path.js
index b70403bece..3388b0a528 100644
--- a/test/sanity/use-proper-babel-path.js
+++ b/test/sanity/use-proper-babel-path.js
@@ -1,20 +1,19 @@
-'use strict';
-let glob = require('glob').sync;
-let readFile = require('fs').readFileSync;
+const glob = require('glob').sync;
+const readFile = require('fs').readFileSync;
const IMPORT_REGEX = /(import|require).*common\/script/;
describe('Use Proper Babel Paths', () => {
it('uses proper babel files in website/server', () => {
- let websiteServerPaths = glob('./website/server/**/*.js');
+ const websiteServerPaths = glob('./website/server/**/*.js');
if (websiteServerPaths.length === 0) {
throw new Error('Could not find any files in website/server/**/*.js');
}
- websiteServerPaths.forEach((filePath) => {
- let file = readFile(filePath, {encoding: 'utf8'});
+ websiteServerPaths.forEach(filePath => {
+ const file = readFile(filePath, { encoding: 'utf8' });
try {
expect(file).to.not.match(IMPORT_REGEX);