From b754d51e8e85cf74912683208fb1c56650e8b313 Mon Sep 17 00:00:00 2001 From: Florent Vilmart <364568+flovilmart@users.noreply.github.com> Date: Sat, 17 Feb 2018 09:55:30 -0500 Subject: [PATCH] chore(package): update jasmine to version 3.0.0 (#4553) * chore(package): update jasmine to version 3.0.0 Closes #4547 * Fixes failing tests for jasmine 3.0 Starting 3.0, done(something) will fail * Update tests so they dont leverage var, but let and const With jasmine 3.0, the randomization engine was making the test fails because of the scope of `var` * Remove randomizer * Use same adapter for PG tests, drop table to ensure the tests dont side effect --- package.json | 2 +- spec/.eslintrc.json | 3 +- spec/AccountLockoutPolicy.spec.js | 12 +- spec/AdaptableController.spec.js | 26 +- spec/AdapterLoader.spec.js | 52 +- spec/Analytics.spec.js | 4 +- spec/AudienceRouter.spec.js | 68 +- spec/Auth.spec.js | 22 +- spec/AuthenticationAdapters.spec.js | 40 +- spec/CLI.spec.js | 4 +- spec/CacheController.spec.js | 22 +- spec/Client.spec.js | 124 ++-- spec/ClientSDK.spec.js | 2 +- spec/CloudCode.spec.js | 108 +-- spec/CloudCodeLogger.spec.js | 4 +- spec/DatabaseController.spec.js | 10 +- spec/EmailVerificationToken.spec.js | 104 +-- spec/EventEmitterPubSub.spec.js | 16 +- spec/FilesController.spec.js | 12 +- spec/GridStoreAdapter.js | 22 +- spec/HTTPRequest.spec.js | 16 +- spec/InMemoryCache.spec.js | 20 +- spec/InMemoryCacheAdapter.spec.js | 12 +- spec/InstallationsRouter.spec.js | 68 +- spec/JobSchedule.spec.js | 14 +- spec/Logger.spec.js | 6 +- spec/LoggerController.spec.js | 18 +- spec/LogsRouter.spec.js | 14 +- spec/Middlewares.spec.js | 8 +- spec/MongoStorageAdapter.spec.js | 2 +- spec/MongoTransform.spec.js | 114 ++-- spec/NullCacheAdapter.spec.js | 10 +- spec/OAuth1.spec.js | 54 +- spec/Parse.Push.spec.js | 12 +- spec/ParseACL.spec.js | 208 +++--- spec/ParseAPI.spec.js | 102 +-- spec/ParseCloudCodePublisher.spec.js | 30 +- spec/ParseFile.spec.js | 182 ++--- spec/ParseGeoPoint.spec.js | 132 ++-- spec/ParseGlobalConfig.spec.js | 2 +- spec/ParseHooks.spec.js | 38 +- spec/ParseInstallation.spec.js | 210 +++--- spec/ParseLiveQueryServer.spec.js | 488 ++++++------- spec/ParseObject.spec.js | 454 ++++++------ spec/ParsePolygon.spec.js | 4 +- spec/ParsePubSub.spec.js | 30 +- spec/ParseQuery.spec.js | 836 +++++++++++------------ spec/ParseRelation.spec.js | 232 +++---- spec/ParseRole.spec.js | 128 ++-- spec/ParseUser.spec.js | 303 ++++---- spec/ParseWebSocket.spec.js | 22 +- spec/ParseWebSocketServer.spec.js | 16 +- spec/PointerPermissions.spec.js | 2 +- spec/PostgresConfigParser.spec.js | 2 +- spec/PostgresInitOptions.spec.js | 6 +- spec/PostgresStorageAdapter.spec.js | 47 +- spec/PromiseRouter.spec.js | 4 +- spec/PublicAPI.spec.js | 2 +- spec/PurchaseValidation.spec.js | 10 +- spec/PushController.spec.js | 234 +++---- spec/PushRouter.spec.js | 16 +- spec/PushWorker.spec.js | 18 +- spec/QueryTools.spec.js | 110 +-- spec/RedisCacheAdapter.spec.js | 12 +- spec/RedisPubSub.spec.js | 8 +- spec/RestQuery.spec.js | 42 +- spec/Schema.spec.js | 58 +- spec/SchemaCache.spec.js | 6 +- spec/SessionTokenCache.spec.js | 14 +- spec/Subscription.spec.js | 24 +- spec/UserController.spec.js | 12 +- spec/ValidationAndPasswordsReset.spec.js | 66 +- spec/WinstonLoggerAdapter.spec.js | 10 +- spec/batch.spec.js | 2 +- spec/cryptoUtils.spec.js | 8 +- spec/helper.js | 44 +- spec/index.spec.js | 28 +- spec/rest.spec.js | 90 ++- spec/schemas.spec.js | 74 +- spec/support/jasmine.json | 3 +- spec/testing-routes.js | 8 +- 81 files changed, 2698 insertions(+), 2704 deletions(-) diff --git a/package.json b/package.json index 6c068de1..0e174254 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,7 @@ "eslint-plugin-flowtype": "^2.39.1", "flow-bin": "^0.66.0", "gaze": "1.1.2", - "jasmine": "2.9.0", + "jasmine": "3.0.0", "jasmine-spec-reporter": "^4.1.0", "mongodb-runner": "3.6.1", "nodemon": "1.15.0", diff --git a/spec/.eslintrc.json b/spec/.eslintrc.json index 007ccf23..b7266986 100644 --- a/spec/.eslintrc.json +++ b/spec/.eslintrc.json @@ -28,6 +28,7 @@ "arrayContains": true }, "rules": { - "no-console": [0] + "no-console": [0], + "no-var": "error" } } diff --git a/spec/AccountLockoutPolicy.spec.js b/spec/AccountLockoutPolicy.spec.js index 92f56fea..94d30672 100644 --- a/spec/AccountLockoutPolicy.spec.js +++ b/spec/AccountLockoutPolicy.spec.js @@ -2,7 +2,7 @@ const Config = require("../src/Config"); -var loginWithWrongCredentialsShouldFail = function(username, password) { +const loginWithWrongCredentialsShouldFail = function(username, password) { return new Promise((resolve, reject) => { Parse.User.logIn(username, password) .then(() => reject('login should have failed')) @@ -16,7 +16,7 @@ var loginWithWrongCredentialsShouldFail = function(username, password) { }); }; -var isAccountLockoutError = function(username, password, duration, waitTime) { +const isAccountLockoutError = function(username, password, duration, waitTime) { return new Promise((resolve, reject) => { setTimeout(() => { Parse.User.logIn(username, password) @@ -40,7 +40,7 @@ describe("Account Lockout Policy: ", () => { publicServerURL: 'http://localhost:1337/1', }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setUsername('username1'); user.setPassword('password'); return user.signUp(null); @@ -215,7 +215,7 @@ describe("Account Lockout Policy: ", () => { publicServerURL: "http://localhost:8378/1" }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setUsername("username2"); user.setPassword("failedLoginAttemptsThreshold"); return user.signUp(); @@ -248,7 +248,7 @@ describe("Account Lockout Policy: ", () => { publicServerURL: "http://localhost:8378/1" }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setUsername("username3"); user.setPassword("failedLoginAttemptsThreshold"); return user.signUp(); @@ -285,7 +285,7 @@ describe("Account Lockout Policy: ", () => { publicServerURL: "http://localhost:8378/1" }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setUsername("username4"); user.setPassword("correct password"); return user.signUp(); diff --git a/spec/AdaptableController.spec.js b/spec/AdaptableController.spec.js index 4d2ec0f1..2bb61add 100644 --- a/spec/AdaptableController.spec.js +++ b/spec/AdaptableController.spec.js @@ -1,9 +1,9 @@ -var AdaptableController = require("../src/Controllers/AdaptableController").AdaptableController; -var FilesAdapter = require("../src/Adapters/Files/FilesAdapter").default; -var FilesController = require("../src/Controllers/FilesController").FilesController; +const AdaptableController = require("../src/Controllers/AdaptableController").AdaptableController; +const FilesAdapter = require("../src/Adapters/Files/FilesAdapter").default; +const FilesController = require("../src/Controllers/FilesController").FilesController; -var MockController = function(options) { +const MockController = function(options) { AdaptableController.call(this, options); } MockController.prototype = Object.create(AdaptableController.prototype); @@ -11,8 +11,8 @@ MockController.prototype.constructor = AdaptableController; describe("AdaptableController", ()=>{ it("should use the provided adapter", (done) => { - var adapter = new FilesAdapter(); - var controller = new FilesController(adapter); + const adapter = new FilesAdapter(); + const controller = new FilesController(adapter); expect(controller.adapter).toBe(adapter); // make sure _adapter is private expect(controller._adapter).toBe(undefined); @@ -23,7 +23,7 @@ describe("AdaptableController", ()=>{ }); it("should throw when creating a new mock controller", (done) => { - var adapter = new FilesAdapter(); + const adapter = new FilesAdapter(); expect(() => { new MockController(adapter); }).toThrow(); @@ -32,9 +32,9 @@ describe("AdaptableController", ()=>{ it("should fail setting the wrong adapter to the controller", (done) => { function WrongAdapter() {} - var adapter = new FilesAdapter(); - var controller = new FilesController(adapter); - var otherAdapter = new WrongAdapter(); + const adapter = new FilesAdapter(); + const controller = new FilesController(adapter); + const otherAdapter = new WrongAdapter(); expect(() => { controller.adapter = otherAdapter; }).toThrow(); @@ -43,7 +43,7 @@ describe("AdaptableController", ()=>{ it("should fail to instantiate a controller with wrong adapter", (done) => { function WrongAdapter() {} - var adapter = new WrongAdapter(); + const adapter = new WrongAdapter(); expect(() => { new FilesController(adapter); }).toThrow(); @@ -58,7 +58,7 @@ describe("AdaptableController", ()=>{ }); it("should accept an object adapter", (done) => { - var adapter = { + const adapter = { createFile: function() { }, deleteFile: function() { }, getFileData: function() { }, @@ -77,7 +77,7 @@ describe("AdaptableController", ()=>{ AGoodAdapter.prototype.getFileData = function() { }; AGoodAdapter.prototype.getFileLocation = function() { }; - var adapter = new AGoodAdapter(); + const adapter = new AGoodAdapter(); expect(() => { new FilesController(adapter); }).not.toThrow(); diff --git a/spec/AdapterLoader.spec.js b/spec/AdapterLoader.spec.js index 2601883e..7afec6fd 100644 --- a/spec/AdapterLoader.spec.js +++ b/spec/AdapterLoader.spec.js @@ -1,16 +1,16 @@ -var loadAdapter = require("../src/Adapters/AdapterLoader").loadAdapter; -var FilesAdapter = require("@parse/fs-files-adapter").default; -var S3Adapter = require("@parse/s3-files-adapter").default; -var ParsePushAdapter = require("@parse/push-adapter").default; +const loadAdapter = require("../src/Adapters/AdapterLoader").loadAdapter; +const FilesAdapter = require("@parse/fs-files-adapter").default; +const S3Adapter = require("@parse/s3-files-adapter").default; +const ParsePushAdapter = require("@parse/push-adapter").default; const Config = require('../src/Config'); describe("AdapterLoader", ()=>{ it("should instantiate an adapter from string in object", (done) => { - var adapterPath = require('path').resolve("./spec/MockAdapter"); + const adapterPath = require('path').resolve("./spec/MockAdapter"); - var adapter = loadAdapter({ + const adapter = loadAdapter({ adapter: adapterPath, options: { key: "value", @@ -25,16 +25,16 @@ describe("AdapterLoader", ()=>{ }); it("should instantiate an adapter from string", (done) => { - var adapterPath = require('path').resolve("./spec/MockAdapter"); - var adapter = loadAdapter(adapterPath); + const adapterPath = require('path').resolve("./spec/MockAdapter"); + const adapter = loadAdapter(adapterPath); expect(adapter instanceof Object).toBe(true); done(); }); it("should instantiate an adapter from string that is module", (done) => { - var adapterPath = require('path').resolve("./src/Adapters/Files/FilesAdapter"); - var adapter = loadAdapter({ + const adapterPath = require('path').resolve("./src/Adapters/Files/FilesAdapter"); + const adapter = loadAdapter({ adapter: adapterPath }); @@ -47,7 +47,7 @@ describe("AdapterLoader", ()=>{ }); it("should instantiate an adapter from npm module", (done) => { - var adapter = loadAdapter({ + const adapter = loadAdapter({ module: '@parse/fs-files-adapter' }); @@ -60,7 +60,7 @@ describe("AdapterLoader", ()=>{ }); it("should instantiate an adapter from function/Class", (done) => { - var adapter = loadAdapter({ + const adapter = loadAdapter({ adapter: FilesAdapter }); expect(adapter instanceof FilesAdapter).toBe(true); @@ -68,52 +68,52 @@ describe("AdapterLoader", ()=>{ }); it("should instantiate the default adapter from Class", (done) => { - var adapter = loadAdapter(null, FilesAdapter); + const adapter = loadAdapter(null, FilesAdapter); expect(adapter instanceof FilesAdapter).toBe(true); done(); }); it("should use the default adapter", (done) => { - var defaultAdapter = new FilesAdapter(); - var adapter = loadAdapter(null, defaultAdapter); + const defaultAdapter = new FilesAdapter(); + const adapter = loadAdapter(null, defaultAdapter); expect(adapter instanceof FilesAdapter).toBe(true); done(); }); it("should use the provided adapter", (done) => { - var originalAdapter = new FilesAdapter(); - var adapter = loadAdapter(originalAdapter); + const originalAdapter = new FilesAdapter(); + const adapter = loadAdapter(originalAdapter); expect(adapter).toBe(originalAdapter); done(); }); it("should fail loading an improperly configured adapter", (done) => { - var Adapter = function(options) { + const Adapter = function(options) { if (!options.foo) { throw "foo is required for that adapter"; } } - var adapterOptions = { + const adapterOptions = { param: "key", doSomething: function() {} }; expect(() => { - var adapter = loadAdapter(adapterOptions, Adapter); + const adapter = loadAdapter(adapterOptions, Adapter); expect(adapter).toEqual(adapterOptions); }).not.toThrow("foo is required for that adapter"); done(); }); it("should load push adapter from options", (done) => { - var options = { + const options = { android: { senderId: 'yolo', apiKey: 'yolo' } } expect(() => { - var adapter = loadAdapter(undefined, ParsePushAdapter, options); + const adapter = loadAdapter(undefined, ParsePushAdapter, options); expect(adapter.constructor).toBe(ParsePushAdapter); expect(adapter).not.toBe(undefined); }).not.toThrow(); @@ -121,8 +121,8 @@ describe("AdapterLoader", ()=>{ }); it("should load custom push adapter from string (#3544)", (done) => { - var adapterPath = require('path').resolve("./spec/MockPushAdapter"); - var options = { + const adapterPath = require('path').resolve("./spec/MockPushAdapter"); + const options = { ios: { bundleId: 'bundle.id' } @@ -145,9 +145,9 @@ describe("AdapterLoader", ()=>{ }); it("should load S3Adapter from direct passing", (done) => { - var s3Adapter = new S3Adapter("key", "secret", "bucket") + const s3Adapter = new S3Adapter("key", "secret", "bucket") expect(() => { - var adapter = loadAdapter(s3Adapter, FilesAdapter); + const adapter = loadAdapter(s3Adapter, FilesAdapter); expect(adapter).toBe(s3Adapter); }).not.toThrow(); done(); diff --git a/spec/Analytics.spec.js b/spec/Analytics.spec.js index a4e7d87a..69d142a6 100644 --- a/spec/Analytics.spec.js +++ b/spec/Analytics.spec.js @@ -16,7 +16,7 @@ describe('AnalyticsController', () => { }) }).then(() => { expect(analyticsAdapter.trackEvent).toHaveBeenCalled(); - var lastCall = analyticsAdapter.trackEvent.calls.first(); + const lastCall = analyticsAdapter.trackEvent.calls.first(); const args = lastCall.args; expect(args[0]).toEqual('MyEvent'); expect(args[1]).toEqual({ @@ -44,7 +44,7 @@ describe('AnalyticsController', () => { }) }).then(() => { expect(analyticsAdapter.appOpened).toHaveBeenCalled(); - var lastCall = analyticsAdapter.appOpened.calls.first(); + const lastCall = analyticsAdapter.appOpened.calls.first(); const args = lastCall.args; expect(args[0]).toEqual({ dimensions: { diff --git a/spec/AudienceRouter.spec.js b/spec/AudienceRouter.spec.js index 5e36adf0..d5e635d6 100644 --- a/spec/AudienceRouter.spec.js +++ b/spec/AudienceRouter.spec.js @@ -1,20 +1,20 @@ -var auth = require('../src/Auth'); -var Config = require('../src/Config'); -var rest = require('../src/rest'); -var AudiencesRouter = require('../src/Routers/AudiencesRouter').AudiencesRouter; +const auth = require('../src/Auth'); +const Config = require('../src/Config'); +const rest = require('../src/rest'); +const AudiencesRouter = require('../src/Routers/AudiencesRouter').AudiencesRouter; describe('AudiencesRouter', () => { it('uses find condition from request.body', (done) => { - var config = Config.get('test'); - var androidAudienceRequest = { + const config = Config.get('test'); + const androidAudienceRequest = { 'name': 'Android Users', 'query': '{ "test": "android" }' }; - var iosAudienceRequest = { + const iosAudienceRequest = { 'name': 'Iphone Users', 'query': '{ "test": "ios" }' }; - var request = { + const request = { config: config, auth: auth.master(config), body: { @@ -26,7 +26,7 @@ describe('AudiencesRouter', () => { info: {} }; - var router = new AudiencesRouter(); + const router = new AudiencesRouter(); rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); @@ -35,7 +35,7 @@ describe('AudiencesRouter', () => { return router.handleFind(request); }) .then((res) => { - var results = res.response.results; + const results = res.response.results; expect(results.length).toEqual(1); done(); }) @@ -46,16 +46,16 @@ describe('AudiencesRouter', () => { }); it('uses find condition from request.query', (done) => { - var config = Config.get('test'); - var androidAudienceRequest = { + const config = Config.get('test'); + const androidAudienceRequest = { 'name': 'Android Users', 'query': '{ "test": "android" }' }; - var iosAudienceRequest = { + const iosAudienceRequest = { 'name': 'Iphone Users', 'query': '{ "test": "ios" }' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -67,7 +67,7 @@ describe('AudiencesRouter', () => { info: {} }; - var router = new AudiencesRouter(); + const router = new AudiencesRouter(); rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); @@ -76,7 +76,7 @@ describe('AudiencesRouter', () => { return router.handleFind(request); }) .then((res) => { - var results = res.response.results; + const results = res.response.results; expect(results.length).toEqual(1); done(); }) @@ -87,16 +87,16 @@ describe('AudiencesRouter', () => { }); it('query installations with limit = 0', (done) => { - var config = Config.get('test'); - var androidAudienceRequest = { + const config = Config.get('test'); + const androidAudienceRequest = { 'name': 'Android Users', 'query': '{ "test": "android" }' }; - var iosAudienceRequest = { + const iosAudienceRequest = { 'name': 'Iphone Users', 'query': '{ "test": "ios" }' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -107,7 +107,7 @@ describe('AudiencesRouter', () => { }; Config.get('test'); - var router = new AudiencesRouter(); + const router = new AudiencesRouter(); rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); @@ -116,7 +116,7 @@ describe('AudiencesRouter', () => { return router.handleFind(request); }) .then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(0); done(); }) @@ -127,16 +127,16 @@ describe('AudiencesRouter', () => { }); it('query installations with count = 1', done => { - var config = Config.get('test'); - var androidAudienceRequest = { + const config = Config.get('test'); + const androidAudienceRequest = { 'name': 'Android Users', 'query': '{ "test": "android" }' }; - var iosAudienceRequest = { + const iosAudienceRequest = { 'name': 'Iphone Users', 'query': '{ "test": "ios" }' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -146,12 +146,12 @@ describe('AudiencesRouter', () => { info: {} }; - var router = new AudiencesRouter(); + const router = new AudiencesRouter(); rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest)) .then(() => router.handleFind(request)) .then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(2); expect(response.count).toEqual(2); done(); @@ -163,16 +163,16 @@ describe('AudiencesRouter', () => { }); it('query installations with limit = 0 and count = 1', (done) => { - var config = Config.get('test'); - var androidAudienceRequest = { + const config = Config.get('test'); + const androidAudienceRequest = { 'name': 'Android Users', 'query': '{ "test": "android" }' }; - var iosAudienceRequest = { + const iosAudienceRequest = { 'name': 'Iphone Users', 'query': '{ "test": "ios" }' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -183,7 +183,7 @@ describe('AudiencesRouter', () => { info: {} }; - var router = new AudiencesRouter(); + const router = new AudiencesRouter(); rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); @@ -192,7 +192,7 @@ describe('AudiencesRouter', () => { return router.handleFind(request); }) .then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(0); expect(response.count).toEqual(2); done(); diff --git a/spec/Auth.spec.js b/spec/Auth.spec.js index e68add00..5802f72d 100644 --- a/spec/Auth.spec.js +++ b/spec/Auth.spec.js @@ -1,11 +1,11 @@ describe('Auth', () => { - var Auth = require('../src/Auth.js').Auth; + const Auth = require('../src/Auth.js').Auth; describe('getUserRoles', () => { - var auth; - var config; - var currentRoles = null; - var currentUserId = 'userId'; + let auth; + let config; + let currentRoles = null; + const currentUserId = 'userId'; beforeEach(() => { currentRoles = ['role:userId']; @@ -33,10 +33,10 @@ describe('Auth', () => { it('should get user roles from the cache', (done) => { auth.getUserRoles() .then((roles) => { - var firstSet = config.cacheController.role.set.calls.first(); + const firstSet = config.cacheController.role.set.calls.first(); expect(firstSet).toEqual(undefined); - var firstGet = config.cacheController.role.get.calls.first(); + const firstGet = config.cacheController.role.get.calls.first(); expect(firstGet.args[0]).toEqual(currentUserId); expect(roles).toEqual(currentRoles); done(); @@ -44,7 +44,7 @@ describe('Auth', () => { }); it('should only query the roles once', (done) => { - var loadRolesSpy = spyOn(auth, '_loadRoles').and.callThrough(); + const loadRolesSpy = spyOn(auth, '_loadRoles').and.callThrough(); auth.getUserRoles() .then((roles) => { expect(roles).toEqual(currentRoles); @@ -57,7 +57,7 @@ describe('Auth', () => { expect(config.cacheController.role.get.calls.count()).toEqual(1); expect(loadRolesSpy.calls.count()).toEqual(1); - var firstGet = config.cacheController.role.get.calls.first(); + const firstGet = config.cacheController.role.get.calls.first(); expect(firstGet.args[0]).toEqual(currentUserId); expect(roles).toEqual(currentRoles); done(); @@ -79,8 +79,8 @@ describe('Auth', () => { }); it('should properly handle bcrypt upgrade', (done) => { - var bcryptOriginal = require('bcrypt-nodejs'); - var bcryptNew = require('bcryptjs'); + const bcryptOriginal = require('bcrypt-nodejs'); + const bcryptNew = require('bcryptjs'); bcryptOriginal.hash('my1Long:password', null, null, function(err, res) { bcryptNew.compare('my1Long:password', res, function(err, res) { expect(res).toBeTruthy(); diff --git a/spec/AuthenticationAdapters.spec.js b/spec/AuthenticationAdapters.spec.js index f2340115..ad182ec4 100644 --- a/spec/AuthenticationAdapters.spec.js +++ b/spec/AuthenticationAdapters.spec.js @@ -1,13 +1,13 @@ -var request = require('request'); -var Config = require("../src/Config"); -var defaultColumns = require('../src/Controllers/SchemaController').defaultColumns; -var authenticationLoader = require('../src/Adapters/Auth'); -var path = require('path'); +const request = require('request'); +const Config = require("../src/Config"); +const defaultColumns = require('../src/Controllers/SchemaController').defaultColumns; +const authenticationLoader = require('../src/Adapters/Auth'); +const path = require('path'); describe('AuthenticationProviders', function() { ["facebook", "github", "instagram", "google", "linkedin", "meetup", "twitter", "janrainengage", "janraincapture", "vkontakte"].map(function(providerName){ it("Should validate structure of " + providerName, (done) => { - var provider = require("../src/Adapters/Auth/" + providerName); + const provider = require("../src/Adapters/Auth/" + providerName); jequal(typeof provider.validateAuthData, "function"); jequal(typeof provider.validateAppId, "function"); const authDataPromise = provider.validateAuthData({}, {}); @@ -20,7 +20,7 @@ describe('AuthenticationProviders', function() { }); }); - var getMockMyOauthProvider = function() { + const getMockMyOauthProvider = function() { return { authData: { id: "12345", @@ -70,18 +70,18 @@ describe('AuthenticationProviders', function() { } }); - var createOAuthUser = function(callback) { + const createOAuthUser = function(callback) { return createOAuthUserWithSessionToken(undefined, callback); } - var createOAuthUserWithSessionToken = function(token, callback) { - var jsonBody = { + const createOAuthUserWithSessionToken = function(token, callback) { + const jsonBody = { authData: { myoauth: getMockMyOauthProvider().authData } }; - var options = { + const options = { headers: {'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', 'X-Parse-Installation-Id': 'yolo', @@ -105,12 +105,12 @@ describe('AuthenticationProviders', function() { it("should create user with REST API", done => { createOAuthUser((error, response, body) => { expect(error).toBe(null); - var b = body; + const b = body; ok(b.sessionToken); expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeUndefined(); - var sessionToken = b.sessionToken; - var q = new Parse.Query("_Session"); + const sessionToken = b.sessionToken; + const q = new Parse.Query("_Session"); q.equalTo('sessionToken', sessionToken); q.first({useMasterKey: true}).then((res) => { if (!res) { @@ -128,17 +128,17 @@ describe('AuthenticationProviders', function() { }); it("should only create a single user with REST API", (done) => { - var objectId; + let objectId; createOAuthUser((error, response, body) => { expect(error).toBe(null); - var b = body + const b = body expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeUndefined(); objectId = b.objectId; createOAuthUser((error, response, body) => { expect(error).toBe(null); - var b = body; + const b = body; expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeUndefined(); expect(b.objectId).toBe(objectId); @@ -164,7 +164,7 @@ describe('AuthenticationProviders', function() { }); it("unlink and link with custom provider", (done) => { - var provider = getMockMyOauthProvider(); + const provider = getMockMyOauthProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("myoauth", { success: function(model) { @@ -186,7 +186,7 @@ describe('AuthenticationProviders', function() { ok(!provider.synchronizedExpiration, "Expiration should be cleared"); // make sure the auth data is properly deleted - var config = Config.get(Parse.applicationId); + const config = Config.get(Parse.applicationId); config.database.adapter.find('_User', { fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation), }, { objectId: model.id }, {}) @@ -244,7 +244,7 @@ describe('AuthenticationProviders', function() { } it('properly loads custom adapter', (done) => { - var validAuthData = { + const validAuthData = { id: 'hello', token: 'world' } diff --git a/spec/CLI.spec.js b/spec/CLI.spec.js index efe9ee1f..066bd644 100644 --- a/spec/CLI.spec.js +++ b/spec/CLI.spec.js @@ -3,7 +3,7 @@ import commander from '../src/cli/utils/commander'; import definitions from '../src/cli/definitions/parse-server'; import liveQueryDefinitions from '../src/cli/definitions/parse-live-query-server'; -var testDefinitions = { +const testDefinitions = { 'arg0': 'PROGRAM_ARG_0', 'arg1': { env: 'PROGRAM_ARG_1', @@ -12,7 +12,7 @@ var testDefinitions = { 'arg2': { env: 'PROGRAM_ARG_2', action: function(value) { - var intValue = parseInt(value); + const intValue = parseInt(value); if (!Number.isInteger(intValue)) { throw 'arg2 is invalid'; } diff --git a/spec/CacheController.spec.js b/spec/CacheController.spec.js index 1ad99a99..219dc89d 100644 --- a/spec/CacheController.spec.js +++ b/spec/CacheController.spec.js @@ -1,9 +1,9 @@ -var CacheController = require('../src/Controllers/CacheController.js').default; +const CacheController = require('../src/Controllers/CacheController.js').default; describe('CacheController', function() { - var FakeCacheAdapter; - var FakeAppID = 'foo'; - var KEY = 'hello'; + let FakeCacheAdapter; + const FakeAppID = 'foo'; + const KEY = 'hello'; beforeEach(() => { FakeCacheAdapter = { @@ -18,7 +18,7 @@ describe('CacheController', function() { it('should expose role and user caches', (done) => { - var cache = new CacheController(FakeCacheAdapter, FakeAppID); + const cache = new CacheController(FakeCacheAdapter, FakeAppID); expect(cache.role).not.toEqual(null); expect(cache.role.get).not.toEqual(null); @@ -31,24 +31,24 @@ describe('CacheController', function() { ['role', 'user'].forEach((cacheName) => { it('should prefix ' + cacheName + ' cache', () => { - var cache = new CacheController(FakeCacheAdapter, FakeAppID)[cacheName]; + const cache = new CacheController(FakeCacheAdapter, FakeAppID)[cacheName]; cache.put(KEY, 'world'); - var firstPut = FakeCacheAdapter.put.calls.first(); + const firstPut = FakeCacheAdapter.put.calls.first(); expect(firstPut.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); cache.get(KEY); - var firstGet = FakeCacheAdapter.get.calls.first(); + const firstGet = FakeCacheAdapter.get.calls.first(); expect(firstGet.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); cache.del(KEY); - var firstDel = FakeCacheAdapter.del.calls.first(); + const firstDel = FakeCacheAdapter.del.calls.first(); expect(firstDel.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); }); }); it('should clear the entire cache', () => { - var cache = new CacheController(FakeCacheAdapter, FakeAppID); + const cache = new CacheController(FakeCacheAdapter, FakeAppID); cache.clear(); expect(FakeCacheAdapter.clear.calls.count()).toEqual(1); @@ -64,7 +64,7 @@ describe('CacheController', function() { FakeCacheAdapter.get = () => Promise.reject(); - var cache = new CacheController(FakeCacheAdapter, FakeAppID); + const cache = new CacheController(FakeCacheAdapter, FakeAppID); cache.get('foo').then(done, () => { fail('Promise should not be rejected.'); diff --git a/spec/Client.spec.js b/spec/Client.spec.js index 14b17955..403c8e5a 100644 --- a/spec/Client.spec.js +++ b/spec/Client.spec.js @@ -1,10 +1,10 @@ -var Client = require('../src/LiveQuery/Client').Client; -var ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; +const Client = require('../src/LiveQuery/Client').Client; +const ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; describe('Client', function() { it('can be initialized', function() { - var parseWebSocket = new ParseWebSocket({}); - var client = new Client(1, parseWebSocket); + const parseWebSocket = new ParseWebSocket({}); + const client = new Client(1, parseWebSocket); expect(client.id).toBe(1); expect(client.parseWebSocket).toBe(parseWebSocket); @@ -12,7 +12,7 @@ describe('Client', function() { }); it('can push response', function() { - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; Client.pushResponse(parseWebSocket, 'message'); @@ -21,13 +21,13 @@ describe('Client', function() { }); it('can push error', function() { - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; Client.pushError(parseWebSocket, 1, 'error', true); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('error'); expect(messageJSON.error).toBe('error'); expect(messageJSON.code).toBe(1); @@ -35,13 +35,13 @@ describe('Client', function() { }); it('can add subscription information', function() { - var subscription = {}; - var fields = ['test']; - var subscriptionInfo = { + const subscription = {}; + const fields = ['test']; + const subscriptionInfo = { subscription: subscription, fields: fields } - var client = new Client(1, {}); + const client = new Client(1, {}); client.addSubscriptionInfo(1, subscriptionInfo); expect(client.subscriptionInfos.size).toBe(1); @@ -49,27 +49,27 @@ describe('Client', function() { }); it('can get subscription information', function() { - var subscription = {}; - var fields = ['test']; - var subscriptionInfo = { + const subscription = {}; + const fields = ['test']; + const subscriptionInfo = { subscription: subscription, fields: fields } - var client = new Client(1, {}); + const client = new Client(1, {}); client.addSubscriptionInfo(1, subscriptionInfo); - var subscriptionInfoAgain = client.getSubscriptionInfo(1); + const subscriptionInfoAgain = client.getSubscriptionInfo(1); expect(subscriptionInfoAgain).toBe(subscriptionInfo); }); it('can delete subscription information', function() { - var subscription = {}; - var fields = ['test']; - var subscriptionInfo = { + const subscription = {}; + const fields = ['test']; + const subscriptionInfo = { subscription: subscription, fields: fields } - var client = new Client(1, {}); + const client = new Client(1, {}); client.addSubscriptionInfo(1, subscriptionInfo); client.deleteSubscriptionInfo(1); @@ -78,7 +78,7 @@ describe('Client', function() { it('can generate ParseObject JSON with null selected field', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -86,13 +86,13 @@ describe('Client', function() { createdAt: '2015-12-07T21:27:13.746Z', ACL: 'test', }; - var client = new Client(1, {}); + const client = new Client(1, {}); expect(client._toJSONWithFields(parseObjectJSON, null)).toBe(parseObjectJSON); }); it('can generate ParseObject JSON with undefined selected field', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -100,13 +100,13 @@ describe('Client', function() { createdAt: '2015-12-07T21:27:13.746Z', ACL: 'test', }; - var client = new Client(1, {}); + const client = new Client(1, {}); expect(client._toJSONWithFields(parseObjectJSON, undefined)).toBe(parseObjectJSON); }); it('can generate ParseObject JSON with selected fields', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -115,7 +115,7 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var client = new Client(1, {}); + const client = new Client(1, {}); expect(client._toJSONWithFields(parseObjectJSON, ['test'])).toEqual({ className: 'test', @@ -128,7 +128,7 @@ describe('Client', function() { }); it('can generate ParseObject JSON with nonexistent selected fields', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -137,8 +137,8 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var client = new Client(1, {}); - var limitedParseObject = client._toJSONWithFields(parseObjectJSON, ['name']); + const client = new Client(1, {}); + const limitedParseObject = client._toJSONWithFields(parseObjectJSON, ['name']); expect(limitedParseObject).toEqual({ className: 'test', @@ -151,48 +151,48 @@ describe('Client', function() { }); it('can push connect response', function() { - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushConnect(); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('connected'); expect(messageJSON.clientId).toBe(1); }); it('can push subscribe response', function() { - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushSubscribe(2); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('subscribed'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); }); it('can push unsubscribe response', function() { - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushUnsubscribe(2); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('unsubscribed'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); }); it('can push create response', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -201,14 +201,14 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushCreate(2, parseObjectJSON); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('create'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); @@ -216,7 +216,7 @@ describe('Client', function() { }); it('can push enter response', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -225,14 +225,14 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushEnter(2, parseObjectJSON); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('enter'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); @@ -240,7 +240,7 @@ describe('Client', function() { }); it('can push update response', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -249,14 +249,14 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushUpdate(2, parseObjectJSON); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('update'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); @@ -264,7 +264,7 @@ describe('Client', function() { }); it('can push leave response', function() { - var parseObjectJSON = { + const parseObjectJSON = { key : 'value', className: 'test', objectId: 'test', @@ -273,14 +273,14 @@ describe('Client', function() { ACL: 'test', test: 'test' }; - var parseWebSocket = { + const parseWebSocket = { send: jasmine.createSpy('send') }; - var client = new Client(1, parseWebSocket); + const client = new Client(1, parseWebSocket); client.pushLeave(2, parseObjectJSON); - var lastCall = parseWebSocket.send.calls.first(); - var messageJSON = JSON.parse(lastCall.args[0]); + const lastCall = parseWebSocket.send.calls.first(); + const messageJSON = JSON.parse(lastCall.args[0]); expect(messageJSON.op).toBe('leave'); expect(messageJSON.clientId).toBe(1); expect(messageJSON.requestId).toBe(2); diff --git a/spec/ClientSDK.spec.js b/spec/ClientSDK.spec.js index 985c1e86..90766a85 100644 --- a/spec/ClientSDK.spec.js +++ b/spec/ClientSDK.spec.js @@ -1,4 +1,4 @@ -var ClientSDK = require('../src/ClientSDK'); +const ClientSDK = require('../src/ClientSDK'); describe('ClientSDK', () => { it('should properly parse the SDK versions', () => { diff --git a/spec/CloudCode.spec.js b/spec/CloudCode.spec.js index 307e97e9..6404b167 100644 --- a/spec/CloudCode.spec.js +++ b/spec/CloudCode.spec.js @@ -48,7 +48,7 @@ describe('Cloud Code', () => { res.error('You shall not pass!'); }); - var obj = new Parse.Object('BeforeSaveFail'); + const obj = new Parse.Object('BeforeSaveFail'); obj.set('foo', 'bar'); obj.save().then(() => { fail('Should not have been able to save BeforeSaveFailure class.'); @@ -80,7 +80,7 @@ describe('Cloud Code', () => { res.error(999, 'Nope'); }); - var obj = new Parse.Object('BeforeSaveFailWithErrorCode'); + const obj = new Parse.Object('BeforeSaveFailWithErrorCode'); obj.set('foo', 'bar'); obj.save().then(function() { fail('Should not have been able to save BeforeSaveFailWithErrorCode class.'); @@ -94,7 +94,7 @@ describe('Cloud Code', () => { it('basic beforeSave rejection via promise', function(done) { Parse.Cloud.beforeSave('BeforeSaveFailWithPromise', function (req, res) { - var query = new Parse.Query('Yolo'); + const query = new Parse.Query('Yolo'); query.find().then(() => { res.error('Nope'); }, () => { @@ -102,7 +102,7 @@ describe('Cloud Code', () => { }); }); - var obj = new Parse.Object('BeforeSaveFailWithPromise'); + const obj = new Parse.Object('BeforeSaveFailWithPromise'); obj.set('foo', 'bar'); obj.save().then(function() { fail('Should not have been able to save BeforeSaveFailure class.'); @@ -120,10 +120,10 @@ describe('Cloud Code', () => { res.success(); }); - var obj = new Parse.Object('BeforeSaveChanged'); + const obj = new Parse.Object('BeforeSaveChanged'); obj.set('foo', 'bar'); obj.save().then(function() { - var query = new Parse.Query('BeforeSaveChanged'); + const query = new Parse.Query('BeforeSaveChanged'); query.get(obj.id).then(function(objAgain) { expect(objAgain.get('foo')).toEqual('baz'); done(); @@ -143,7 +143,7 @@ describe('Cloud Code', () => { res.success(); }); - var obj = new Parse.Object('BeforeSaveChanged'); + const obj = new Parse.Object('BeforeSaveChanged'); obj.set('foo', 'bing'); obj.save().then(() => { expect(obj.get('foo')).toEqual('baz'); @@ -157,16 +157,16 @@ describe('Cloud Code', () => { it('test afterSave ran and created an object', function(done) { Parse.Cloud.afterSave('AfterSaveTest', function(req) { - var obj = new Parse.Object('AfterSaveProof'); + const obj = new Parse.Object('AfterSaveProof'); obj.set('proof', req.object.id); obj.save(); }); - var obj = new Parse.Object('AfterSaveTest'); + const obj = new Parse.Object('AfterSaveTest'); obj.save(); setTimeout(function() { - var query = new Parse.Query('AfterSaveProof'); + const query = new Parse.Query('AfterSaveProof'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(1); @@ -341,13 +341,13 @@ describe('Cloud Code', () => { res.success(); }); - var obj = new Parse.Object('BeforeSaveChanged'); + const obj = new Parse.Object('BeforeSaveChanged'); obj.set('foo', 'bar'); obj.save().then(function() { obj.set('foo', 'bar'); return obj.save(); }).then(function() { - var query = new Parse.Query('BeforeSaveChanged'); + const query = new Parse.Query('BeforeSaveChanged'); return query.get(obj.id).then(function(objAgain) { expect(objAgain.get('foo')).toEqual('baz'); done(); @@ -363,8 +363,8 @@ describe('Cloud Code', () => { res.error('Nope'); }); - var obj = new Parse.Object('BeforeDeleteFail'); - var id; + const obj = new Parse.Object('BeforeDeleteFail'); + let id; obj.set('foo', 'bar'); obj.save().then(() => { id = obj.id; @@ -376,7 +376,7 @@ describe('Cloud Code', () => { expect(error.code).toEqual(Parse.Error.SCRIPT_FAILED); expect(error.message).toEqual('Nope'); - var objAgain = new Parse.Object('BeforeDeleteFail', {objectId: id}); + const objAgain = new Parse.Object('BeforeDeleteFail', {objectId: id}); return objAgain.fetch(); }).then((objAgain) => { if (objAgain) { @@ -393,7 +393,7 @@ describe('Cloud Code', () => { it('basic beforeDelete rejection via promise', function(done) { Parse.Cloud.beforeSave('BeforeDeleteFailWithPromise', function (req, res) { - var query = new Parse.Query('Yolo'); + const query = new Parse.Query('Yolo'); query.find().then(() => { res.error('Nope'); }, () => { @@ -401,7 +401,7 @@ describe('Cloud Code', () => { }); }); - var obj = new Parse.Object('BeforeDeleteFailWithPromise'); + const obj = new Parse.Object('BeforeDeleteFailWithPromise'); obj.set('foo', 'bar'); obj.save().then(function() { fail('Should not have been able to save BeforeSaveFailure class.'); @@ -416,18 +416,18 @@ describe('Cloud Code', () => { it('test afterDelete ran and created an object', function(done) { Parse.Cloud.afterDelete('AfterDeleteTest', function(req) { - var obj = new Parse.Object('AfterDeleteProof'); + const obj = new Parse.Object('AfterDeleteProof'); obj.set('proof', req.object.id); obj.save(); }); - var obj = new Parse.Object('AfterDeleteTest'); + const obj = new Parse.Object('AfterDeleteTest'); obj.save().then(function() { obj.destroy(); }); setTimeout(function() { - var query = new Parse.Query('AfterDeleteProof'); + const query = new Parse.Query('AfterDeleteProof'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(1); @@ -473,7 +473,7 @@ describe('Cloud Code', () => { } expect(result.object.className).toEqual('Foo'); expect(result.object.get('x')).toEqual(2); - var bar = result.object.get('relation'); + const bar = result.object.get('relation'); expect(bar instanceof Parse.Object).toBeTruthy(); expect(bar.className).toEqual('Bar'); expect(bar.get('x')).toEqual(3); @@ -582,7 +582,7 @@ describe('Cloud Code', () => { }); Parse.Cloud.define('createBeforeSaveChangedObject', function(req, res){ - var obj = new Parse.Object('BeforeSaveChanged'); + const obj = new Parse.Object('BeforeSaveChanged'); obj.save().then(() => { res.success(obj); }) @@ -598,7 +598,7 @@ describe('Cloud Code', () => { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.beforeSave('GameScore', (req, res) => { - var object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.get('fooAgain')).toEqual('barAgain'); if (triggerTime == 0) { @@ -638,7 +638,7 @@ describe('Cloud Code', () => { res.success(); }); - var obj = new Parse.Object('BeforeSaveUnchanged'); + const obj = new Parse.Object('BeforeSaveUnchanged'); obj.set('foo', 'bar'); obj.save().then(function() { done(); @@ -653,12 +653,12 @@ describe('Cloud Code', () => { res.success(); }); - var obj = new Parse.Object('BeforeDeleteTest'); + const obj = new Parse.Object('BeforeDeleteTest'); obj.set('foo', 'bar'); obj.save().then(function() { return obj.destroy(); }).then(function() { - var objAgain = new Parse.Object('BeforeDeleteTest', obj.id); + const objAgain = new Parse.Object('BeforeDeleteTest', obj.id); return objAgain.fetch().then(fail, done); }, function(error) { fail(error); @@ -681,13 +681,13 @@ describe('Cloud Code', () => { } }); - var user = new Parse.User(); + const user = new Parse.User(); user.set("password", "asdf"); user.set("email", "asdf@example.com"); user.set("username", "zxcv"); user.signUp(null, { success: function() { - var obj = new Parse.Object('SaveTriggerUser'); + const obj = new Parse.Object('SaveTriggerUser'); obj.save().then(function() { done(); }, function(error) { @@ -855,15 +855,15 @@ describe('Cloud Code', () => { res.success(); }); - var TestObject = Parse.Object.extend("TestObject"); - var NoBeforeSaveObject = Parse.Object.extend("NoBeforeSave"); - var BeforeSaveObject = Parse.Object.extend("BeforeSaveUnchanged"); + const TestObject = Parse.Object.extend("TestObject"); + const NoBeforeSaveObject = Parse.Object.extend("NoBeforeSave"); + const BeforeSaveObject = Parse.Object.extend("BeforeSaveUnchanged"); - var aTestObject = new TestObject(); + const aTestObject = new TestObject(); aTestObject.set("foo", "bar"); aTestObject.save() .then(aTestObject => { - var aNoBeforeSaveObj = new NoBeforeSaveObject(); + const aNoBeforeSaveObj = new NoBeforeSaveObject(); aNoBeforeSaveObj.set("aTestObject", aTestObject); expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); return aNoBeforeSaveObj.save(); @@ -871,7 +871,7 @@ describe('Cloud Code', () => { .then(aNoBeforeSaveObj => { expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); - var aBeforeSaveObj = new BeforeSaveObject(); + const aBeforeSaveObj = new BeforeSaveObject(); aBeforeSaveObj.set("aTestObject", aTestObject); expect(aBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); return aBeforeSaveObj.save(); @@ -892,15 +892,15 @@ describe('Cloud Code', () => { res.success(); }); - var TestObject = Parse.Object.extend("TestObject"); - var BeforeSaveUnchangedObject = Parse.Object.extend("BeforeSaveUnchanged"); - var BeforeSaveChangedObject = Parse.Object.extend("BeforeSaveChanged"); + const TestObject = Parse.Object.extend("TestObject"); + const BeforeSaveUnchangedObject = Parse.Object.extend("BeforeSaveUnchanged"); + const BeforeSaveChangedObject = Parse.Object.extend("BeforeSaveChanged"); - var aTestObject = new TestObject(); + const aTestObject = new TestObject(); aTestObject.set("foo", "bar"); aTestObject.save() .then(aTestObject => { - var aBeforeSaveUnchangedObject = new BeforeSaveUnchangedObject(); + const aBeforeSaveUnchangedObject = new BeforeSaveUnchangedObject(); aBeforeSaveUnchangedObject.set("aTestObject", aTestObject); expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar"); return aBeforeSaveUnchangedObject.save(); @@ -908,7 +908,7 @@ describe('Cloud Code', () => { .then(aBeforeSaveUnchangedObject => { expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar"); - var aBeforeSaveChangedObject = new BeforeSaveChangedObject(); + const aBeforeSaveChangedObject = new BeforeSaveChangedObject(); aBeforeSaveChangedObject.set("aTestObject", aTestObject); expect(aBeforeSaveChangedObject.get("aTestObject").get("foo")).toEqual("bar"); return aBeforeSaveChangedObject.save(); @@ -921,21 +921,21 @@ describe('Cloud Code', () => { }); it('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => { - var TestObject = Parse.Object.extend('TestObject'); - var NoBeforeSaveObject = Parse.Object.extend('NoBeforeSave'); - var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); + const TestObject = Parse.Object.extend('TestObject'); + const NoBeforeSaveObject = Parse.Object.extend('NoBeforeSave'); + const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { - var object = req.object; + const object = req.object; object.set('before', 'save'); res.success(); }); Parse.Cloud.define('removeme', (req, res) => { - var testObject = new TestObject(); + const testObject = new TestObject(); testObject.save() .then(testObject => { - var object = new NoBeforeSaveObject({remove: testObject}); + const object = new NoBeforeSaveObject({remove: testObject}); return object.save(); }) .then(object => { @@ -948,10 +948,10 @@ describe('Cloud Code', () => { }); Parse.Cloud.define('removeme2', (req, res) => { - var testObject = new TestObject(); + const testObject = new TestObject(); testObject.save() .then(testObject => { - var object = new BeforeSaveObject({remove: testObject}); + const object = new BeforeSaveObject({remove: testObject}); return object.save(); }) .then(object => { @@ -984,11 +984,11 @@ describe('Cloud Code', () => { trying to delete a field that doesn't exists doesn't play nice */ it_exclude_dbs(['postgres'])('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => { - var TestObject = Parse.Object.extend('TestObject'); - var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); + const TestObject = Parse.Object.extend('TestObject'); + const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { - var object = req.object; + const object = req.object; object.set('before', 'save'); object.unset('remove'); res.success(); @@ -1013,11 +1013,11 @@ describe('Cloud Code', () => { }); it('should not include relation op (regression test for #1606)', done => { - var TestObject = Parse.Object.extend('TestObject'); - var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); + const TestObject = Parse.Object.extend('TestObject'); + const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); let testObj; Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { - var object = req.object; + const object = req.object; object.set('before', 'save'); testObj = new TestObject(); testObj.save().then(() => { diff --git a/spec/CloudCodeLogger.spec.js b/spec/CloudCodeLogger.spec.js index 5842cf85..72891361 100644 --- a/spec/CloudCodeLogger.spec.js +++ b/spec/CloudCodeLogger.spec.js @@ -24,7 +24,7 @@ describe("Cloud Code Logger", () => { // see helpers.js:afterEach it("should expose log to functions", done => { - var logController = new LoggerController(new WinstonLoggerAdapter()); + const logController = new LoggerController(new WinstonLoggerAdapter()); Parse.Cloud.define("loggerTest", (req, res) => { req.log.info('logTest', 'info log', { info: 'some log' }); @@ -73,7 +73,7 @@ describe("Cloud Code Logger", () => { }); it("should expose log to trigger", (done) => { - var logController = new LoggerController(new WinstonLoggerAdapter()); + const logController = new LoggerController(new WinstonLoggerAdapter()); Parse.Cloud.beforeSave("MyObject", (req, res) => { req.log.info('beforeSave MyObject', 'info log', { info: 'some log' }); diff --git a/spec/DatabaseController.spec.js b/spec/DatabaseController.spec.js index 423b18a1..43e85ccf 100644 --- a/spec/DatabaseController.spec.js +++ b/spec/DatabaseController.spec.js @@ -1,12 +1,12 @@ -var DatabaseController = require('../src/Controllers/DatabaseController.js'); -var validateQuery = DatabaseController._validateQuery; +const DatabaseController = require('../src/Controllers/DatabaseController.js'); +const validateQuery = DatabaseController._validateQuery; describe('DatabaseController', function() { describe('validateQuery', function() { it('should restructure simple cases of SERVER-13732', (done) => { - var query = {$or: [{a: 1}, {a: 2}], _rperm: {$in: ['a', 'b']}, foo: 3}; + const query = {$or: [{a: 1}, {a: 2}], _rperm: {$in: ['a', 'b']}, foo: 3}; validateQuery(query); expect(query).toEqual({$or: [{a: 1, _rperm: {$in: ['a', 'b']}, foo: 3}, {a: 2, _rperm: {$in: ['a', 'b']}, foo: 3}]}); @@ -14,7 +14,7 @@ describe('DatabaseController', function() { }); it('should not restructure SERVER-13732 queries with $nears', (done) => { - var query = {$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}}; + let query = {$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}}; validateQuery(query); expect(query).toEqual({$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}}); @@ -27,7 +27,7 @@ describe('DatabaseController', function() { it('should push refactored keys down a tree for SERVER-13732', (done) => { - var query = {a: 1, $or: [{$or: [{b: 1}, {b: 2}]}, + const query = {a: 1, $or: [{$or: [{b: 1}, {b: 2}]}, {$or: [{c: 1}, {c: 2}]}]}; validateQuery(query); expect(query).toEqual({$or: [{$or: [{b: 1, a: 1}, {b: 2, a: 1}]}, diff --git a/spec/EmailVerificationToken.spec.js b/spec/EmailVerificationToken.spec.js index d17a1e14..b6e05a29 100644 --- a/spec/EmailVerificationToken.spec.js +++ b/spec/EmailVerificationToken.spec.js @@ -7,9 +7,9 @@ const Config = require('../src/Config'); describe("Email Verification Token Expiration: ", () => { it('show the invalid verification link page, if the user clicks on the verify email link after the email verify token expires', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -48,9 +48,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('emailVerified should set to false, if the user does not verify their email before the email verify token expires', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -96,9 +96,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('if user clicks on the email verify link before email verification token expiration then show the verify email success page', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -132,9 +132,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('if user clicks on the email verify link before email verification token expiration then emailVerified should be true', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -175,9 +175,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('if user clicks on the email verify link before email verification token expiration then user should be able to login', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -219,9 +219,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('sets the _email_verify_token_expires_at and _email_verify_token fields after user SignUp', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -262,9 +262,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('unsets the _email_verify_token_expires_at and _email_verify_token fields in the User class if email verification is successful', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -314,16 +314,16 @@ describe("Email Verification Token Expiration: ", () => { }); it('clicking on the email verify link by an email VERIFIED user that was setup before enabling the expire email verify token should show email verify email success', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => {} } - var serverConfig = { + const serverConfig = { appName: 'emailVerifyToken', verifyUserEmails: true, emailAdapter: emailAdapter, @@ -370,16 +370,16 @@ describe("Email Verification Token Expiration: ", () => { }); it('clicking on the email verify link by an email UNVERIFIED user that was setup before enabling the expire email verify token should show invalid verficiation link page', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => {} } - var serverConfig = { + const serverConfig = { appName: 'emailVerifyToken', verifyUserEmails: true, emailAdapter: emailAdapter, @@ -484,11 +484,11 @@ describe("Email Verification Token Expiration: ", () => { }); it('should send a new verification email when a resend is requested and the user is UNVERIFIED', done => { - var user = new Parse.User(); - var sendEmailOptions; - var sendVerificationEmailCallCount = 0; + const user = new Parse.User(); + let sendEmailOptions; + let sendVerificationEmailCallCount = 0; let userBeforeRequest; - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; sendVerificationEmailCallCount++; @@ -560,10 +560,10 @@ describe("Email Verification Token Expiration: ", () => { }); it('should not send a new verification email when a resend is requested and the user is VERIFIED', done => { - var user = new Parse.User(); - var sendEmailOptions; - var sendVerificationEmailCallCount = 0; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + let sendVerificationEmailCallCount = 0; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; sendVerificationEmailCallCount++; @@ -624,9 +624,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('should not send a new verification email if this user does not exist', done => { - var sendEmailOptions; - var sendVerificationEmailCallCount = 0; - var emailAdapter = { + let sendEmailOptions; + let sendVerificationEmailCallCount = 0; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; sendVerificationEmailCallCount++; @@ -669,9 +669,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('should fail if no email is supplied', done => { - var sendEmailOptions; - var sendVerificationEmailCallCount = 0; - var emailAdapter = { + let sendEmailOptions; + let sendVerificationEmailCallCount = 0; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; sendVerificationEmailCallCount++; @@ -713,9 +713,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('should fail if email is not a string', done => { - var sendEmailOptions; - var sendVerificationEmailCallCount = 0; - var emailAdapter = { + let sendEmailOptions; + let sendVerificationEmailCallCount = 0; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; sendVerificationEmailCallCount++; @@ -757,9 +757,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('client should not see the _email_verify_token_expires_at field', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -800,9 +800,9 @@ describe("Email Verification Token Expiration: ", () => { }); it('emailVerified should be set to false after changing from an already verified email', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, diff --git a/spec/EventEmitterPubSub.spec.js b/spec/EventEmitterPubSub.spec.js index 546206ff..2ac94e4f 100644 --- a/spec/EventEmitterPubSub.spec.js +++ b/spec/EventEmitterPubSub.spec.js @@ -1,12 +1,12 @@ -var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; +const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; describe('EventEmitterPubSub', function() { it('can publish and subscribe', function() { - var publisher = EventEmitterPubSub.createPublisher(); - var subscriber = EventEmitterPubSub.createSubscriber(); + const publisher = EventEmitterPubSub.createPublisher(); + const subscriber = EventEmitterPubSub.createSubscriber(); subscriber.subscribe('testChannel'); // Register mock checked for subscriber - var isChecked = false; + let isChecked = false; subscriber.on('message', function(channel, message) { isChecked = true; expect(channel).toBe('testChannel'); @@ -19,12 +19,12 @@ describe('EventEmitterPubSub', function() { }); it('can unsubscribe', function() { - var publisher = EventEmitterPubSub.createPublisher(); - var subscriber = EventEmitterPubSub.createSubscriber(); + const publisher = EventEmitterPubSub.createPublisher(); + const subscriber = EventEmitterPubSub.createSubscriber(); subscriber.subscribe('testChannel'); subscriber.unsubscribe('testChannel'); // Register mock checked for subscriber - var isCalled = false; + let isCalled = false; subscriber.on('message', function() { isCalled = true; }); @@ -35,7 +35,7 @@ describe('EventEmitterPubSub', function() { }); it('can unsubscribe not subscribing channel', function() { - var subscriber = EventEmitterPubSub.createSubscriber(); + const subscriber = EventEmitterPubSub.createSubscriber(); // Make sure subscriber does not throw exception subscriber.unsubscribe('testChannel'); diff --git a/spec/FilesController.spec.js b/spec/FilesController.spec.js index 4bade0d9..3cb5f3e3 100644 --- a/spec/FilesController.spec.js +++ b/spec/FilesController.spec.js @@ -17,19 +17,19 @@ const mockAdapter = { describe("FilesController",() =>{ it("should properly expand objects", (done) => { - var config = Config.get(Parse.applicationId); - var gridStoreAdapter = new GridStoreAdapter('mongodb://localhost:27017/parse'); - var filesController = new FilesController(gridStoreAdapter) - var result = filesController.expandFilesInObject(config, function(){}); + const config = Config.get(Parse.applicationId); + const gridStoreAdapter = new GridStoreAdapter('mongodb://localhost:27017/parse'); + const filesController = new FilesController(gridStoreAdapter) + const result = filesController.expandFilesInObject(config, function(){}); expect(result).toBeUndefined(); - var fullFile = { + const fullFile = { type: '__type', url: "http://an.url" } - var anObject = { + const anObject = { aFile: fullFile } filesController.expandFilesInObject(config, anObject); diff --git a/spec/GridStoreAdapter.js b/spec/GridStoreAdapter.js index e27d59fc..2cc16fdb 100644 --- a/spec/GridStoreAdapter.js +++ b/spec/GridStoreAdapter.js @@ -1,24 +1,24 @@ -var MongoClient = require("mongodb").MongoClient; -var GridStore = require("mongodb").GridStore; +const MongoClient = require("mongodb").MongoClient; +const GridStore = require("mongodb").GridStore; -var GridStoreAdapter = require("../src/Adapters/Files/GridStoreAdapter").GridStoreAdapter; -var Config = require("../src/Config"); -var FilesController = require('../src/Controllers/FilesController').default; +const GridStoreAdapter = require("../src/Adapters/Files/GridStoreAdapter").GridStoreAdapter; +const Config = require("../src/Config"); +const FilesController = require('../src/Controllers/FilesController').default; // Small additional tests to improve overall coverage describe_only_db('mongo')("GridStoreAdapter",() =>{ it("should properly instanciate the GridStore when deleting a file", (done) => { - var databaseURI = 'mongodb://localhost:27017/parse'; - var config = Config.get(Parse.applicationId); - var gridStoreAdapter = new GridStoreAdapter(databaseURI); - var filesController = new FilesController(gridStoreAdapter); + const databaseURI = 'mongodb://localhost:27017/parse'; + const config = Config.get(Parse.applicationId); + const gridStoreAdapter = new GridStoreAdapter(databaseURI); + const filesController = new FilesController(gridStoreAdapter); // save original unlink before redefinition - var originalUnlink = GridStore.prototype.unlink; + const originalUnlink = GridStore.prototype.unlink; - var gridStoreMode; + let gridStoreMode; // new unlink method that will capture the mode in which GridStore was opened GridStore.prototype.unlink = function() { diff --git a/spec/HTTPRequest.spec.js b/spec/HTTPRequest.spec.js index 061b616f..5ea67f26 100644 --- a/spec/HTTPRequest.spec.js +++ b/spec/HTTPRequest.spec.js @@ -1,14 +1,14 @@ 'use strict'; -var httpRequest = require("../src/cloud-code/httpRequest"), +const httpRequest = require("../src/cloud-code/httpRequest"), HTTPResponse = require('../src/cloud-code/HTTPResponse').default, bodyParser = require('body-parser'), express = require("express"); -var port = 13371; -var httpRequestServer = "http://localhost:" + port; +const port = 13371; +const httpRequestServer = "http://localhost:" + port; -var app = express(); +const app = express(); app.use(bodyParser.json({ 'type': '*/*' })); app.get("/hello", function(req, res){ res.json({response: "OK"}); @@ -53,7 +53,7 @@ describe("httpRequest", () => { }); it("should do /hello with callback and promises", (done) => { - var calls = 0; + let calls = 0; httpRequest({ url: httpRequestServer + "/hello", success: function() { calls++; }, @@ -102,7 +102,7 @@ describe("httpRequest", () => { }); it("should fail on 404", (done) => { - var calls = 0; + let calls = 0; httpRequest({ url: httpRequestServer + "/404", success: function() { @@ -138,7 +138,7 @@ describe("httpRequest", () => { }) it("should post on echo", (done) => { - var calls = 0; + let calls = 0; httpRequest({ method: "POST", url: httpRequestServer + "/echo", @@ -307,7 +307,7 @@ describe("httpRequest", () => { const httpResponse = new HTTPResponse({}, new Buffer(json)); const encoded = Parse._encode(httpResponse); let foundData, foundText, foundBody = false; - for(var key in encoded) { + for(const key in encoded) { if (key == 'data') { foundData = true; } diff --git a/spec/InMemoryCache.spec.js b/spec/InMemoryCache.spec.js index 17c72d29..c5c7cd38 100644 --- a/spec/InMemoryCache.spec.js +++ b/spec/InMemoryCache.spec.js @@ -2,16 +2,16 @@ const InMemoryCache = require('../src/Adapters/Cache/InMemoryCache').default; describe('InMemoryCache', function() { - var BASE_TTL = { + const BASE_TTL = { ttl: 100 }; - var NO_EXPIRE_TTL = { + const NO_EXPIRE_TTL = { ttl: NaN }; - var KEY = 'hello'; - var KEY_2 = KEY + '_2'; + const KEY = 'hello'; + const KEY_2 = KEY + '_2'; - var VALUE = 'world'; + const VALUE = 'world'; function wait(sleep) { @@ -21,11 +21,11 @@ describe('InMemoryCache', function() { } it('should destroy a expire items in the cache', (done) => { - var cache = new InMemoryCache(BASE_TTL); + const cache = new InMemoryCache(BASE_TTL); cache.put(KEY, VALUE); - var value = cache.get(KEY); + let value = cache.get(KEY); expect(value).toEqual(VALUE); wait(BASE_TTL.ttl * 2).then(() => { @@ -36,7 +36,7 @@ describe('InMemoryCache', function() { }); it('should delete items', (done) => { - var cache = new InMemoryCache(NO_EXPIRE_TTL); + const cache = new InMemoryCache(NO_EXPIRE_TTL); cache.put(KEY, VALUE); cache.put(KEY_2, VALUE); expect(cache.get(KEY)).toEqual(VALUE); @@ -53,7 +53,7 @@ describe('InMemoryCache', function() { }); it('should clear all items', (done) => { - var cache = new InMemoryCache(NO_EXPIRE_TTL); + const cache = new InMemoryCache(NO_EXPIRE_TTL); cache.put(KEY, VALUE); cache.put(KEY_2, VALUE); @@ -67,7 +67,7 @@ describe('InMemoryCache', function() { }); it('should deafult TTL to 5 seconds', () => { - var cache = new InMemoryCache({}); + const cache = new InMemoryCache({}); expect(cache.ttl).toEqual(5 * 1000); }); diff --git a/spec/InMemoryCacheAdapter.spec.js b/spec/InMemoryCacheAdapter.spec.js index 444beed8..ac041a75 100644 --- a/spec/InMemoryCacheAdapter.spec.js +++ b/spec/InMemoryCacheAdapter.spec.js @@ -1,8 +1,8 @@ -var InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; +const InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; describe('InMemoryCacheAdapter', function() { - var KEY = 'hello'; - var VALUE = 'world'; + const KEY = 'hello'; + const VALUE = 'world'; function wait(sleep) { return new Promise(function(resolve) { @@ -11,7 +11,7 @@ describe('InMemoryCacheAdapter', function() { } it('should expose promisifyed methods', (done) => { - var cache = new InMemoryCacheAdapter({ + const cache = new InMemoryCacheAdapter({ ttl: NaN }); @@ -27,7 +27,7 @@ describe('InMemoryCacheAdapter', function() { }); it('should get/set/clear', (done) => { - var cache = new InMemoryCacheAdapter({ + const cache = new InMemoryCacheAdapter({ ttl: NaN }); @@ -41,7 +41,7 @@ describe('InMemoryCacheAdapter', function() { }); it('should expire after ttl', (done) => { - var cache = new InMemoryCacheAdapter({ + const cache = new InMemoryCacheAdapter({ ttl: 10 }); diff --git a/spec/InstallationsRouter.spec.js b/spec/InstallationsRouter.spec.js index 50ee1964..47dd6df2 100644 --- a/spec/InstallationsRouter.spec.js +++ b/spec/InstallationsRouter.spec.js @@ -1,20 +1,20 @@ -var auth = require('../src/Auth'); -var Config = require('../src/Config'); -var rest = require('../src/rest'); -var InstallationsRouter = require('../src/Routers/InstallationsRouter').InstallationsRouter; +const auth = require('../src/Auth'); +const Config = require('../src/Config'); +const rest = require('../src/rest'); +const InstallationsRouter = require('../src/Routers/InstallationsRouter').InstallationsRouter; describe('InstallationsRouter', () => { it('uses find condition from request.body', (done) => { - var config = Config.get('test'); - var androidDeviceRequest = { + const config = Config.get('test'); + const androidDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'deviceType': 'android' }; - var iosDeviceRequest = { + const iosDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'deviceType': 'ios' }; - var request = { + const request = { config: config, auth: auth.master(config), body: { @@ -26,14 +26,14 @@ describe('InstallationsRouter', () => { info: {} }; - var router = new InstallationsRouter(); + const router = new InstallationsRouter(); rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }).then(() => { return router.handleFind(request); }).then((res) => { - var results = res.response.results; + const results = res.response.results; expect(results.length).toEqual(1); done(); }).catch((err) => { @@ -43,16 +43,16 @@ describe('InstallationsRouter', () => { }); it('uses find condition from request.query', (done) => { - var config = Config.get('test'); - var androidDeviceRequest = { + const config = Config.get('test'); + const androidDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'deviceType': 'android' }; - var iosDeviceRequest = { + const iosDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'deviceType': 'ios' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -64,14 +64,14 @@ describe('InstallationsRouter', () => { info: {} }; - var router = new InstallationsRouter(); + const router = new InstallationsRouter(); rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }).then(() => { return router.handleFind(request); }).then((res) => { - var results = res.response.results; + const results = res.response.results; expect(results.length).toEqual(1); done(); }).catch((err) => { @@ -81,16 +81,16 @@ describe('InstallationsRouter', () => { }); it('query installations with limit = 0', (done) => { - var config = Config.get('test'); - var androidDeviceRequest = { + const config = Config.get('test'); + const androidDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'deviceType': 'android' }; - var iosDeviceRequest = { + const iosDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'deviceType': 'ios' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -101,14 +101,14 @@ describe('InstallationsRouter', () => { }; Config.get('test'); - var router = new InstallationsRouter(); + const router = new InstallationsRouter(); rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }).then(() => { return router.handleFind(request); }).then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(0); done(); }).catch((err) => { @@ -118,16 +118,16 @@ describe('InstallationsRouter', () => { }); it('query installations with count = 1', done => { - var config = Config.get('test'); - var androidDeviceRequest = { + const config = Config.get('test'); + const androidDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'deviceType': 'android' }; - var iosDeviceRequest = { + const iosDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'deviceType': 'ios' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -137,12 +137,12 @@ describe('InstallationsRouter', () => { info: {} }; - var router = new InstallationsRouter(); + const router = new InstallationsRouter(); rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest)) .then(() => router.handleFind(request)) .then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(2); expect(response.count).toEqual(2); done(); @@ -154,16 +154,16 @@ describe('InstallationsRouter', () => { }); it('query installations with limit = 0 and count = 1', (done) => { - var config = Config.get('test'); - var androidDeviceRequest = { + const config = Config.get('test'); + const androidDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'deviceType': 'android' }; - var iosDeviceRequest = { + const iosDeviceRequest = { 'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'deviceType': 'ios' }; - var request = { + const request = { config: config, auth: auth.master(config), body: {}, @@ -174,14 +174,14 @@ describe('InstallationsRouter', () => { info: {} }; - var router = new InstallationsRouter(); + const router = new InstallationsRouter(); rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }).then(() => { return router.handleFind(request); }).then((res) => { - var response = res.response; + const response = res.response; expect(response.results.length).toEqual(0); expect(response.count).toEqual(2); done(); diff --git a/spec/JobSchedule.spec.js b/spec/JobSchedule.spec.js index e2839794..bd8ca307 100644 --- a/spec/JobSchedule.spec.js +++ b/spec/JobSchedule.spec.js @@ -35,23 +35,23 @@ describe('JobSchedule', () => { 'jobName': 'SomeJob' }); jobSchedule.save(null).then(done.fail) - .catch(done); + .catch(() => done()); }); it('should reject access when not using masterKey (/jobs)', (done) => { - rp.get(Parse.serverURL + '/cloud_code/jobs', defaultOptions).then(done.fail, done); + rp.get(Parse.serverURL + '/cloud_code/jobs', defaultOptions).then(done.fail, () => done()); }); it('should reject access when not using masterKey (/jobs/data)', (done) => { - rp.get(Parse.serverURL + '/cloud_code/jobs/data', defaultOptions).then(done.fail, done); + rp.get(Parse.serverURL + '/cloud_code/jobs/data', defaultOptions).then(done.fail, () => done()); }); it('should reject access when not using masterKey (PUT /jobs/id)', (done) => { - rp.put(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, done); + rp.put(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, () => done()); }); it('should reject access when not using masterKey (PUT /jobs/id)', (done) => { - rp.del(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, done); + rp.del(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, () => done()); }); it('should allow access when using masterKey (/jobs)', (done) => { @@ -90,7 +90,7 @@ describe('JobSchedule', () => { }); rp.post(Parse.serverURL + '/cloud_code/jobs', options) .then(done.fail) - .catch(done); + .catch(() => done()); }); it('should update a job', (done) => { @@ -144,7 +144,7 @@ describe('JobSchedule', () => { })); }) .then(done.fail) - .catch(done); + .catch(() => done()); }); it('should destroy a job', (done) => { diff --git a/spec/Logger.spec.js b/spec/Logger.spec.js index d4e31245..ee35e353 100644 --- a/spec/Logger.spec.js +++ b/spec/Logger.spec.js @@ -1,5 +1,5 @@ -var logging = require('../src/Adapters/Logger/WinstonLogger'); -var winston = require('winston'); +const logging = require('../src/Adapters/Logger/WinstonLogger'); +const winston = require('winston'); class TestTransport extends winston.Transport { log(level, msg, meta, callback) { @@ -51,7 +51,7 @@ describe('Logger', () => { spyOn(process.stdout, 'write'); logging.logger.info('hi', {key: 'value'}); expect(process.stdout.write).toHaveBeenCalled(); - var firstLog = process.stdout.write.calls.first().args[0]; + const firstLog = process.stdout.write.calls.first().args[0]; expect(firstLog).toEqual(JSON.stringify({key: 'value', level: 'info', message: 'hi' }) + '\n'); return reconfigureServer({ jsonLogs: false diff --git a/spec/LoggerController.spec.js b/spec/LoggerController.spec.js index 3ce65433..4a8e63f4 100644 --- a/spec/LoggerController.spec.js +++ b/spec/LoggerController.spec.js @@ -1,12 +1,12 @@ -var LoggerController = require('../src/Controllers/LoggerController').LoggerController; -var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; +const LoggerController = require('../src/Controllers/LoggerController').LoggerController; +const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; describe('LoggerController', () => { it('can check process a query without throwing', (done) => { // Make mock request - var query = {}; + const query = {}; - var loggerController = new LoggerController(new WinstonLoggerAdapter()); + const loggerController = new LoggerController(new WinstonLoggerAdapter()); expect(() => { loggerController.getLogs(query).then(function(res) { @@ -29,7 +29,7 @@ describe('LoggerController', () => { it('can set the proper default values', (done) => { // Make mock request - var result = LoggerController.parseOptions(); + const result = LoggerController.parseOptions(); expect(result.size).toEqual(10); expect(result.order).toEqual('desc'); expect(result.level).toEqual('info'); @@ -39,7 +39,7 @@ describe('LoggerController', () => { it('can process a query without throwing', (done) => { // Make mock request - var query = { + const query = { from: "2016-01-01Z00:00:00", until: "2016-01-01Z00:00:00", size: 5, @@ -47,7 +47,7 @@ describe('LoggerController', () => { level: 'error' }; - var result = LoggerController.parseOptions(query); + const result = LoggerController.parseOptions(query); expect(result.from.getTime()).toEqual(1451606400000); expect(result.until.getTime()).toEqual(1451606400000); @@ -60,7 +60,7 @@ describe('LoggerController', () => { it('can check process a query without throwing', (done) => { // Make mock request - var query = { + const query = { from: "2016-01-01", until: "2016-01-30", size: 5, @@ -68,7 +68,7 @@ describe('LoggerController', () => { level: 'error' }; - var loggerController = new LoggerController(new WinstonLoggerAdapter()); + const loggerController = new LoggerController(new WinstonLoggerAdapter()); expect(() => { loggerController.getLogs(query).then(function(res) { diff --git a/spec/LogsRouter.spec.js b/spec/LogsRouter.spec.js index 04eac524..65c8b62f 100644 --- a/spec/LogsRouter.spec.js +++ b/spec/LogsRouter.spec.js @@ -1,16 +1,16 @@ 'use strict'; const request = require('request'); -var LogsRouter = require('../src/Routers/LogsRouter').LogsRouter; -var LoggerController = require('../src/Controllers/LoggerController').LoggerController; -var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; +const LogsRouter = require('../src/Routers/LogsRouter').LogsRouter; +const LoggerController = require('../src/Controllers/LoggerController').LoggerController; +const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; const loggerController = new LoggerController(new WinstonLoggerAdapter()); describe('LogsRouter', () => { it('can check valid master key of request', (done) => { // Make mock request - var request = { + const request = { auth: { isMaster: true }, @@ -20,7 +20,7 @@ describe('LogsRouter', () => { } }; - var router = new LogsRouter(); + const router = new LogsRouter(); expect(() => { router.validateRequest(request); @@ -30,7 +30,7 @@ describe('LogsRouter', () => { it('can check invalid construction of controller', (done) => { // Make mock request - var request = { + const request = { auth: { isMaster: true }, @@ -40,7 +40,7 @@ describe('LogsRouter', () => { } }; - var router = new LogsRouter(); + const router = new LogsRouter(); expect(() => { router.validateRequest(request); diff --git a/spec/Middlewares.spec.js b/spec/Middlewares.spec.js index 7543f370..0b1ea593 100644 --- a/spec/Middlewares.spec.js +++ b/spec/Middlewares.spec.js @@ -1,9 +1,9 @@ -var middlewares = require('../src/middlewares'); -var AppCache = require('../src/cache').AppCache; +const middlewares = require('../src/middlewares'); +const AppCache = require('../src/cache').AppCache; describe('middlewares', () => { - var fakeReq, fakeRes; + let fakeReq, fakeRes; beforeEach(() => { fakeReq = { @@ -27,7 +27,7 @@ describe('middlewares', () => { it('should use _ContentType if provided', (done) => { expect(fakeReq.headers['content-type']).toEqual(undefined); - var contentType = 'image/jpeg'; + const contentType = 'image/jpeg'; fakeReq.body._ContentType = contentType; middlewares.handleParseHeaders(fakeReq, fakeRes, () => { expect(fakeReq.headers['content-type']).toEqual(contentType); diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index 19e8ce31..b263f70d 100644 --- a/spec/MongoStorageAdapter.spec.js +++ b/spec/MongoStorageAdapter.spec.js @@ -53,7 +53,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { .then(() => adapter._rawFind('Foo', {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj._id).toEqual('abcde'); expect(obj.objectId).toBeUndefined(); done(); diff --git a/spec/MongoTransform.spec.js b/spec/MongoTransform.spec.js index 0c24f715..ce48fb52 100644 --- a/spec/MongoTransform.spec.js +++ b/spec/MongoTransform.spec.js @@ -7,8 +7,8 @@ const mongodb = require('mongodb'); describe('parseObjectToMongoObjectForCreate', () => { it('a basic number', (done) => { - var input = {five: 5}; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { + const input = {five: 5}; + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {five: {type: 'Number'}} }); jequal(input, output); @@ -16,8 +16,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('an object with null values', (done) => { - var input = {objectWithNullValues: {isNull: null, notNull: 3}}; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { + const input = {objectWithNullValues: {isNull: null, notNull: 3}}; + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {objectWithNullValues: {type: 'object'}} }); jequal(input, output); @@ -25,23 +25,23 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('built-in timestamps', (done) => { - var input = { + const input = { createdAt: "2015-10-06T21:24:50.332Z", updatedAt: "2015-10-06T21:24:50.332Z" }; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); expect(output._created_at instanceof Date).toBe(true); expect(output._updated_at instanceof Date).toBe(true); done(); }); it('array of pointers', (done) => { - var pointer = { + const pointer = { __type: 'Pointer', objectId: 'myId', className: 'Blah', }; - var out = transform.parseObjectToMongoObjectForCreate(null, {pointers: [pointer]},{ + const out = transform.parseObjectToMongoObjectForCreate(null, {pointers: [pointer]},{ fields: {pointers: {type: 'Array'}} }); jequal([pointer], out.pointers); @@ -51,21 +51,21 @@ describe('parseObjectToMongoObjectForCreate', () => { //TODO: object creation requests shouldn't be seeing __op delete, it makes no sense to //have __op delete in a new object. Figure out what this should actually be testing. xit('a delete op', (done) => { - var input = {deleteMe: {__op: 'Delete'}}; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); + const input = {deleteMe: {__op: 'Delete'}}; + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); jequal(output, {}); done(); }); it('Doesnt allow ACL, as Parse Server should tranform ACL to _wperm + _rperm', done => { - var input = {ACL: {'0123': {'read': true, 'write': true}}}; + const input = {ACL: {'0123': {'read': true, 'write': true}}}; expect(() => transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} })).toThrow(); done(); }); it('plain', (done) => { - var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; - var out = transform.parseObjectToMongoObjectForCreate(null, {location: geoPoint},{ + const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; + const out = transform.parseObjectToMongoObjectForCreate(null, {location: geoPoint},{ fields: {location: {type: 'GeoPoint'}} }); expect(out.location).toEqual([180, -180]); @@ -73,8 +73,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('in array', (done) => { - var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; - var out = transform.parseObjectToMongoObjectForCreate(null, {locations: [geoPoint, geoPoint]},{ + const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; + const out = transform.parseObjectToMongoObjectForCreate(null, {locations: [geoPoint, geoPoint]},{ fields: {locations: {type: 'Array'}} }); expect(out.locations).toEqual([geoPoint, geoPoint]); @@ -82,8 +82,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('in sub-object', (done) => { - var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; - var out = transform.parseObjectToMongoObjectForCreate(null, { locations: { start: geoPoint }},{ + const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; + const out = transform.parseObjectToMongoObjectForCreate(null, { locations: { start: geoPoint }},{ fields: {locations: {type: 'Object'}} }); expect(out).toEqual({ locations: { start: geoPoint } }); @@ -91,31 +91,31 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('objectId', (done) => { - var out = transform.transformWhere(null, {objectId: 'foo'}); + const out = transform.transformWhere(null, {objectId: 'foo'}); expect(out._id).toEqual('foo'); done(); }); it('objectId in a list', (done) => { - var input = { + const input = { objectId: {'$in': ['one', 'two', 'three']}, }; - var output = transform.transformWhere(null, input); + const output = transform.transformWhere(null, input); jequal(input.objectId, output._id); done(); }); it('built-in timestamps', (done) => { - var input = {createdAt: new Date(), updatedAt: new Date()}; - var output = transform.mongoObjectToParseObject(null, input, { fields: {} }); + const input = {createdAt: new Date(), updatedAt: new Date()}; + const output = transform.mongoObjectToParseObject(null, input, { fields: {} }); expect(typeof output.createdAt).toEqual('string'); expect(typeof output.updatedAt).toEqual('string'); done(); }); it('pointer', (done) => { - var input = {_p_userPointer: '_User$123'}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {_p_userPointer: '_User$123'}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { userPointer: { type: 'Pointer', targetClass: '_User' } }, }); expect(typeof output.userPointer).toEqual('object'); @@ -126,8 +126,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('null pointer', (done) => { - var input = {_p_userPointer: null}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {_p_userPointer: null}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { userPointer: { type: 'Pointer', targetClass: '_User' } }, }); expect(output.userPointer).toBeUndefined(); @@ -135,8 +135,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('file', (done) => { - var input = {picture: 'pic.jpg'}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {picture: 'pic.jpg'}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { picture: { type: 'File' }}, }); expect(typeof output.picture).toEqual('object'); @@ -145,8 +145,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('geopoint', (done) => { - var input = {location: [45, -45]}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {location: [45, -45]}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { location: { type: 'GeoPoint' }}, }); expect(typeof output.location).toEqual('object'); @@ -157,8 +157,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('polygon', (done) => { - var input = {location: { type: 'Polygon', coordinates: [[[45, -45],[45, -45]]]}}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {location: { type: 'Polygon', coordinates: [[[45, -45],[45, -45]]]}}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { location: { type: 'Polygon' }}, }); expect(typeof output.location).toEqual('object'); @@ -169,8 +169,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('bytes', (done) => { - var input = {binaryData: "aGVsbG8gd29ybGQ="}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {binaryData: "aGVsbG8gd29ybGQ="}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { binaryData: { type: 'Bytes' }}, }); expect(typeof output.binaryData).toEqual('object'); @@ -181,8 +181,8 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('nested array', (done) => { - var input = {arr: [{_testKey: 'testValue' }]}; - var output = transform.mongoObjectToParseObject(null, input, { + const input = {arr: [{_testKey: 'testValue' }]}; + const output = transform.mongoObjectToParseObject(null, input, { fields: { arr: { type: 'Array' } }, }); expect(Array.isArray(output.arr)).toEqual(true); @@ -210,10 +210,10 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('changes new pointer key', (done) => { - var input = { + const input = { somePointer: {__type: 'Pointer', className: 'Micro', objectId: 'oft'} }; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {somePointer: {type: 'Pointer'}} }); expect(typeof output._p_somePointer).toEqual('string'); @@ -222,10 +222,10 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('changes existing pointer keys', (done) => { - var input = { + const input = { userPointer: {__type: 'Pointer', className: '_User', objectId: 'qwerty'} }; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {userPointer: {type: 'Pointer'}} }); expect(typeof output._p_userPointer).toEqual('string'); @@ -234,12 +234,12 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('writes the old ACL format in addition to rperm and wperm on create', (done) => { - var input = { + const input = { _rperm: ['*'], _wperm: ['Kevin'], }; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); expect(typeof output._acl).toEqual('object'); expect(output._acl['Kevin'].w).toBeTruthy(); expect(output._acl['Kevin'].r).toBeUndefined(); @@ -249,10 +249,10 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('removes Relation types', (done) => { - var input = { + const input = { aRelation: { __type: 'Relation', className: 'Stuff' }, }; - var output = transform.parseObjectToMongoObjectForCreate(null, input, { + const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: { aRelation: { __type: 'Relation', className: 'Stuff' }, }, @@ -262,13 +262,13 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('writes the old ACL format in addition to rperm and wperm on update', (done) => { - var input = { + const input = { _rperm: ['*'], _wperm: ['Kevin'] }; - var output = transform.transformUpdate(null, input, { fields: {} }); - var set = output.$set; + const output = transform.transformUpdate(null, input, { fields: {} }); + const set = output.$set; expect(typeof set).toEqual('object'); expect(typeof set._acl).toEqual('object'); expect(set._acl['Kevin'].w).toBeTruthy(); @@ -279,11 +279,11 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('untransforms from _rperm and _wperm to ACL', (done) => { - var input = { + const input = { _rperm: ["*"], _wperm: ["Kevin"] }; - var output = transform.mongoObjectToParseObject(null, input, { fields: {} }); + const output = transform.mongoObjectToParseObject(null, input, { fields: {} }); expect(output._rperm).toEqual(['*']); expect(output._wperm).toEqual(['Kevin']); expect(output.ACL).toBeUndefined() @@ -291,11 +291,11 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('untransforms mongodb number types', (done) => { - var input = { + const input = { long: mongodb.Long.fromNumber(Number.MAX_SAFE_INTEGER), double: new mongodb.Double(Number.MAX_VALUE) } - var output = transform.mongoObjectToParseObject(null, input, { + const output = transform.mongoObjectToParseObject(null, input, { fields: { long: { type: 'Number' }, double: { type: 'Number' }, @@ -307,10 +307,10 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('Date object where iso attribute is of type Date', (done) => { - var input = { + const input = { ts : { __type: 'Date', iso: new Date('2017-01-18T00:00:00.000Z') } } - var output = transform.mongoObjectToParseObject(null, input, { + const output = transform.mongoObjectToParseObject(null, input, { fields : { ts : { type : 'Date' } } @@ -320,10 +320,10 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('Date object where iso attribute is of type String', (done) => { - var input = { + const input = { ts : { __type: 'Date', iso: '2017-01-18T00:00:00.000Z' } } - var output = transform.mongoObjectToParseObject(null, input, { + const output = transform.mongoObjectToParseObject(null, input, { fields : { ts : { type : 'Date' } } @@ -335,10 +335,10 @@ describe('parseObjectToMongoObjectForCreate', () => { describe('transformUpdate', () => { it('removes Relation types', (done) => { - var input = { + const input = { aRelation: { __type: 'Relation', className: 'Stuff' }, }; - var output = transform.transformUpdate(null, input, { + const output = transform.transformUpdate(null, input, { fields: { aRelation: { __type: 'Relation', className: 'Stuff' }, }, diff --git a/spec/NullCacheAdapter.spec.js b/spec/NullCacheAdapter.spec.js index a1943559..d1d6b0a9 100644 --- a/spec/NullCacheAdapter.spec.js +++ b/spec/NullCacheAdapter.spec.js @@ -1,11 +1,11 @@ -var NullCacheAdapter = require('../src/Adapters/Cache/NullCacheAdapter').default; +const NullCacheAdapter = require('../src/Adapters/Cache/NullCacheAdapter').default; describe('NullCacheAdapter', function() { - var KEY = 'hello'; - var VALUE = 'world'; + const KEY = 'hello'; + const VALUE = 'world'; it('should expose promisifyed methods', (done) => { - var cache = new NullCacheAdapter({ + const cache = new NullCacheAdapter({ ttl: NaN }); @@ -21,7 +21,7 @@ describe('NullCacheAdapter', function() { }); it('should get/set/clear', (done) => { - var cache = new NullCacheAdapter({ + const cache = new NullCacheAdapter({ ttl: NaN }); diff --git a/spec/OAuth1.spec.js b/spec/OAuth1.spec.js index 5c64f7e3..31b68316 100644 --- a/spec/OAuth1.spec.js +++ b/spec/OAuth1.spec.js @@ -1,4 +1,4 @@ -var OAuth = require("../src/Adapters/Auth/OAuth1Client"); +const OAuth = require("../src/Adapters/Auth/OAuth1Client"); describe('OAuth', function() { it("Nonce should have right length", (done) => { @@ -7,45 +7,45 @@ describe('OAuth', function() { }); it("Should properly build parameter string", (done) => { - var string = OAuth.buildParameterString({c:1, a:2, b:3}) + const string = OAuth.buildParameterString({c:1, a:2, b:3}) jequal(string, "a=2&b=3&c=1"); done(); }); it("Should properly build empty parameter string", (done) => { - var string = OAuth.buildParameterString() + const string = OAuth.buildParameterString() jequal(string, ""); done(); }); it("Should properly build signature string", (done) => { - var string = OAuth.buildSignatureString("get", "http://dummy.com", ""); + const string = OAuth.buildSignatureString("get", "http://dummy.com", ""); jequal(string, "GET&http%3A%2F%2Fdummy.com&"); done(); }); it("Should properly generate request signature", (done) => { - var request = { + let request = { host: "dummy.com", path: "path" }; - var oauth_params = { + const oauth_params = { oauth_timestamp: 123450000, oauth_nonce: "AAAAAAAAAAAAAAAAA", oauth_consumer_key: "hello", oauth_token: "token" }; - var consumer_secret = "world"; - var auth_token_secret = "secret"; + const consumer_secret = "world"; + const auth_token_secret = "secret"; request = OAuth.signRequest(request, oauth_params, consumer_secret, auth_token_secret); jequal(request.headers['Authorization'], 'OAuth oauth_consumer_key="hello", oauth_nonce="AAAAAAAAAAAAAAAAA", oauth_signature="8K95bpQcDi9Nd2GkhumTVcw4%2BXw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="123450000", oauth_token="token", oauth_version="1.0"'); done(); }); it("Should properly build request", (done) => { - var options = { + const options = { host: "dummy.com", consumer_key: "hello", consumer_secret: "world", @@ -57,11 +57,11 @@ describe('OAuth', function() { oauth_nonce: "AAAAAAAAAAAAAAAAA" } }; - var path = "path"; - var method = "get"; + const path = "path"; + const method = "get"; - var oauthClient = new OAuth(options); - var req = oauthClient.buildRequest(method, path, {"query": "param"}); + const oauthClient = new OAuth(options); + const req = oauthClient.buildRequest(method, path, {"query": "param"}); jequal(req.host, options.host); jequal(req.path, "/" + path + "?query=param"); @@ -75,7 +75,7 @@ describe('OAuth', function() { function validateCannotAuthenticateError(data, done) { jequal(typeof data, "object"); jequal(typeof data.errors, "object"); - var errors = data.errors; + const errors = data.errors; jequal(typeof errors[0], "object"); // Cannot authenticate error jequal(errors[0].code, 32); @@ -83,48 +83,48 @@ describe('OAuth', function() { } it("Should fail a GET request", (done) => { - var options = { + const options = { host: "api.twitter.com", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", }; - var path = "/1.1/help/configuration.json"; - var params = {"lang": "en"}; - var oauthClient = new OAuth(options); + const path = "/1.1/help/configuration.json"; + const params = {"lang": "en"}; + const oauthClient = new OAuth(options); oauthClient.get(path, params).then(function(data){ validateCannotAuthenticateError(data, done); }) }); it("Should fail a POST request", (done) => { - var options = { + const options = { host: "api.twitter.com", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", }; - var body = { + const body = { lang: "en" }; - var path = "/1.1/account/settings.json"; + const path = "/1.1/account/settings.json"; - var oauthClient = new OAuth(options); + const oauthClient = new OAuth(options); oauthClient.post(path, null, body).then(function(data){ validateCannotAuthenticateError(data, done); }) }); it("Should fail a request", (done) => { - var options = { + const options = { host: "localhost", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", }; - var body = { + const body = { lang: "en" }; - var path = "/"; + const path = "/"; - var oauthClient = new OAuth(options); + const oauthClient = new OAuth(options); oauthClient.post(path, null, body).then(function(){ jequal(false, true); done(); @@ -135,7 +135,7 @@ describe('OAuth', function() { }); it("Should fail with missing options", (done) => { - var options = undefined; + const options = undefined; try { new OAuth(options); } catch (error) { diff --git a/spec/Parse.Push.spec.js b/spec/Parse.Push.spec.js index 77f3fbc2..90558284 100644 --- a/spec/Parse.Push.spec.js +++ b/spec/Parse.Push.spec.js @@ -9,12 +9,12 @@ const delayPromise = (delay) => { } describe('Parse.Push', () => { - var setup = function() { - var sendToInstallationSpy = jasmine.createSpy(); + const setup = function() { + const sendToInstallationSpy = jasmine.createSpy(); - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { - var badge = body.data.badge; + const badge = body.data.badge; const promises = installations.map((installation) => { sendToInstallationSpy(installation); @@ -46,9 +46,9 @@ describe('Parse.Push', () => { } }) .then(() => { - var installations = []; + const installations = []; while(installations.length != 10) { - var installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); installation.set("deviceToken","device_token_" + installations.length) installation.set("badge", installations.length); diff --git a/spec/ParseACL.spec.js b/spec/ParseACL.spec.js index b5bd723b..8398ccba 100644 --- a/spec/ParseACL.spec.js +++ b/spec/ParseACL.spec.js @@ -1,12 +1,12 @@ // This is a port of the test suite: // hungry/js/test/parse_acl_test.js -var rest = require('../src/rest'); -var Config = require('../src/Config'); -var auth = require('../src/Auth'); +const rest = require('../src/rest'); +const Config = require('../src/Config'); +const auth = require('../src/Auth'); describe('Parse.ACL', () => { it("acl must be valid", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); ok(!user.setACL("Ceci n'est pas un ACL.", { error: function(user, error) { equal(error.code, -1); @@ -17,13 +17,13 @@ describe('Parse.ACL', () => { it("refresh object with acl", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -41,13 +41,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and public get", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -60,7 +60,7 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Get - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { success: function() { fail('Should not have retrieved the object.'); @@ -80,13 +80,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and public find", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -100,7 +100,7 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Find - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 0); @@ -117,13 +117,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and public update", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -156,13 +156,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and public delete", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -190,13 +190,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and logged in get", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -211,7 +211,7 @@ describe('Parse.ACL', () => { Parse.User.logIn("alice", "wonderland", { success: function() { // Get - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { success: function(result) { ok(result); @@ -235,13 +235,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and logged in find", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -256,11 +256,11 @@ describe('Parse.ACL', () => { Parse.User.logIn("alice", "wonderland", { success: function() { // Find - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var result = results[0]; + const result = results[0]; ok(result); if (!result) { return fail(); @@ -285,13 +285,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and logged in update", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -323,13 +323,13 @@ describe('Parse.ACL', () => { it("acl an object owned by one user and logged in delete", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -360,13 +360,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly readable and public get", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -389,7 +389,7 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Get - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { success: function(result) { ok(result); @@ -408,13 +408,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly readable and public find", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -437,11 +437,11 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Find - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var result = results[0]; + const result = results[0]; ok(result); equal(result.id, object.id); done(); @@ -458,13 +458,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly readable and public update", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -505,13 +505,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly readable and public delete", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -549,13 +549,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly writable and public get", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -578,7 +578,7 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Get - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { error: function(model, error) { equal(error.code, Parse.Error.OBJECT_NOT_FOUND); @@ -596,13 +596,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly writable and public find", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -625,7 +625,7 @@ describe('Parse.ACL', () => { Parse.User.logOut() .then(() => { // Find - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 0); @@ -643,13 +643,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly writable and public update", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -689,13 +689,13 @@ describe('Parse.ACL', () => { it("acl making an object publicly writable and public delete", (done) => { // Create an object owned by Alice. - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp(null, { success: function() { - var object = new TestObject(); - var acl = new Parse.ACL(user); + const object = new TestObject(); + const acl = new Parse.ACL(user); object.setACL(acl); object.save(null, { success: function() { @@ -734,14 +734,14 @@ describe('Parse.ACL', () => { it("acl making an object privately writable (#3194)", (done) => { // Create an object owned by Alice. - var object; - var user2; - var user = new Parse.User(); + let object; + let user2; + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "wonderland"); user.signUp().then(() => { object = new TestObject(); - var acl = new Parse.ACL(user); + const acl = new Parse.ACL(user); acl.setPublicWriteAccess(false); acl.setPublicReadAccess(true); object.setACL(acl); @@ -774,8 +774,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -791,7 +791,7 @@ describe('Parse.ACL', () => { // Sign in as Bob again. Parse.User.logIn("bob", "pass", { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { success: function(result) { ok(result); @@ -820,8 +820,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -837,11 +837,11 @@ describe('Parse.ACL', () => { // Sign in as Bob again. Parse.User.logIn("bob", "pass", { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var result = results[0]; + const result = results[0]; ok(result); if (!result) { fail("should have result"); @@ -872,8 +872,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -916,8 +916,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -960,8 +960,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -977,7 +977,7 @@ describe('Parse.ACL', () => { // Start making requests by the public. Parse.User.logOut() .then(() => { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id).then((result) => { fail(result); }, (error) => { @@ -1004,8 +1004,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -1021,7 +1021,7 @@ describe('Parse.ACL', () => { // Start making requests by the public. Parse.User.logOut() .then(() => { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 0); @@ -1048,8 +1048,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -1092,8 +1092,8 @@ describe('Parse.ACL', () => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { // Create an object shared by Bob and Alice. - var object = new TestObject(); - var acl = new Parse.ACL(alice); + const object = new TestObject(); + const acl = new Parse.ACL(alice); acl.setWriteAccess(bob, true); acl.setReadAccess(bob, true); object.setACL(acl); @@ -1127,10 +1127,10 @@ describe('Parse.ACL', () => { it("acl saveAll with permissions", (done) => { Parse.User.signUp("alice", "wonderland", null, { success: function(alice) { - var acl = new Parse.ACL(alice); + const acl = new Parse.ACL(alice); - var object1 = new TestObject(); - var object2 = new TestObject(); + const object1 = new TestObject(); + const object2 = new TestObject(); object1.setACL(acl); object2.setACL(acl); Parse.Object.saveAll([object1, object2], { @@ -1149,7 +1149,7 @@ describe('Parse.ACL', () => { object2.set("foo", "bar"); Parse.Object.saveAll([object1, object2], { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo("foo", "bar"); query.find({ success: function(results) { @@ -1193,16 +1193,16 @@ describe('Parse.ACL', () => { }); it("query for included object with ACL works", (done) => { - var obj1 = new Parse.Object("TestClass1"); - var obj2 = new Parse.Object("TestClass2"); - var acl = new Parse.ACL(); + const obj1 = new Parse.Object("TestClass1"); + const obj2 = new Parse.Object("TestClass2"); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); obj2.set("ACL", acl); obj1.set("other", obj2); obj1.save(null, expectSuccess({ success: function() { obj2._clearServerData(); - var query = new Parse.Query("TestClass1"); + const query = new Parse.Query("TestClass1"); query.first(expectSuccess({ success: function(obj1Again) { ok(!obj1Again.get("other").get("ACL")); @@ -1221,11 +1221,11 @@ describe('Parse.ACL', () => { }); it('restricted ACL does not have public access', (done) => { - var obj = new Parse.Object("TestClassMasterACL"); - var acl = new Parse.ACL(); + const obj = new Parse.Object("TestClassMasterACL"); + const acl = new Parse.ACL(); obj.set('ACL', acl); obj.save().then(() => { - var query = new Parse.Query("TestClassMasterACL"); + const query = new Parse.Query("TestClassMasterACL"); return query.find(); }).then((results) => { ok(!results.length, 'Should not have returned object with secure ACL.'); @@ -1235,7 +1235,7 @@ describe('Parse.ACL', () => { it('regression test #701', done => { const config = Config.get('test'); - var anonUser = { + const anonUser = { authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' @@ -1245,8 +1245,8 @@ describe('Parse.ACL', () => { Parse.Cloud.afterSave(Parse.User, req => { if (!req.object.existed()) { - var user = req.object; - var acl = new Parse.ACL(user); + const user = req.object; + const acl = new Parse.ACL(user); user.setACL(acl); user.save(null, {useMasterKey: true}).then(user => { new Parse.Query('_User').get(user.objectId).then(() => { diff --git a/spec/ParseAPI.spec.js b/spec/ParseAPI.spec.js index ffc5b7ba..de16ebb7 100644 --- a/spec/ParseAPI.spec.js +++ b/spec/ParseAPI.spec.js @@ -2,24 +2,24 @@ // It would probably be better to refactor them into different files. 'use strict'; -var request = require('request'); +const request = require('request'); const rp = require('request-promise'); const Parse = require("parse/node"); const Config = require('../src/Config'); const SchemaController = require('../src/Controllers/SchemaController'); -var TestUtils = require('../src/TestUtils'); +const TestUtils = require('../src/TestUtils'); const userSchema = SchemaController.convertSchemaToAdapterSchema({ className: '_User', fields: Object.assign({}, SchemaController.defaultColumns._Default, SchemaController.defaultColumns._User) }); describe_only_db('mongo')('miscellaneous', () => { it('test rest_create_app', function(done) { - var appId; + let appId; Parse._request('POST', 'rest_create_app').then((res) => { expect(typeof res.application_id).toEqual('string'); expect(res.master_key).toEqual('master'); appId = res.application_id; Parse.initialize(appId, 'unused'); - var obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.set('foo', 'bar'); return obj.save(); }).then(() => { @@ -38,7 +38,7 @@ describe_only_db('mongo')('miscellaneous', () => { describe('miscellaneous', function() { it('create a GameScore object', function(done) { - var obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('score', 1337); obj.save().then(function(obj) { expect(typeof obj.id).toBe('string'); @@ -52,7 +52,7 @@ describe('miscellaneous', function() { it('get a TestObject', function(done) { create({ 'bloop' : 'blarg' }, function(obj) { - var t2 = new TestObject({ objectId: obj.id }); + const t2 = new TestObject({ objectId: obj.id }); t2.fetch({ success: function(obj2) { expect(obj2.get('bloop')).toEqual('blarg'); @@ -277,12 +277,12 @@ describe('miscellaneous', function() { }); it('save various data types', function(done) { - var obj = new TestObject(); + const obj = new TestObject(); obj.set('date', new Date()); obj.set('array', [1, 2, 3]); obj.set('object', {one: 1, two: 2}); obj.save().then(() => { - var obj2 = new TestObject({objectId: obj.id}); + const obj2 = new TestObject({objectId: obj.id}); return obj2.fetch(); }).then((obj2) => { expect(obj2.get('date') instanceof Date).toBe(true); @@ -294,12 +294,12 @@ describe('miscellaneous', function() { }); it('query with limit', function(done) { - var baz = new TestObject({ foo: 'baz' }); - var qux = new TestObject({ foo: 'qux' }); + const baz = new TestObject({ foo: 'baz' }); + const qux = new TestObject({ foo: 'qux' }); baz.save().then(() => { return qux.save(); }).then(() => { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.limit(1); return query.find(); }).then((results) => { @@ -312,8 +312,8 @@ describe('miscellaneous', function() { }); it('query without limit get default 100 records', function(done) { - var objects = []; - for (var i = 0; i < 150; i++) { + const objects = []; + for (let i = 0; i < 150; i++) { objects.push(new TestObject({name: 'name' + i})); } Parse.Object.saveAll(objects).then(() => { @@ -328,8 +328,8 @@ describe('miscellaneous', function() { }); it('basic saveAll', function(done) { - var alpha = new TestObject({ letter: 'alpha' }); - var beta = new TestObject({ letter: 'beta' }); + const alpha = new TestObject({ letter: 'alpha' }); + const beta = new TestObject({ letter: 'beta' }); Parse.Object.saveAll([alpha, beta]).then(() => { expect(alpha.id).toBeTruthy(); expect(beta.id).toBeTruthy(); @@ -344,7 +344,7 @@ describe('miscellaneous', function() { }); it('test beforeSave set object acl success', function(done) { - var acl = new Parse.ACL({ + const acl = new Parse.ACL({ '*': { read: true, write: false } }); Parse.Cloud.beforeSave('BeforeSaveAddACL', function(req, res) { @@ -352,10 +352,10 @@ describe('miscellaneous', function() { res.success(); }); - var obj = new Parse.Object('BeforeSaveAddACL'); + const obj = new Parse.Object('BeforeSaveAddACL'); obj.set('lol', true); obj.save().then(function() { - var query = new Parse.Query('BeforeSaveAddACL'); + const query = new Parse.Query('BeforeSaveAddACL'); query.get(obj.id).then(function(objAgain) { expect(objAgain.get('lol')).toBeTruthy(); expect(objAgain.getACL().equals(acl)); @@ -534,20 +534,20 @@ describe('miscellaneous', function() { it('pointer reassign is working properly (#1288)', (done) => { Parse.Cloud.beforeSave('GameScore', (req, res) => { - var obj = req.object; + const obj = req.object; if (obj.get('point')) { return res.success(); } - var TestObject1 = Parse.Object.extend('TestObject1'); - var newObj = new TestObject1({'key1': 1}); + const TestObject1 = Parse.Object.extend('TestObject1'); + const newObj = new TestObject1({'key1': 1}); return newObj.save().then((newObj) => { obj.set('point' , newObj); res.success(); }); }); - var pointId; - var obj = new Parse.Object('GameScore'); + let pointId; + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.save().then(() => { expect(obj.get('point')).not.toBeUndefined(); @@ -562,10 +562,10 @@ describe('miscellaneous', function() { }); it('test afterSave get full object on create and update', function(done) { - var triggerTime = 0; + let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { - var object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.id).not.toBeUndefined(); expect(object.createdAt).not.toBeUndefined(); @@ -584,7 +584,7 @@ describe('miscellaneous', function() { res.success(); }); - var obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); obj.save().then(function() { @@ -602,17 +602,17 @@ describe('miscellaneous', function() { }); it('test afterSave get original object on update', function(done) { - var triggerTime = 0; + let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { - var object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.get('fooAgain')).toEqual('barAgain'); expect(object.id).not.toBeUndefined(); expect(object.createdAt).not.toBeUndefined(); expect(object.updatedAt).not.toBeUndefined(); - var originalObject = req.original; + const originalObject = req.original; if (triggerTime == 0) { // Create expect(object.get('foo')).toEqual('bar'); @@ -635,7 +635,7 @@ describe('miscellaneous', function() { res.success(); }); - var obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); obj.save().then(function() { @@ -653,11 +653,11 @@ describe('miscellaneous', function() { }); it('test afterSave get full original object even req auth can not query it', (done) => { - var triggerTime = 0; + let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { - var object = req.object; - var originalObject = req.original; + const object = req.object; + const originalObject = req.original; if (triggerTime == 0) { // Create } else if (triggerTime == 1) { @@ -677,10 +677,10 @@ describe('miscellaneous', function() { res.success(); }); - var obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); - var acl = new Parse.ACL(); + const acl = new Parse.ACL(); // Make sure our update request can not query the object acl.setPublicReadAccess(false); acl.setPublicWriteAccess(true); @@ -700,7 +700,7 @@ describe('miscellaneous', function() { }); it('afterSave flattens custom operations', done => { - var triggerTime = 0; + let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { const object = req.object; @@ -721,7 +721,7 @@ describe('miscellaneous', function() { res.success(); }); - var obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.increment('yolo', 1); obj.save().then(() => { obj.increment('yolo', 1); @@ -817,7 +817,7 @@ describe('miscellaneous', function() { it('should return the updated fields on PUT', done => { const obj = new Parse.Object('GameScore'); obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => { - var headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -921,7 +921,7 @@ describe('miscellaneous', function() { expect(req.installationId).toEqual('yolo'); }); - var headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -952,7 +952,7 @@ describe('miscellaneous', function() { expect(req.installationId).toEqual('yolo'); }); - var headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -979,7 +979,7 @@ describe('miscellaneous', function() { Parse.Cloud.define('echoParams', (req, res) => { res.success(req.params); }); - var headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-Javascript-Key': 'test' @@ -994,7 +994,7 @@ describe('miscellaneous', function() { body: '{"foo":"bar", "other": 1}' }, (error, response, body) => { expect(error).toBe(null); - var res = JSON.parse(body).result; + const res = JSON.parse(body).result; expect(res.option).toEqual('1'); // Make sure query string params override body params expect(res.other).toEqual('2'); @@ -1054,7 +1054,7 @@ describe('miscellaneous', function() { }); it('fails on invalid client key', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-Client-Key': 'notclient' @@ -1064,14 +1064,14 @@ describe('miscellaneous', function() { url: 'http://localhost:8378/1/classes/TestObject' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toEqual('unauthorized'); done(); }); }); it('fails on invalid windows key', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-Windows-Key': 'notwindows' @@ -1081,14 +1081,14 @@ describe('miscellaneous', function() { url: 'http://localhost:8378/1/classes/TestObject' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toEqual('unauthorized'); done(); }); }); it('fails on invalid javascript key', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-Javascript-Key': 'notjavascript' @@ -1098,14 +1098,14 @@ describe('miscellaneous', function() { url: 'http://localhost:8378/1/classes/TestObject' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toEqual('unauthorized'); done(); }); }); it('fails on invalid rest api key', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'notrest' @@ -1115,7 +1115,7 @@ describe('miscellaneous', function() { url: 'http://localhost:8378/1/classes/TestObject' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toEqual('unauthorized'); done(); }); @@ -1442,7 +1442,7 @@ describe('miscellaneous', function() { 'X-Parse-Application-Id': 'test', 'X-Parse-Master-Key': 'test' }; - var user, object; + let user, object; createTestUser().then((x) => { user = x; const acl = new Parse.ACL(); diff --git a/spec/ParseCloudCodePublisher.spec.js b/spec/ParseCloudCodePublisher.spec.js index 5fba0b25..00e6a879 100644 --- a/spec/ParseCloudCodePublisher.spec.js +++ b/spec/ParseCloudCodePublisher.spec.js @@ -1,10 +1,10 @@ -var ParseCloudCodePublisher = require('../src/LiveQuery/ParseCloudCodePublisher').ParseCloudCodePublisher; -var Parse = require('parse/node'); +const ParseCloudCodePublisher = require('../src/LiveQuery/ParseCloudCodePublisher').ParseCloudCodePublisher; +const Parse = require('parse/node'); describe('ParseCloudCodePublisher', function() { beforeEach(function(done) { // Mock ParsePubSub - var mockParsePubSub = { + const mockParsePubSub = { createPublisher: jasmine.createSpy('publish').and.returnValue({ publish: jasmine.createSpy('publish'), on: jasmine.createSpy('on') @@ -19,46 +19,46 @@ describe('ParseCloudCodePublisher', function() { }); it('can initialize', function() { - var config = {} + const config = {} new ParseCloudCodePublisher(config); - var ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; + const ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; expect(ParsePubSub.createPublisher).toHaveBeenCalledWith(config); }); it('can handle cloud code afterSave request', function() { - var publisher = new ParseCloudCodePublisher({}); + const publisher = new ParseCloudCodePublisher({}); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); - var request = {}; + const request = {}; publisher.onCloudCodeAfterSave(request); expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterSave', request); }); it('can handle cloud code afterDelete request', function() { - var publisher = new ParseCloudCodePublisher({}); + const publisher = new ParseCloudCodePublisher({}); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); - var request = {}; + const request = {}; publisher.onCloudCodeAfterDelete(request); expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterDelete', request); }); it('can handle cloud code request', function() { - var publisher = new ParseCloudCodePublisher({}); - var currentParseObject = new Parse.Object('Test'); + const publisher = new ParseCloudCodePublisher({}); + const currentParseObject = new Parse.Object('Test'); currentParseObject.set('key', 'value'); - var originalParseObject = new Parse.Object('Test'); + const originalParseObject = new Parse.Object('Test'); originalParseObject.set('key', 'originalValue'); - var request = { + const request = { object: currentParseObject, original: originalParseObject }; publisher._onCloudCodeMessage('afterSave', request); - var args = publisher.parsePublisher.publish.calls.mostRecent().args; + const args = publisher.parsePublisher.publish.calls.mostRecent().args; expect(args[0]).toBe('afterSave'); - var message = JSON.parse(args[1]); + const message = JSON.parse(args[1]); expect(message.currentParseObject).toEqual(request.object._toFullJSON()); expect(message.originalParseObject).toEqual(request.original._toFullJSON()); }); diff --git a/spec/ParseFile.spec.js b/spec/ParseFile.spec.js index 9ec2c680..9f19a871 100644 --- a/spec/ParseFile.spec.js +++ b/spec/ParseFile.spec.js @@ -3,18 +3,18 @@ "use strict"; -var request = require('request'); +const request = require('request'); -var str = "Hello World!"; -var data = []; -for (var i = 0; i < str.length; i++) { +const str = "Hello World!"; +const data = []; +for (let i = 0; i < str.length; i++) { data.push(str.charCodeAt(i)); } describe('Parse.File testing', () => { describe('creating files', () => { it('works with Content-Type', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -25,7 +25,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/_file.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); request.get(b.url, (error, response, body) => { @@ -49,7 +49,7 @@ describe('Parse.File testing', () => { }) }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/_file.html/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.html$/); request.get(b.url, (error, response, body) => { @@ -66,7 +66,7 @@ describe('Parse.File testing', () => { }); it('works without Content-Type', done => { - var headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; @@ -76,7 +76,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/_file.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); request.get(b.url, (error, response, body) => { @@ -89,7 +89,7 @@ describe('Parse.File testing', () => { }); it('supports REST end-to-end file create, read, delete, read', done => { - var headers = { + const headers = { 'Content-Type': 'image/jpeg', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -100,7 +100,7 @@ describe('Parse.File testing', () => { body: 'check one two', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/_testfile.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*testfile.txt$/); request.get(b.url, (error, response, body) => { @@ -137,7 +137,7 @@ describe('Parse.File testing', () => { }); it('blocks file deletions with missing or incorrect master-key header', done => { - var headers = { + const headers = { 'Content-Type': 'image/jpeg', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -148,7 +148,7 @@ describe('Parse.File testing', () => { body: 'the file body' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*thefile.jpg$/); // missing X-Parse-Master-Key header request.del({ @@ -159,7 +159,7 @@ describe('Parse.File testing', () => { url: 'http://localhost:8378/1/files/' + b.name }, (error, response, body) => { expect(error).toBe(null); - var del_b = JSON.parse(body); + const del_b = JSON.parse(body); expect(response.statusCode).toEqual(403); expect(del_b.error).toMatch(/unauthorized/); // incorrect X-Parse-Master-Key header @@ -172,7 +172,7 @@ describe('Parse.File testing', () => { url: 'http://localhost:8378/1/files/' + b.name }, (error, response, body) => { expect(error).toBe(null); - var del_b2 = JSON.parse(body); + const del_b2 = JSON.parse(body); expect(response.statusCode).toEqual(403); expect(del_b2.error).toMatch(/unauthorized/); done(); @@ -182,7 +182,7 @@ describe('Parse.File testing', () => { }); it('handles other filetypes', done => { - var headers = { + const headers = { 'Content-Type': 'image/jpeg', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -193,7 +193,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/_file.jpg$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/.*file.jpg$/); request.get(b.url, (error, response, body) => { @@ -205,7 +205,7 @@ describe('Parse.File testing', () => { }); it("save file", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + const file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); file.save(expectSuccess({ success: function(result) { @@ -219,7 +219,7 @@ describe('Parse.File testing', () => { }); it("save file in object", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + const file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); file.save(expectSuccess({ success: function(result) { @@ -228,7 +228,7 @@ describe('Parse.File testing', () => { ok(file.url()); notEqual(file.name(), "hello.txt"); - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.save({ file: file }, expectSuccess({ @@ -246,7 +246,7 @@ describe('Parse.File testing', () => { }); it("save file in object with escaped characters in filename", done => { - var file = new Parse.File("hello . txt", data, "text/plain"); + const file = new Parse.File("hello . txt", data, "text/plain"); ok(!file.url()); file.save(expectSuccess({ success: function(result) { @@ -255,7 +255,7 @@ describe('Parse.File testing', () => { ok(file.url()); notEqual(file.name(), "hello . txt"); - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.save({ file: file }, expectSuccess({ @@ -274,9 +274,9 @@ describe('Parse.File testing', () => { }); it("autosave file in object", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + let file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.save({ file: file }, expectSuccess({ @@ -296,22 +296,22 @@ describe('Parse.File testing', () => { }); it("autosave file in object in object", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + let file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); - var child = new Parse.Object("Child"); + const child = new Parse.Object("Child"); child.set("file", file); - var parent = new Parse.Object("Parent"); + const parent = new Parse.Object("Parent"); parent.set("child", child); parent.save(expectSuccess({ success: function(parent) { - var query = new Parse.Query("Parent"); + const query = new Parse.Query("Parent"); query.include("child"); query.get(parent.id, expectSuccess({ success: function(parentAgain) { - var childAgain = parentAgain.get("child"); + const childAgain = parentAgain.get("child"); file = childAgain.get("file"); ok(file instanceof Parse.File); ok(file.name()); @@ -325,7 +325,7 @@ describe('Parse.File testing', () => { }); it("saving an already saved file", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + const file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); file.save(expectSuccess({ success: function(result) { @@ -333,7 +333,7 @@ describe('Parse.File testing', () => { ok(file.name()); ok(file.url()); notEqual(file.name(), "hello.txt"); - var previousName = file.name(); + const previousName = file.name(); file.save(expectSuccess({ success: function() { @@ -346,13 +346,13 @@ describe('Parse.File testing', () => { }); it("two saves at the same time", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + const file = new Parse.File("hello.txt", data, "text/plain"); - var firstName; - var secondName; + let firstName; + let secondName; - var firstSave = file.save().then(function() { firstName = file.name(); }); - var secondSave = file.save().then(function() { secondName = file.name(); }); + const firstSave = file.save().then(function() { firstName = file.name(); }); + const secondSave = file.save().then(function() { secondName = file.name(); }); Parse.Promise.when(firstSave, secondSave).then(function() { equal(firstName, secondName); @@ -364,9 +364,9 @@ describe('Parse.File testing', () => { }); it("file toJSON testing", done => { - var file = new Parse.File("hello.txt", data, "text/plain"); + const file = new Parse.File("hello.txt", data, "text/plain"); ok(!file.url()); - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.save({ file: file }, expectSuccess({ @@ -378,7 +378,7 @@ describe('Parse.File testing', () => { }); it("content-type used with no extension", done => { - var headers = { + const headers = { 'Content-Type': 'text/html', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -389,7 +389,7 @@ describe('Parse.File testing', () => { body: 'fee fi fo', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.name).toMatch(/\.html$/); request.get(b.url, (error, response) => { if (!response) { @@ -403,7 +403,7 @@ describe('Parse.File testing', () => { }); it("filename is url encoded", done => { - var headers = { + const headers = { 'Content-Type': 'text/html', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -414,26 +414,26 @@ describe('Parse.File testing', () => { body: 'oh emm gee', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.url).toMatch(/hello%20world/); done(); }) }); it('supports array of files', done => { - var file = { + const file = { __type: 'File', url: 'http://meep.meep', name: 'meep' }; - var files = [file, file]; - var obj = new Parse.Object('FilesArrayTest'); + const files = [file, file]; + const obj = new Parse.Object('FilesArrayTest'); obj.set('files', files); obj.save().then(() => { - var query = new Parse.Query('FilesArrayTest'); + const query = new Parse.Query('FilesArrayTest'); return query.first(); }).then((result) => { - var filesAgain = result.get('files'); + const filesAgain = result.get('files'); expect(filesAgain.length).toEqual(2); expect(filesAgain[0].name()).toEqual('meep'); expect(filesAgain[0].url()).toEqual('http://meep.meep'); @@ -442,7 +442,7 @@ describe('Parse.File testing', () => { }); it('validates filename characters', done => { - var headers = { + const headers = { 'Content-Type': 'text/plain', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -452,19 +452,19 @@ describe('Parse.File testing', () => { url: 'http://localhost:8378/1/files/di$avowed.txt', body: 'will fail', }, (error, response, body) => { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.code).toEqual(122); done(); }); }); it('validates filename length', done => { - var headers = { + const headers = { 'Content-Type': 'text/plain', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; - var fileName = 'Onceuponamidnightdrearywhileiponderedweak' + + const fileName = 'Onceuponamidnightdrearywhileiponderedweak' + 'andwearyOveramanyquaintandcuriousvolumeof' + 'forgottenloreWhileinoddednearlynappingsud' + 'denlytherecameatapping'; @@ -473,30 +473,30 @@ describe('Parse.File testing', () => { url: 'http://localhost:8378/1/files/' + fileName, body: 'will fail', }, (error, response, body) => { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.code).toEqual(122); done(); }); }); it('supports a dictionary with file', done => { - var file = { + const file = { __type: 'File', url: 'http://meep.meep', name: 'meep' }; - var dict = { + const dict = { file: file }; - var obj = new Parse.Object('FileObjTest'); + const obj = new Parse.Object('FileObjTest'); obj.set('obj', dict); obj.save().then(() => { - var query = new Parse.Query('FileObjTest'); + const query = new Parse.Query('FileObjTest'); return query.first(); }).then((result) => { - var dictAgain = result.get('obj'); + const dictAgain = result.get('obj'); expect(typeof dictAgain).toEqual('object'); - var fileAgain = dictAgain['file']; + const fileAgain = dictAgain['file']; expect(fileAgain.name()).toEqual('meep'); expect(fileAgain.url()).toEqual('http://meep.meep'); done(); @@ -507,18 +507,18 @@ describe('Parse.File testing', () => { }); it('creates correct url for old files hosted on files.parsetfss.com', done => { - var file = { + const file = { __type: 'File', url: 'http://irrelevant.elephant/', name: 'tfss-123.txt' }; - var obj = new Parse.Object('OldFileTest'); + const obj = new Parse.Object('OldFileTest'); obj.set('oldfile', file); obj.save().then(() => { - var query = new Parse.Query('OldFileTest'); + const query = new Parse.Query('OldFileTest'); return query.first(); }).then((result) => { - var fileAgain = result.get('oldfile'); + const fileAgain = result.get('oldfile'); expect(fileAgain.url()).toEqual( 'http://files.parsetfss.com/test/tfss-123.txt' ); @@ -530,18 +530,18 @@ describe('Parse.File testing', () => { }); it('creates correct url for old files hosted on files.parse.com', done => { - var file = { + const file = { __type: 'File', url: 'http://irrelevant.elephant/', name: 'd6e80979-a128-4c57-a167-302f874700dc-123.txt' }; - var obj = new Parse.Object('OldFileTest'); + const obj = new Parse.Object('OldFileTest'); obj.set('oldfile', file); obj.save().then(() => { - var query = new Parse.Query('OldFileTest'); + const query = new Parse.Query('OldFileTest'); return query.first(); }).then((result) => { - var fileAgain = result.get('oldfile'); + const fileAgain = result.get('oldfile'); expect(fileAgain.url()).toEqual( 'http://files.parse.com/test/d6e80979-a128-4c57-a167-302f874700dc-123.txt' ); @@ -553,14 +553,14 @@ describe('Parse.File testing', () => { }); it('supports files in objects without urls', done => { - var file = { + const file = { __type: 'File', name: '123.txt' }; - var obj = new Parse.Object('FileTest'); + const obj = new Parse.Object('FileTest'); obj.set('file', file); obj.save().then(() => { - var query = new Parse.Query('FileTest'); + const query = new Parse.Query('FileTest'); return query.first(); }).then(result => { const fileAgain = result.get('file'); @@ -576,15 +576,15 @@ describe('Parse.File testing', () => { reconfigureServer({ publicServerURL: 'https://mydomain/parse' }).then(() => { - var file = { + const file = { __type: 'File', name: '123.txt' }; - var obj = new Parse.Object('FileTest'); + const obj = new Parse.Object('FileTest'); obj.set('file', file); return obj.save() }).then(() => { - var query = new Parse.Query('FileTest'); + const query = new Parse.Query('FileTest'); return query.first(); }).then(result => { const fileAgain = result.get('file'); @@ -597,7 +597,7 @@ describe('Parse.File testing', () => { }); it('fails to upload an empty file', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -615,7 +615,7 @@ describe('Parse.File testing', () => { }); it('fails to upload without a file name', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -633,7 +633,7 @@ describe('Parse.File testing', () => { }); it('fails to upload without a file name', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -651,7 +651,7 @@ describe('Parse.File testing', () => { }); it('fails to delete an unkown file', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -670,7 +670,7 @@ describe('Parse.File testing', () => { describe_only_db('mongo')('Gridstore Range tests', () => { it('supports range requests', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -681,7 +681,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -696,7 +696,7 @@ describe('Parse.File testing', () => { }); it('supports small range requests', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -707,7 +707,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -723,7 +723,7 @@ describe('Parse.File testing', () => { // See specs https://www.greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges it('supports getting one byte', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -734,7 +734,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -749,7 +749,7 @@ describe('Parse.File testing', () => { }); it('supports getting last n bytes', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -760,7 +760,7 @@ describe('Parse.File testing', () => { body: 'something different', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -776,7 +776,7 @@ describe('Parse.File testing', () => { }); it('supports getting first n bytes', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -787,7 +787,7 @@ describe('Parse.File testing', () => { body: 'something different', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -802,7 +802,7 @@ describe('Parse.File testing', () => { }); function repeat(string, count) { - var s = string; + let s = string; while (count > 0) { s += string; count--; @@ -811,7 +811,7 @@ describe('Parse.File testing', () => { } it('supports large range requests', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -822,7 +822,7 @@ describe('Parse.File testing', () => { body: repeat('argle bargle', 100) }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', @@ -856,7 +856,7 @@ describe('Parse.File testing', () => { // for fallback tests describe_only_db('postgres')('Default Range tests', () => { it('fallback to regular request', done => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -867,7 +867,7 @@ describe('Parse.File testing', () => { body: 'argle bargle', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.get({ url: b.url, headers: { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', diff --git a/spec/ParseGeoPoint.spec.js b/spec/ParseGeoPoint.spec.js index b7f38fc5..66915c7f 100644 --- a/spec/ParseGeoPoint.spec.js +++ b/spec/ParseGeoPoint.spec.js @@ -2,22 +2,22 @@ // hungry/js/test/parse_geo_point_test.js const rp = require('request-promise'); -var TestObject = Parse.Object.extend('TestObject'); +const TestObject = Parse.Object.extend('TestObject'); describe('Parse.GeoPoint testing', () => { it('geo point roundtrip', (done) => { - var point = new Parse.GeoPoint(44.0, -11.0); - var obj = new TestObject(); + const point = new Parse.GeoPoint(44.0, -11.0); + const obj = new TestObject(); obj.set('location', point); obj.set('name', 'Ferndale'); obj.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var pointAgain = results[0].get('location'); + const pointAgain = results[0].get('location'); ok(pointAgain); equal(pointAgain.latitude, 44.0); equal(pointAgain.longitude, -11.0); @@ -37,7 +37,7 @@ describe('Parse.GeoPoint testing', () => { obj.set('location', newPoint); return obj.save(); }).then(() => { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.get(obj.id); }).then((result) => { const point = result.get('location'); @@ -48,8 +48,8 @@ describe('Parse.GeoPoint testing', () => { }); it('has the correct __type field in the json response', done => { - var point = new Parse.GeoPoint(44.0, -11.0); - var obj = new TestObject(); + const point = new Parse.GeoPoint(44.0, -11.0); + const obj = new TestObject(); obj.set('location', point); obj.set('name', 'Zhoul') obj.save(null, { @@ -69,8 +69,8 @@ describe('Parse.GeoPoint testing', () => { }); it('creating geo point exception two fields', (done) => { - var point = new Parse.GeoPoint(20, 20); - var obj = new TestObject(); + const point = new Parse.GeoPoint(20, 20); + const obj = new TestObject(); obj.set('locationOne', point); obj.set('locationTwo', point); obj.save().then(() => { @@ -83,8 +83,8 @@ describe('Parse.GeoPoint testing', () => { // TODO: This should also have support in postgres, or higher level database agnostic support. it_exclude_dbs(['postgres'])('updating geo point exception two fields', (done) => { - var point = new Parse.GeoPoint(20, 20); - var obj = new TestObject(); + const point = new Parse.GeoPoint(20, 20); + const obj = new TestObject(); obj.set('locationOne', point); obj.save(null, { success: (obj) => { @@ -100,10 +100,10 @@ describe('Parse.GeoPoint testing', () => { }); it('geo line', (done) => { - var line = []; - for (var i = 0; i < 10; ++i) { - var obj = new TestObject(); - var point = new Parse.GeoPoint(i * 4.0 - 12.0, i * 3.2 - 11.0); + const line = []; + for (let i = 0; i < 10; ++i) { + const obj = new TestObject(); + const point = new Parse.GeoPoint(i * 4.0 - 12.0, i * 3.2 - 11.0); obj.set('location', point); obj.set('construct', 'line'); obj.set('seq', i); @@ -111,8 +111,8 @@ describe('Parse.GeoPoint testing', () => { } Parse.Object.saveAll(line, { success: function() { - var query = new Parse.Query(TestObject); - var point = new Parse.GeoPoint(24, 19); + const query = new Parse.Query(TestObject); + const point = new Parse.GeoPoint(24, 19); query.equalTo('construct', 'line'); query.withinMiles('location', point, 10000); query.find({ @@ -128,17 +128,17 @@ describe('Parse.GeoPoint testing', () => { }); it('geo max distance large', (done) => { - var objects = []; + const objects = []; [0, 1, 2].map(function(i) { - var obj = new TestObject(); - var point = new Parse.GeoPoint(0.0, i * 45.0); + const obj = new TestObject(); + const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); obj.set('index', i); objects.push(obj); }); Parse.Object.saveAll(objects).then(() => { - var query = new Parse.Query(TestObject); - var point = new Parse.GeoPoint(1.0, -1.0); + const query = new Parse.Query(TestObject); + const point = new Parse.GeoPoint(1.0, -1.0); query.withinRadians('location', point, 3.14); return query.find(); }).then((results) => { @@ -151,17 +151,17 @@ describe('Parse.GeoPoint testing', () => { }); it('geo max distance medium', (done) => { - var objects = []; + const objects = []; [0, 1, 2].map(function(i) { - var obj = new TestObject(); - var point = new Parse.GeoPoint(0.0, i * 45.0); + const obj = new TestObject(); + const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); obj.set('index', i); objects.push(obj); }); Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(TestObject); - var point = new Parse.GeoPoint(1.0, -1.0); + const query = new Parse.Query(TestObject); + const point = new Parse.GeoPoint(1.0, -1.0); query.withinRadians('location', point, 3.14 * 0.5); query.find({ success: function(results) { @@ -175,17 +175,17 @@ describe('Parse.GeoPoint testing', () => { }); it('geo max distance small', (done) => { - var objects = []; + const objects = []; [0, 1, 2].map(function(i) { - var obj = new TestObject(); - var point = new Parse.GeoPoint(0.0, i * 45.0); + const obj = new TestObject(); + const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); obj.set('index', i); objects.push(obj); }); Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(TestObject); - var point = new Parse.GeoPoint(1.0, -1.0); + const query = new Parse.Query(TestObject); + const point = new Parse.GeoPoint(1.0, -1.0); query.withinRadians('location', point, 3.14 * 0.25); query.find({ success: function(results) { @@ -197,16 +197,16 @@ describe('Parse.GeoPoint testing', () => { }); }); - var makeSomeGeoPoints = function(callback) { - var sacramento = new TestObject(); + const makeSomeGeoPoints = function(callback) { + const sacramento = new TestObject(); sacramento.set('location', new Parse.GeoPoint(38.52, -121.50)); sacramento.set('name', 'Sacramento'); - var honolulu = new TestObject(); + const honolulu = new TestObject(); honolulu.set('location', new Parse.GeoPoint(21.35, -157.93)); honolulu.set('name', 'Honolulu'); - var sf = new TestObject(); + const sf = new TestObject(); sf.set('location', new Parse.GeoPoint(37.75, -122.68)); sf.set('name', 'San Francisco'); @@ -215,8 +215,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in km everywhere', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); // Honolulu is 4300 km away from SFO on a sphere ;) query.withinKilometers('location', sfo, 4800.0); query.find({ @@ -230,8 +230,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in km california', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinKilometers('location', sfo, 3700.0); query.find({ success: function(results) { @@ -246,8 +246,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in km bay area', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinKilometers('location', sfo, 100.0); query.find({ success: function(results) { @@ -261,8 +261,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in km mid peninsula', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinKilometers('location', sfo, 10.0); query.find({ success: function(results) { @@ -275,8 +275,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in miles everywhere', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinMiles('location', sfo, 2600.0); query.find({ success: function(results) { @@ -289,8 +289,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in miles california', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinMiles('location', sfo, 2200.0); query.find({ success: function(results) { @@ -305,8 +305,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in miles bay area', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); // 100km is 62 miles... query.withinMiles('location', sfo, 62.0); query.find({ @@ -321,8 +321,8 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance in miles mid peninsula', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.withinMiles('location', sfo, 10.0); query.find({ success: function(results) { @@ -335,8 +335,8 @@ describe('Parse.GeoPoint testing', () => { it('returns nearest location', (done) => { makeSomeGeoPoints(function() { - var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); - var query = new Parse.Query(TestObject); + const sfo = new Parse.GeoPoint(37.6189722, -122.3748889); + const query = new Parse.Query(TestObject); query.near('location', sfo); query.find({ success: function(results) { @@ -368,16 +368,16 @@ describe('Parse.GeoPoint testing', () => { }); it('supports a sub-object with a geo point', done => { - var point = new Parse.GeoPoint(44.0, -11.0); - var obj = new TestObject(); + const point = new Parse.GeoPoint(44.0, -11.0); + const obj = new TestObject(); obj.set('subobject', { location: point }); obj.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var pointAgain = results[0].get('subobject')['location']; + const pointAgain = results[0].get('subobject')['location']; ok(pointAgain); equal(pointAgain.latitude, 44.0); equal(pointAgain.longitude, -11.0); @@ -389,17 +389,17 @@ describe('Parse.GeoPoint testing', () => { }); it('supports array of geo points', done => { - var point1 = new Parse.GeoPoint(44.0, -11.0); - var point2 = new Parse.GeoPoint(22.0, -55.0); - var obj = new TestObject(); + const point1 = new Parse.GeoPoint(44.0, -11.0); + const point2 = new Parse.GeoPoint(22.0, -55.0); + const obj = new TestObject(); obj.set('locations', [ point1, point2 ]); obj.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); - var locations = results[0].get('locations'); + const locations = results[0].get('locations'); expect(locations.length).toEqual(2); expect(locations[0]).toEqual(point1); expect(locations[1]).toEqual(point2); @@ -411,8 +411,8 @@ describe('Parse.GeoPoint testing', () => { }); it('equalTo geopoint', (done) => { - var point = new Parse.GeoPoint(44.0, -11.0); - var obj = new TestObject(); + const point = new Parse.GeoPoint(44.0, -11.0); + const obj = new TestObject(); obj.set('location', point); obj.save().then(() => { const query = new Parse.Query(TestObject); diff --git a/spec/ParseGlobalConfig.spec.js b/spec/ParseGlobalConfig.spec.js index 45411d1e..46f9c078 100644 --- a/spec/ParseGlobalConfig.spec.js +++ b/spec/ParseGlobalConfig.spec.js @@ -1,6 +1,6 @@ 'use strict'; -var request = require('request'); +const request = require('request'); const Config = require('../src/Config'); describe('a GlobalConfig', () => { diff --git a/spec/ParseHooks.spec.js b/spec/ParseHooks.spec.js index 0bc5650b..86dcd8e6 100644 --- a/spec/ParseHooks.spec.js +++ b/spec/ParseHooks.spec.js @@ -1,16 +1,16 @@ "use strict"; /* global describe, it, expect, fail, Parse */ -var request = require('request'); -var triggers = require('../src/triggers'); -var HooksController = require('../src/Controllers/HooksController').default; -var express = require("express"); -var bodyParser = require('body-parser'); +const request = require('request'); +const triggers = require('../src/triggers'); +const HooksController = require('../src/Controllers/HooksController').default; +const express = require("express"); +const bodyParser = require('body-parser'); -var port = 12345; -var hookServerURL = "http://localhost:" + port; +const port = 12345; +const hookServerURL = "http://localhost:" + port; const AppCache = require('../src/cache').AppCache; -var app = express(); +const app = express(); app.use(bodyParser.json({ 'type': '*/*' })) app.listen(12345); @@ -273,14 +273,14 @@ describe('Hooks', () => { it("should create hooks and properly preload them", (done) => { - var promises = []; - for (var i = 0; i < 5; i++) { + const promises = []; + for (let i = 0; i < 5; i++) { promises.push(Parse.Hooks.createTrigger("MyClass" + i, "beforeSave", "http://url.com/beforeSave/" + i)); promises.push(Parse.Hooks.createFunction("AFunction" + i, "http://url.com/function" + i)); } Parse.Promise.when(promises).then(function(){ - for (var i = 0; i < 5; i++) { + for (let i = 0; i < 5; i++) { // Delete everything from memory, as the server just started triggers.removeTrigger("beforeSave", "MyClass" + i, Parse.applicationId); triggers.removeFunction("AFunction" + i, Parse.applicationId); @@ -294,7 +294,7 @@ describe('Hooks', () => { fail('Should properly create all hooks'); done(); }).then(function() { - for (var i = 0; i < 5; i++) { + for (let i = 0; i < 5; i++) { expect(triggers.getTrigger("MyClass" + i, "beforeSave", Parse.applicationId)).not.toBeUndefined(); expect(triggers.getFunction("AFunction" + i, Parse.applicationId)).not.toBeUndefined(); } @@ -414,10 +414,10 @@ describe('Hooks', () => { it("should run the beforeSave hook on the test server", (done) => { - var triggerCount = 0; + let triggerCount = 0; app.post("/BeforeSaveSome", function(req, res) { triggerCount++; - var object = req.body.object; + const object = req.body.object; object.hello = "world"; // Would need parse cloud express to set much more // But this should override the key upon return @@ -442,7 +442,7 @@ describe('Hooks', () => { it("beforeSave hooks should correctly handle responses containing entire object", (done) => { app.post("/BeforeSaveSome2", function(req, res) { - var object = Parse.Object.fromJSON(req.body.object); + const object = Parse.Object.fromJSON(req.body.object); object.set('hello', "world"); res.json({success: object}); }); @@ -461,11 +461,11 @@ describe('Hooks', () => { }); it("should run the afterSave hook on the test server", (done) => { - var triggerCount = 0; - var newObjectId; + let triggerCount = 0; + let newObjectId; app.post("/AfterSaveSome", function(req, res) { triggerCount++; - var obj = new Parse.Object("AnotherObject"); + const obj = new Parse.Object("AnotherObject"); obj.set("foo", "bar"); obj.save().then(function(obj){ newObjectId = obj.id; @@ -477,7 +477,7 @@ describe('Hooks', () => { const obj = new Parse.Object("SomeRandomObject"); return obj.save(); }).then(function() { - var promise = new Parse.Promise(); + const promise = new Parse.Promise(); // Wait a bit here as it's an after save setTimeout(() => { expect(triggerCount).toBe(1); diff --git a/spec/ParseInstallation.spec.js b/spec/ParseInstallation.spec.js index 05de2908..9102291b 100644 --- a/spec/ParseInstallation.spec.js +++ b/spec/ParseInstallation.spec.js @@ -26,9 +26,9 @@ describe('Installations', () => { }); it('creates an android installation with ids', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var device = 'android'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; @@ -36,7 +36,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.installationId).toEqual(installId); expect(obj.deviceType).toEqual(device); done(); @@ -44,9 +44,9 @@ describe('Installations', () => { }); it('creates an ios installation with ids', (done) => { - var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var device = 'ios'; - var input = { + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const device = 'ios'; + const input = { 'deviceToken': t, 'deviceType': device }; @@ -54,7 +54,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.deviceToken).toEqual(t); expect(obj.deviceType).toEqual(device); done(); @@ -62,9 +62,9 @@ describe('Installations', () => { }); it('creates an embedded installation with ids', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var device = 'embedded'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'embedded'; + const input = { 'installationId': installId, 'deviceType': device }; @@ -72,7 +72,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.installationId).toEqual(installId); expect(obj.deviceType).toEqual(device); done(); @@ -80,9 +80,9 @@ describe('Installations', () => { }); it('creates an android installation with all fields', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var device = 'android'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device, 'channels': ['foo', 'bar'] @@ -91,7 +91,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.installationId).toEqual(installId); expect(obj.deviceType).toEqual(device); expect(typeof obj.channels).toEqual('object'); @@ -103,9 +103,9 @@ describe('Installations', () => { }); it('creates an ios installation with all fields', (done) => { - var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var device = 'ios'; - var input = { + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const device = 'ios'; + const input = { 'deviceToken': t, 'deviceType': device, 'channels': ['foo', 'bar'] @@ -114,7 +114,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.deviceToken).toEqual(t); expect(obj.deviceType).toEqual(device); expect(typeof obj.channels).toEqual('object'); @@ -126,9 +126,9 @@ describe('Installations', () => { }); it('should properly fail queying installations', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var device = 'android'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; @@ -147,9 +147,9 @@ describe('Installations', () => { }); it('should properly queying installations with masterKey', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var device = 'android'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; @@ -159,7 +159,7 @@ describe('Installations', () => { return query.find({useMasterKey: true}); }).then((results) => { expect(results.length).toEqual(1); - var obj = results[0].toJSON(); + const obj = results[0].toJSON(); expect(obj.installationId).toEqual(installId); expect(obj.deviceType).toEqual(device); done(); @@ -170,7 +170,7 @@ describe('Installations', () => { }); it('fails with missing ids', (done) => { - var input = { + const input = { 'deviceType': 'android', 'channels': ['foo', 'bar'] }; @@ -185,8 +185,8 @@ describe('Installations', () => { }); it('fails for android with missing type', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const input = { 'installationId': installId, 'channels': ['foo', 'bar'] }; @@ -201,8 +201,8 @@ describe('Installations', () => { }); it('creates an object with custom fields', (done) => { - var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var input = { + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const input = { 'deviceToken': t, 'deviceType': 'ios', 'channels': ['foo', 'bar'], @@ -212,7 +212,7 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(obj.custom).toEqual('allowed'); done(); }).catch((error) => { console.log(error); }); @@ -221,16 +221,16 @@ describe('Installations', () => { // Note: did not port test 'TestObjectIDForIdentifiers' it('merging when installationId already exists', (done) => { - var installId1 = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var input = { + const installId1 = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const input = { 'deviceToken': t, 'deviceType': 'ios', 'installationId': installId1, 'channels': ['foo', 'bar'] }; - var firstObject; - var secondObject; + let firstObject; + let secondObject; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { @@ -253,23 +253,23 @@ describe('Installations', () => { }); it('merging when two objects both only have one id', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input1 = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const input1 = { 'installationId': installId, 'deviceType': 'ios' }; - var input2 = { + const input2 = { 'deviceToken': t, 'deviceType': 'ios' }; - var input3 = { + const input3 = { 'deviceToken': t, 'installationId': installId, 'deviceType': 'ios' }; - var firstObject; - var secondObject; + let firstObject; + let secondObject; rest.create(config, auth.nobody(config), '_Installation', input1) .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { @@ -299,11 +299,11 @@ describe('Installations', () => { }); xit('creating multiple devices with same device token works', (done) => { - var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; - var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - var installId3 = '33333333-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; + const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; + const installId3 = '33333333-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const input = { 'installationId': installId1, 'deviceType': 'ios', 'deviceToken': t @@ -330,7 +330,7 @@ describe('Installations', () => { }); it('updating with new channels', (done) => { - var input = { + const input = { installationId: '12345678-abcd-abcd-abcd-123456789abc', deviceType: 'android', channels: ['foo', 'bar'] @@ -339,8 +339,8 @@ describe('Installations', () => { .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); - var objectId = results[0].objectId; - var update = { + const objectId = results[0].objectId; + const update = { 'channels': ['baz'] }; return rest.update(config, auth.nobody(config), '_Installation', { objectId }, update); @@ -358,9 +358,9 @@ describe('Installations', () => { }); it('update android fails with new installation id', (done) => { - var installId1 = '12345678-abcd-abcd-abcd-123456789abc'; - var installId2 = '87654321-abcd-abcd-abcd-123456789abc'; - var input = { + const installId1 = '12345678-abcd-abcd-abcd-123456789abc'; + const installId2 = '87654321-abcd-abcd-abcd-123456789abc'; + let input = { 'installationId': installId1, 'deviceType': 'android', 'channels': ['foo', 'bar'] @@ -381,9 +381,9 @@ describe('Installations', () => { }); it('update ios fails with new deviceToken and no installationId', (done) => { - var a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var input = { + const a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + let input = { 'deviceToken': a, 'deviceType': 'ios', 'channels': ['foo', 'bar'] @@ -403,10 +403,10 @@ describe('Installations', () => { }); it('update ios updates device token', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + let input = { 'installationId': installId, 'deviceType': 'ios', 'deviceToken': t, @@ -435,8 +435,8 @@ describe('Installations', () => { }); it('update fails to change deviceType', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + let input = { 'installationId': installId, 'deviceType': 'android', 'channels': ['foo', 'bar'] @@ -459,8 +459,8 @@ describe('Installations', () => { }); it('update android with custom field', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + let input = { 'installationId': installId, 'deviceType': 'android', 'channels': ['foo', 'bar'] @@ -483,16 +483,16 @@ describe('Installations', () => { }); it('update android device token with duplicate device token', (done) => { - var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; - var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; + const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId1, 'deviceToken': t, 'deviceType': 'android' }; - var firstObject; - var secondObject; + let firstObject; + let secondObject; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => { input = { @@ -528,16 +528,16 @@ describe('Installations', () => { }); it('update ios device token with duplicate device token', (done) => { - var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; - var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; + const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId1, 'deviceToken': t, 'deviceType': 'ios' }; - var firstObject; - var secondObject; + let firstObject; + let secondObject; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => { input = { @@ -577,10 +577,10 @@ describe('Installations', () => { }); xit('update ios device token with duplicate token different app', (done) => { - var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; - var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; + const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const input = { 'installationId': installId1, 'deviceToken': t, 'deviceType': 'ios', @@ -605,9 +605,9 @@ describe('Installations', () => { }); it('update ios token and channels', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId, 'deviceType': 'ios' }; @@ -635,9 +635,9 @@ describe('Installations', () => { }); it('update ios linking two existing objects', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId, 'deviceType': 'ios' }; @@ -673,9 +673,9 @@ describe('Installations', () => { }); it('update is linking two existing objects w/ increment', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId, 'deviceType': 'ios' }; @@ -716,14 +716,14 @@ describe('Installations', () => { }); it('update is linking two existing with installation id', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId, 'deviceType': 'ios' }; - var installObj; - var tokenObj; + let installObj; + let tokenObj; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { @@ -759,14 +759,14 @@ describe('Installations', () => { }); it('update is linking two existing with installation id w/ op', (done) => { - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + let input = { 'installationId': installId, 'deviceType': 'ios' }; - var installObj; - var tokenObj; + let installObj; + let tokenObj; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { @@ -817,9 +817,9 @@ describe('Installations', () => { // imported installation, then we should reuse the existing installation // object in case the developer already added additional fields via Data // Browser or REST API (e.g. channel targeting info). - var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - var installId = '12345678-abcd-abcd-abcd-123456789abc'; - var input = { + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + let input = { 'deviceToken': t, 'deviceType': 'ios' }; diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index 41a8b5af..9f347747 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -1,19 +1,19 @@ -var Parse = require('parse/node'); -var ParseLiveQueryServer = require('../src/LiveQuery/ParseLiveQueryServer').ParseLiveQueryServer; -var ParseServer = require('../src/ParseServer').default; +const Parse = require('parse/node'); +const ParseLiveQueryServer = require('../src/LiveQuery/ParseLiveQueryServer').ParseLiveQueryServer; +const ParseServer = require('../src/ParseServer').default; // Global mock info -var queryHashValue = 'hash'; -var testUserId = 'userId'; -var testClassName = 'TestObject'; +const queryHashValue = 'hash'; +const testUserId = 'userId'; +const testClassName = 'TestObject'; describe('ParseLiveQueryServer', function() { beforeEach(function(done) { // Mock ParseWebSocketServer - var mockParseWebSocketServer = jasmine.createSpy('ParseWebSocketServer'); + const mockParseWebSocketServer = jasmine.createSpy('ParseWebSocketServer'); jasmine.mockLibrary('../src/LiveQuery/ParseWebSocketServer', 'ParseWebSocketServer', mockParseWebSocketServer); // Mock Client - var mockClient = function(id, socket, hasMasterKey) { + const mockClient = function(id, socket, hasMasterKey) { this.pushConnect = jasmine.createSpy('pushConnect'); this.pushSubscribe = jasmine.createSpy('pushSubscribe'); this.pushUnsubscribe = jasmine.createSpy('pushUnsubscribe'); @@ -30,19 +30,19 @@ describe('ParseLiveQueryServer', function() { mockClient.pushError = jasmine.createSpy('pushError'); jasmine.mockLibrary('../src/LiveQuery/Client', 'Client', mockClient); // Mock Subscription - var mockSubscriotion = function() { + const mockSubscriotion = function() { this.addClientSubscription = jasmine.createSpy('addClientSubscription'); this.deleteClientSubscription = jasmine.createSpy('deleteClientSubscription'); } jasmine.mockLibrary('../src/LiveQuery/Subscription', 'Subscription', mockSubscriotion); // Mock queryHash - var mockQueryHash = jasmine.createSpy('matchesQuery').and.returnValue(queryHashValue); + const mockQueryHash = jasmine.createSpy('matchesQuery').and.returnValue(queryHashValue); jasmine.mockLibrary('../src/LiveQuery/QueryTools', 'queryHash', mockQueryHash); // Mock matchesQuery - var mockMatchesQuery = jasmine.createSpy('matchesQuery').and.returnValue(true); + const mockMatchesQuery = jasmine.createSpy('matchesQuery').and.returnValue(true); jasmine.mockLibrary('../src/LiveQuery/QueryTools', 'matchesQuery', mockMatchesQuery); // Mock ParsePubSub - var mockParsePubSub = { + const mockParsePubSub = { createPublisher: function() { return { publish: jasmine.createSpy('publish'), @@ -58,7 +58,7 @@ describe('ParseLiveQueryServer', function() { }; jasmine.mockLibrary('../src/LiveQuery/ParsePubSub', 'ParsePubSub', mockParsePubSub); // Make mock SessionTokenCache - var mockSessionTokenCache = function(){ + const mockSessionTokenCache = function(){ this.getUserId = function(sessionToken){ if (typeof sessionToken === 'undefined') { return Parse.Promise.as(undefined); @@ -74,8 +74,8 @@ describe('ParseLiveQueryServer', function() { }); it('can be initialized', function() { - var httpServer = {}; - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, httpServer); + const httpServer = {}; + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, httpServer); expect(parseLiveQueryServer.clientId).toBeUndefined(); expect(parseLiveQueryServer.clients.size).toBe(0); @@ -83,8 +83,8 @@ describe('ParseLiveQueryServer', function() { }); it('can be initialized from ParseServer', function() { - var httpServer = {}; - var parseLiveQueryServer = ParseServer.createLiveQueryServer(httpServer, {}); + const httpServer = {}; + const parseLiveQueryServer = ParseServer.createLiveQueryServer(httpServer, {}); expect(parseLiveQueryServer.clientId).toBeUndefined(); expect(parseLiveQueryServer.clients.size).toBe(0); @@ -92,7 +92,7 @@ describe('ParseLiveQueryServer', function() { }); it('can be initialized from ParseServer without httpServer', function(done) { - var parseLiveQueryServer = ParseServer.createLiveQueryServer(undefined, { + const parseLiveQueryServer = ParseServer.createLiveQueryServer(undefined, { port: 22345 }); @@ -103,7 +103,7 @@ describe('ParseLiveQueryServer', function() { }); it('can be initialized through ParseServer without liveQueryServerOptions', function(done) { - var parseServer = ParseServer.start({ + const parseServer = ParseServer.start({ appId: 'hello', masterKey: 'world', port: 22345, @@ -117,11 +117,11 @@ describe('ParseLiveQueryServer', function() { expect(parseServer.liveQueryServer).not.toBeUndefined(); expect(parseServer.liveQueryServer.server).toBe(parseServer.server); - parseServer.server.close(done); + parseServer.server.close(() => done()); }); it('can be initialized through ParseServer with liveQueryServerOptions', function(done) { - var parseServer = ParseServer.start({ + const parseServer = ParseServer.start({ appId: 'hello', masterKey: 'world', port: 22346, @@ -138,13 +138,13 @@ describe('ParseLiveQueryServer', function() { expect(parseServer.liveQueryServer).not.toBeUndefined(); expect(parseServer.liveQueryServer.server).not.toBe(parseServer.server); parseServer.liveQueryServer.server.close(); - parseServer.server.close(done); + parseServer.server.close(() => done()); }); it('can handle connect command', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var parseWebSocket = { + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseWebSocket = { clientId: -1 }; parseLiveQueryServer._validateKeys = jasmine.createSpy('validateKeys').and.returnValue(true); @@ -154,40 +154,40 @@ describe('ParseLiveQueryServer', function() { expect(parseLiveQueryServer.clients.size).toBe(1); const firstKey = clientKeys.next().value; expect(parseWebSocket.clientId).toBe(firstKey); - var client = parseLiveQueryServer.clients.get(firstKey); + const client = parseLiveQueryServer.clients.get(firstKey); expect(client).not.toBeNull(); // Make sure we send connect response to the client expect(client.pushConnect).toHaveBeenCalled(); }); it('can handle subscribe command without clientId', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var incompleteParseConn = { + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const incompleteParseConn = { }; parseLiveQueryServer._handleSubscribe(incompleteParseConn, {}); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can handle subscribe command with new query', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Handle mock subscription - var parseWebSocket = { + const parseWebSocket = { clientId: clientId }; - var query = { + const query = { className: 'test', where: { key: 'value' }, fields: [ 'test' ] } - var requestId = 2; - var request = { + const requestId = 2; + const request = { query: query, requestId: requestId, sessionToken: 'sessionToken' @@ -195,18 +195,18 @@ describe('ParseLiveQueryServer', function() { parseLiveQueryServer._handleSubscribe(parseWebSocket, request); // Make sure we add the subscription to the server - var subscriptions = parseLiveQueryServer.subscriptions; + const subscriptions = parseLiveQueryServer.subscriptions; expect(subscriptions.size).toBe(1); expect(subscriptions.get(query.className)).not.toBeNull(); - var classSubscriptions = subscriptions.get(query.className); + const classSubscriptions = subscriptions.get(query.className); expect(classSubscriptions.size).toBe(1); expect(classSubscriptions.get('hash')).not.toBeNull(); // TODO(check subscription constructor to verify we pass the right argument) // Make sure we add clientInfo to the subscription - var subscription = classSubscriptions.get('hash'); + const subscription = classSubscriptions.get('hash'); expect(subscription.addClientSubscription).toHaveBeenCalledWith(clientId, requestId); // Make sure we add subscriptionInfo to the client - var args = client.addSubscriptionInfo.calls.first().args; + const args = client.addSubscriptionInfo.calls.first().args; expect(args[0]).toBe(requestId); expect(args[1].fields).toBe(query.fields); expect(args[1].sessionToken).toBe(request.sessionToken); @@ -215,18 +215,18 @@ describe('ParseLiveQueryServer', function() { }); it('can handle subscribe command with existing query', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Add two mock clients - var clientId = 1; + const clientId = 1; addMockClient(parseLiveQueryServer, clientId); - var clientIdAgain = 2; - var clientAgain = addMockClient(parseLiveQueryServer, clientIdAgain); + const clientIdAgain = 2; + const clientAgain = addMockClient(parseLiveQueryServer, clientIdAgain); // Add subscription for mock client 1 - var parseWebSocket = { + const parseWebSocket = { clientId: clientId }; - var requestId = 2; - var query = { + const requestId = 2; + const query = { className: 'test', where: { key: 'value' @@ -235,30 +235,30 @@ describe('ParseLiveQueryServer', function() { } addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket, query); // Add subscription for mock client 2 - var parseWebSocketAgain = { + const parseWebSocketAgain = { clientId: clientIdAgain }; - var queryAgain = { + const queryAgain = { className: 'test', where: { key: 'value' }, fields: [ 'testAgain' ] } - var requestIdAgain = 1; + const requestIdAgain = 1; addMockSubscription(parseLiveQueryServer, clientIdAgain, requestIdAgain, parseWebSocketAgain, queryAgain); // Make sure we only have one subscription - var subscriptions = parseLiveQueryServer.subscriptions; + const subscriptions = parseLiveQueryServer.subscriptions; expect(subscriptions.size).toBe(1); expect(subscriptions.get(query.className)).not.toBeNull(); - var classSubscriptions = subscriptions.get(query.className); + const classSubscriptions = subscriptions.get(query.className); expect(classSubscriptions.size).toBe(1); expect(classSubscriptions.get('hash')).not.toBeNull(); // Make sure we add clientInfo to the subscription - var subscription = classSubscriptions.get('hash'); + const subscription = classSubscriptions.get('hash'); // Make sure client 2 info has been added - var args = subscription.addClientSubscription.calls.mostRecent().args; + let args = subscription.addClientSubscription.calls.mostRecent().args; expect(args).toEqual([clientIdAgain, requestIdAgain]); // Make sure we add subscriptionInfo to the client 2 args = clientAgain.addSubscriptionInfo.calls.mostRecent().args; @@ -267,59 +267,59 @@ describe('ParseLiveQueryServer', function() { }); it('can handle unsubscribe command without clientId', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var incompleteParseConn = { + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const incompleteParseConn = { }; parseLiveQueryServer._handleUnsubscribe(incompleteParseConn, {}); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can handle unsubscribe command without not existed client', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var parseWebSocket = { + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseWebSocket = { clientId: 1 }; parseLiveQueryServer._handleUnsubscribe(parseWebSocket, {}); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can handle unsubscribe command without not existed query', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Add mock client - var clientId = 1; + const clientId = 1; addMockClient(parseLiveQueryServer, clientId); // Handle unsubscribe command - var parseWebSocket = { + const parseWebSocket = { clientId: 1 }; parseLiveQueryServer._handleUnsubscribe(parseWebSocket, {}); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can handle unsubscribe command', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add subscription for mock client - var parseWebSocket = { + const parseWebSocket = { clientId: 1 }; - var requestId = 2; - var subscription = addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket); + const requestId = 2; + const subscription = addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket); // Mock client.getSubscriptionInfo - var subscriptionInfo = client.addSubscriptionInfo.calls.mostRecent().args[1]; + const subscriptionInfo = client.addSubscriptionInfo.calls.mostRecent().args[1]; client.getSubscriptionInfo = function() { return subscriptionInfo; }; // Handle unsubscribe command - var requestAgain = { + const requestAgain = { requestId: requestId }; parseLiveQueryServer._handleUnsubscribe(parseWebSocket, requestAgain); @@ -329,44 +329,44 @@ describe('ParseLiveQueryServer', function() { // Make sure we delete client from subscription expect(subscription.deleteClientSubscription).toHaveBeenCalledWith(clientId, requestId); // Make sure we clear subscription in the server - var subscriptions = parseLiveQueryServer.subscriptions; + const subscriptions = parseLiveQueryServer.subscriptions; expect(subscriptions.size).toBe(0); }); it('can set connect command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Register mock connect/subscribe/unsubscribe handler for the server parseLiveQueryServer._handleConnect = jasmine.createSpy('_handleSubscribe'); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check connect request - var connectRequest = { + const connectRequest = { op: 'connect', applicationId: '1' }; // Trigger message event parseWebSocket.emit('message', connectRequest); // Make sure _handleConnect is called - var args = parseLiveQueryServer._handleConnect.calls.mostRecent().args; + const args = parseLiveQueryServer._handleConnect.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); }); it('can set subscribe command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Register mock connect/subscribe/unsubscribe handler for the server parseLiveQueryServer._handleSubscribe = jasmine.createSpy('_handleSubscribe'); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check subscribe request - var subscribeRequest = JSON.stringify({ + const subscribeRequest = JSON.stringify({ op: 'subscribe', requestId: 1, query: {className: 'Test', where: {}} @@ -374,47 +374,47 @@ describe('ParseLiveQueryServer', function() { // Trigger message event parseWebSocket.emit('message', subscribeRequest); // Make sure _handleSubscribe is called - var args = parseLiveQueryServer._handleSubscribe.calls.mostRecent().args; + const args = parseLiveQueryServer._handleSubscribe.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(subscribeRequest); }); it('can set unsubscribe command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Register mock connect/subscribe/unsubscribe handler for the server parseLiveQueryServer._handleUnsubscribe = jasmine.createSpy('_handleSubscribe'); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check unsubscribe request - var unsubscribeRequest = JSON.stringify({op: 'unsubscribe', requestId: 1}); + const unsubscribeRequest = JSON.stringify({op: 'unsubscribe', requestId: 1}); // Trigger message event parseWebSocket.emit('message', unsubscribeRequest); // Make sure _handleUnsubscribe is called - var args = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; + const args = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(unsubscribeRequest); }); it('can set update command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Register mock connect/subscribe/unsubscribe handler for the server spyOn(parseLiveQueryServer, '_handleUpdateSubscription').and.callThrough(); spyOn(parseLiveQueryServer, '_handleUnsubscribe').and.callThrough(); spyOn(parseLiveQueryServer, '_handleSubscribe').and.callThrough(); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check updateRequest request - var updateRequest = JSON.stringify({ + const updateRequest = JSON.stringify({ op: 'update', requestId: 1, query: {className: 'Test', where: {}} @@ -422,7 +422,7 @@ describe('ParseLiveQueryServer', function() { // Trigger message event parseWebSocket.emit('message', updateRequest); // Make sure _handleUnsubscribe is called - var args = parseLiveQueryServer._handleUpdateSubscription.calls.mostRecent().args; + const args = parseLiveQueryServer._handleUpdateSubscription.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(updateRequest); expect(parseLiveQueryServer._handleUnsubscribe).toHaveBeenCalled(); @@ -433,41 +433,41 @@ describe('ParseLiveQueryServer', function() { }); it('can set missing command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check invalid request - var invalidRequest = '{}'; + const invalidRequest = '{}'; // Trigger message event parseWebSocket.emit('message', invalidRequest); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can set unknown command message handler for a parseWebSocket', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock parseWebsocket - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); // Check unknown request - var unknownRequest = '{"op":"unknown"}'; + const unknownRequest = '{"op":"unknown"}'; // Trigger message event parseWebSocket.emit('message', unknownRequest); - var Client = require('../src/LiveQuery/Client').Client; + const Client = require('../src/LiveQuery/Client').Client; expect(Client.pushError).toHaveBeenCalled(); }); it('can set disconnect command message handler for a parseWebSocket which has not registered to the server', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); parseWebSocket.clientId = 1; // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); @@ -483,9 +483,9 @@ describe('ParseLiveQueryServer', function() { } const spy = spyOn(cloudCodeHandler, 'handler').and.callThrough(); Parse.Cloud.onLiveQueryEvent(cloudCodeHandler.handler); - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var EventEmitter = require('events'); - var parseWebSocket = new EventEmitter(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const EventEmitter = require('events'); + const parseWebSocket = new EventEmitter(); parseWebSocket.clientId = 1; // Register message handlers for the parseWebSocket parseLiveQueryServer._onConnect(parseWebSocket); @@ -502,15 +502,15 @@ describe('ParseLiveQueryServer', function() { // TODO: Test server can set disconnect command message handler for a parseWebSocket it('has no subscription and can handle object delete command', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make deletedParseObject - var parseObject = new Parse.Object(testClassName); + const parseObject = new Parse.Object(testClassName); parseObject._finishFetch({ key: 'value', className: testClassName }); // Make mock message - var message = { + const message = { currentParseObject: parseObject }; // Make sure we do not crash in this case @@ -518,25 +518,25 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object delete command which does not match any subscription', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make deletedParseObject - var parseObject = new Parse.Object(testClassName); + const parseObject = new Parse.Object(testClassName); parseObject._finishFetch({ key: 'value', className: testClassName }); // Make mock message - var message = { + const message = { currentParseObject: parseObject }; // Add mock client - var clientId = 1; + const clientId = 1; addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); - var client = parseLiveQueryServer.clients.get(clientId); + const client = parseLiveQueryServer.clients.get(clientId); // Mock _matchesSubscription to return not matching parseLiveQueryServer._matchesSubscription = function() { return false; @@ -551,24 +551,24 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object delete command which matches some subscriptions', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make deletedParseObject - var parseObject = new Parse.Object(testClassName); + const parseObject = new Parse.Object(testClassName); parseObject._finishFetch({ key: 'value', className: testClassName }); // Make mock message - var message = { + const message = { currentParseObject: parseObject }; // Add mock client - var clientId = 1; + const clientId = 1; addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); - var client = parseLiveQueryServer.clients.get(clientId); + const client = parseLiveQueryServer.clients.get(clientId); // Mock _matchesSubscription to return matching parseLiveQueryServer._matchesSubscription = function() { return true; @@ -587,22 +587,22 @@ describe('ParseLiveQueryServer', function() { }); it('has no subscription and can handle object save command', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(); + const message = generateMockMessage(); // Make sure we do not crash in this case parseLiveQueryServer._onAfterSave(message); }); it('can handle object save command which does not match any subscription', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(); + const message = generateMockMessage(); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); // Mock _matchesSubscription to return not matching parseLiveQueryServer._matchesSubscription = function() { @@ -626,19 +626,19 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object enter command which matches some subscriptions', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(true); + const message = generateMockMessage(true); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); // Mock _matchesSubscription to return matching // In order to mimic a enter, we need original match return false // and the current match return true - var counter = 0; + let counter = 0; parseLiveQueryServer._matchesSubscription = function(parseObject){ if (!parseObject) { return false; @@ -663,14 +663,14 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object update command which matches some subscriptions', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(true); + const message = generateMockMessage(true); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); // Mock _matchesSubscription to return matching parseLiveQueryServer._matchesSubscription = function(parseObject){ @@ -696,19 +696,19 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object leave command which matches some subscriptions', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(true); + const message = generateMockMessage(true); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); // Mock _matchesSubscription to return matching // In order to mimic a leave, we need original match return true // and the current match return false - var counter = 0; + let counter = 0; parseLiveQueryServer._matchesSubscription = function(parseObject){ if (!parseObject) { return false; @@ -733,14 +733,14 @@ describe('ParseLiveQueryServer', function() { }); it('can handle object create command which matches some subscriptions', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request message - var message = generateMockMessage(); + const message = generateMockMessage(); // Add mock client - var clientId = 1; - var client = addMockClient(parseLiveQueryServer, clientId); + const clientId = 1; + const client = addMockClient(parseLiveQueryServer, clientId); // Add mock subscription - var requestId = 2; + const requestId = 2; addMockSubscription(parseLiveQueryServer, clientId, requestId); // Mock _matchesSubscription to return matching parseLiveQueryServer._matchesSubscription = function(parseObject){ @@ -766,9 +766,9 @@ describe('ParseLiveQueryServer', function() { }); it('can match subscription for null or undefined parse object', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock subscription - var subscription = { + const subscription = { match: jasmine.createSpy('match') } @@ -779,36 +779,36 @@ describe('ParseLiveQueryServer', function() { }); it('can match subscription', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock subscription - var subscription = { + const subscription = { query: {} } - var parseObject = {}; + const parseObject = {}; expect(parseLiveQueryServer._matchesSubscription(parseObject, subscription)).toBe(true); // Make sure matchesQuery is called - var matchesQuery = require('../src/LiveQuery/QueryTools').matchesQuery; + const matchesQuery = require('../src/LiveQuery/QueryTools').matchesQuery; expect(matchesQuery).toHaveBeenCalledWith(parseObject, subscription.query); }); it('can inflate parse object', function() { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); // Make mock request - var objectJSON = { + const objectJSON = { "className":"testClassName", "createdAt":"2015-12-22T01:51:12.955Z", "key":"value", "objectId":"BfwxBCz6yW", "updatedAt":"2016-01-05T00:46:45.659Z" }; - var originalObjectJSON = { + const originalObjectJSON = { "className":"testClassName", "createdAt":"2015-12-22T01:51:12.955Z", "key":"originalValue", "objectId":"BfwxBCz6yW", "updatedAt":"2016-01-05T00:46:45.659Z" }; - var message = { + const message = { currentParseObject: objectJSON, originalParseObject: originalObjectJSON }; @@ -816,7 +816,7 @@ describe('ParseLiveQueryServer', function() { parseLiveQueryServer._inflateParseObject(message); // Verify object - var object = message.currentParseObject; + const object = message.currentParseObject; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.get('key')).toEqual('value'); expect(object.className).toEqual('testClassName'); @@ -824,7 +824,7 @@ describe('ParseLiveQueryServer', function() { expect(object.createdAt).not.toBeUndefined(); expect(object.updatedAt).not.toBeUndefined(); // Verify original object - var originalObject = message.originalParseObject; + const originalObject = message.originalParseObject; expect(originalObject instanceof Parse.Object).toBeTruthy(); expect(originalObject.get('key')).toEqual('originalValue'); expect(originalObject.className).toEqual('testClassName'); @@ -834,9 +834,9 @@ describe('ParseLiveQueryServer', function() { }); it('can match undefined ACL', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var client = {}; - var requestId = 0; + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const client = {}; + const requestId = 0; parseLiveQueryServer._matchesACL(undefined, client, requestId).then(function(isMatched) { expect(isMatched).toBe(true); @@ -845,12 +845,12 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with none exist requestId', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); - var client = { + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue(undefined) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -859,15 +859,15 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with public read access', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: 'sessionToken' }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(true); @@ -876,15 +876,15 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with valid subscription sessionToken', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: 'sessionToken' }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(true); @@ -893,17 +893,17 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with valid client sessionToken', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); // Mock sessionTokenCache will return false when sessionToken is undefined - var client = { + const client = { sessionToken: 'sessionToken', getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: undefined }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(true); @@ -912,17 +912,17 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with invalid subscription and client sessionToken', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); // Mock sessionTokenCache will return false when sessionToken is undefined - var client = { + const client = { sessionToken: undefined, getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: undefined }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -931,17 +931,17 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with subscription sessionToken checking error', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); // Mock sessionTokenCache will return error when sessionToken is null, this is just // the behaviour of our mock sessionTokenCache, not real sessionTokenCache - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: null }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -950,17 +950,17 @@ describe('ParseLiveQueryServer', function() { }); it('can match ACL with client sessionToken checking error', function(done) { - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); // Mock sessionTokenCache will return error when sessionToken is null - var client = { + const client = { sessionToken: null, getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: null }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -970,15 +970,15 @@ describe('ParseLiveQueryServer', function() { it('won\'t match ACL that doesn\'t have public read or any roles', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: 'sessionToken' }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -989,15 +989,15 @@ describe('ParseLiveQueryServer', function() { it('won\'t match non-public ACL with role when there is no user', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); acl.setRoleReadAccess("livequery", true); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ }) }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -1008,16 +1008,16 @@ describe('ParseLiveQueryServer', function() { it('won\'t match ACL with role based read access set to false', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); acl.setRoleReadAccess("liveQueryRead", false); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: 'sessionToken' }) }; - var requestId = 0; + const requestId = 0; spyOn(Parse, "Query").and.callFake(function(){ return { @@ -1026,7 +1026,7 @@ describe('ParseLiveQueryServer', function() { }, find() { //Return a role with the name "liveQueryRead" as that is what was set on the ACL - var liveQueryRole = new Parse.Role(); + const liveQueryRole = new Parse.Role(); liveQueryRole.set('name', 'liveQueryRead'); return [ liveQueryRole @@ -1044,16 +1044,16 @@ describe('ParseLiveQueryServer', function() { it('will match ACL with role based read access set to true', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); acl.setRoleReadAccess("liveQueryRead", true); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ sessionToken: 'sessionToken' }) }; - var requestId = 0; + const requestId = 0; spyOn(Parse, "Query").and.callFake(function(){ return { @@ -1062,7 +1062,7 @@ describe('ParseLiveQueryServer', function() { }, find() { //Return a role with the name "liveQueryRead" as that is what was set on the ACL - var liveQueryRole = new Parse.Role(); + const liveQueryRole = new Parse.Role(); liveQueryRole.set('name', 'liveQueryRead'); return [ liveQueryRole @@ -1079,12 +1079,12 @@ describe('ParseLiveQueryServer', function() { }); it('can validate key when valid key is provided', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { clientKey: 'test' } }); - var request = { + const request = { clientKey: 'test' } @@ -1092,12 +1092,12 @@ describe('ParseLiveQueryServer', function() { }); it('can validate key when invalid key is provided', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { clientKey: 'test' } }); - var request = { + const request = { clientKey: 'error' } @@ -1105,32 +1105,32 @@ describe('ParseLiveQueryServer', function() { }); it('can validate key when key is not provided', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { clientKey: 'test' } }); - var request = { + const request = { } expect(parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs)).not.toBeTruthy(); }); it('can validate key when validKerPairs is empty', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, {}); - var request = { + const parseLiveQueryServer = new ParseLiveQueryServer({}, {}); + const request = { } expect(parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs)).toBeTruthy(); }); it('can validate client has master key when valid', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { masterKey: 'test' } }); - var request = { + const request = { masterKey: 'test' }; @@ -1138,12 +1138,12 @@ describe('ParseLiveQueryServer', function() { }); it('can validate client doesn\'t have master key when invalid', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { masterKey: 'test' } }); - var request = { + const request = { masterKey: 'notValid' }; @@ -1151,7 +1151,7 @@ describe('ParseLiveQueryServer', function() { }); it('can validate client doesn\'t have master key when not provided', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, { + const parseLiveQueryServer = new ParseLiveQueryServer({}, { keyPairs: { masterKey: 'test' } @@ -1161,8 +1161,8 @@ describe('ParseLiveQueryServer', function() { }); it('can validate client doesn\'t have master key when validKeyPairs is empty', function() { - var parseLiveQueryServer = new ParseLiveQueryServer({}, {}); - var request = { + const parseLiveQueryServer = new ParseLiveQueryServer({}, {}); + const request = { masterKey: 'test' }; @@ -1171,15 +1171,15 @@ describe('ParseLiveQueryServer', function() { it('will match non-public ACL when client has master key', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ }), hasMasterKey: true }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(true); @@ -1190,15 +1190,15 @@ describe('ParseLiveQueryServer', function() { it('won\'t match non-public ACL when client has no master key', function(done){ - var parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); - var acl = new Parse.ACL(); + const parseLiveQueryServer = new ParseLiveQueryServer(10, 10, {}); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); - var client = { + const client = { getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ }), hasMasterKey: false }; - var requestId = 0; + const requestId = 0; parseLiveQueryServer._matchesACL(acl, client, requestId).then(function(isMatched) { expect(isMatched).toBe(false); @@ -1219,8 +1219,8 @@ describe('ParseLiveQueryServer', function() { // Helper functions to add mock client and subscription to a liveQueryServer function addMockClient(parseLiveQueryServer, clientId) { - var Client = require('../src/LiveQuery/Client').Client; - var client = new Client(clientId, {}); + const Client = require('../src/LiveQuery/Client').Client; + const client = new Client(clientId, {}); parseLiveQueryServer.clients.set(clientId, client); return client; } @@ -1228,7 +1228,7 @@ describe('ParseLiveQueryServer', function() { function addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket, query) { // If parseWebSocket is null, we use the default one if (!parseWebSocket) { - var EventEmitter = require('events'); + const EventEmitter = require('events'); parseWebSocket = new EventEmitter(); } parseWebSocket.clientId = clientId; @@ -1242,7 +1242,7 @@ describe('ParseLiveQueryServer', function() { fields: [ 'test' ] }; } - var request = { + const request = { query: query, requestId: requestId, sessionToken: 'sessionToken' @@ -1250,7 +1250,7 @@ describe('ParseLiveQueryServer', function() { parseLiveQueryServer._handleSubscribe(parseWebSocket, request); // Make mock subscription - var subscription = parseLiveQueryServer.subscriptions.get(query.className).get(queryHashValue); + const subscription = parseLiveQueryServer.subscriptions.get(query.className).get(queryHashValue); subscription.hasSubscribingClient = function() { return false; } @@ -1266,16 +1266,16 @@ describe('ParseLiveQueryServer', function() { // Helper functiosn to generate request message function generateMockMessage(hasOriginalParseObject) { - var parseObject = new Parse.Object(testClassName); + const parseObject = new Parse.Object(testClassName); parseObject._finishFetch({ key: 'value', className: testClassName }); - var message = { + const message = { currentParseObject: parseObject }; if (hasOriginalParseObject) { - var originalParseObject = new Parse.Object(testClassName); + const originalParseObject = new Parse.Object(testClassName); originalParseObject._finishFetch({ key: 'originalValue', className: testClassName diff --git a/spec/ParseObject.spec.js b/spec/ParseObject.spec.js index cc449458..aedf2511 100644 --- a/spec/ParseObject.spec.js +++ b/spec/ParseObject.spec.js @@ -23,7 +23,7 @@ describe('Parse.Object testing', () => { it("update", function(done) { create({ "test" : "test" }, function(model) { - var t2 = new TestObject({ objectId: model.id }); + const t2 = new TestObject({ objectId: model.id }); t2.set("test", "changed"); t2.save(null, { success: function(model) { @@ -35,7 +35,7 @@ describe('Parse.Object testing', () => { }); it("save without null", function(done) { - var object = new TestObject(); + const object = new TestObject(); object.set("favoritePony", "Rainbow Dash"); object.save({ success: function(objectAgain) { @@ -50,8 +50,8 @@ describe('Parse.Object testing', () => { }); it("save cycle", done => { - var a = new Parse.Object("TestObject"); - var b = new Parse.Object("TestObject"); + const a = new Parse.Object("TestObject"); + const b = new Parse.Object("TestObject"); a.set("b", b); a.save().then(function() { b.set("a", a); @@ -73,7 +73,7 @@ describe('Parse.Object testing', () => { it("get", function(done) { create({ "test" : "test" }, function(model) { - var t2 = new TestObject({ objectId: model.id }); + const t2 = new TestObject({ objectId: model.id }); t2.fetch({ success: function(model2) { equal(model2.get("test"), "test", "Update should have succeeded"); @@ -86,13 +86,13 @@ describe('Parse.Object testing', () => { }); it("delete", function(done) { - var t = new TestObject(); + const t = new TestObject(); t.set("test", "test"); t.save(null, { success: function() { t.destroy({ success: function() { - var t2 = new TestObject({ objectId: t.id }); + const t2 = new TestObject({ objectId: t.id }); t2.fetch().then(fail, done); } }); @@ -101,11 +101,11 @@ describe('Parse.Object testing', () => { }); it("find", function(done) { - var t = new TestObject(); + const t = new TestObject(); t.set("foo", "bar"); t.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo("foo", "bar"); query.find({ success: function(results) { @@ -118,19 +118,19 @@ describe('Parse.Object testing', () => { }); it("relational fields", function(done) { - var item = new Item(); + const item = new Item(); item.set("property", "x"); - var container = new Container(); + const container = new Container(); container.set("item", item); Parse.Object.saveAll([item, container], { success: function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.find({ success: function(results) { equal(results.length, 1); - var containerAgain = results[0]; - var itemAgain = containerAgain.get("item"); + const containerAgain = results[0]; + const itemAgain = containerAgain.get("item"); itemAgain.fetch({ success: function() { equal(itemAgain.get("property"), "x"); @@ -145,10 +145,10 @@ describe('Parse.Object testing', () => { it("save adds no data keys (other than createdAt and updatedAt)", function(done) { - var object = new TestObject(); + const object = new TestObject(); object.save(null, { success: function() { - var keys = Object.keys(object.attributes).sort(); + const keys = Object.keys(object.attributes).sort(); equal(keys.length, 2); done(); } @@ -156,19 +156,19 @@ describe('Parse.Object testing', () => { }); it("recursive save", function(done) { - var item = new Item(); + const item = new Item(); item.set("property", "x"); - var container = new Container(); + const container = new Container(); container.set("item", item); container.save(null, { success: function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.find({ success: function(results) { equal(results.length, 1); - var containerAgain = results[0]; - var itemAgain = containerAgain.get("item"); + const containerAgain = results[0]; + const itemAgain = containerAgain.get("item"); itemAgain.fetch({ success: function() { equal(itemAgain.get("property"), "x"); @@ -182,10 +182,10 @@ describe('Parse.Object testing', () => { }); it("fetch", function(done) { - var item = new Item({ foo: "bar" }); + const item = new Item({ foo: "bar" }); item.save(null, { success: function() { - var itemAgain = new Item(); + const itemAgain = new Item(); itemAgain.id = item.id; itemAgain.fetch({ success: function() { @@ -206,10 +206,10 @@ describe('Parse.Object testing', () => { }); it("createdAt doesn't change", function(done) { - var object = new TestObject({ foo: "bar" }); + const object = new TestObject({ foo: "bar" }); object.save(null, { success: function() { - var objectAgain = new TestObject(); + const objectAgain = new TestObject(); objectAgain.id = object.id; objectAgain.fetch({ success: function() { @@ -222,7 +222,7 @@ describe('Parse.Object testing', () => { }); it("createdAt and updatedAt exposed", function(done) { - var object = new TestObject({ foo: "bar" }); + const object = new TestObject({ foo: "bar" }); object.save(null, { success: function() { notEqual(object.updatedAt, undefined); @@ -233,11 +233,11 @@ describe('Parse.Object testing', () => { }); it("updatedAt gets updated", function(done) { - var object = new TestObject({ foo: "bar" }); + const object = new TestObject({ foo: "bar" }); object.save(null, { success: function() { ok(object.updatedAt, "initial save should cause updatedAt to exist"); - var firstUpdatedAt = object.updatedAt; + const firstUpdatedAt = object.updatedAt; object.save({ foo: "baz" }, { success: function() { ok(object.updatedAt, "two saves should cause updatedAt to exist"); @@ -250,16 +250,16 @@ describe('Parse.Object testing', () => { }); it("createdAt is reasonable", function(done) { - var startTime = new Date(); - var object = new TestObject({ foo: "bar" }); + const startTime = new Date(); + const object = new TestObject({ foo: "bar" }); object.save(null, { success: function() { - var endTime = new Date(); - var startDiff = Math.abs(startTime.getTime() - + const endTime = new Date(); + const startDiff = Math.abs(startTime.getTime() - object.createdAt.getTime()); ok(startDiff < 5000); - var endDiff = Math.abs(endTime.getTime() - + const endDiff = Math.abs(endTime.getTime() - object.createdAt.getTime()); ok(endDiff < 5000); @@ -269,7 +269,7 @@ describe('Parse.Object testing', () => { }); it_exclude_dbs(['postgres'])("can set null", function(done) { - var obj = new Parse.Object("TestObject"); + const obj = new Parse.Object("TestObject"); obj.set("foo", null); obj.save(null, { success: function(obj) { @@ -289,7 +289,7 @@ describe('Parse.Object testing', () => { }); it("can set boolean", function(done) { - var obj = new Parse.Object("TestObject"); + const obj = new Parse.Object("TestObject"); obj.set("yes", true); obj.set("no", false); obj.save(null, { @@ -306,7 +306,7 @@ describe('Parse.Object testing', () => { }); it('cannot set invalid date', function(done) { - var obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.set('when', new Date(Date.parse(null))); try { obj.save(); @@ -320,7 +320,7 @@ describe('Parse.Object testing', () => { }); it("invalid class name", function(done) { - var item = new Parse.Object("Foo^bar"); + const item = new Parse.Object("Foo^bar"); item.save(null, { success: function() { ok(false, "The name should have been invalid."); @@ -336,23 +336,23 @@ describe('Parse.Object testing', () => { }); it("invalid key name", function(done) { - var item = new Parse.Object("Item"); + const item = new Parse.Object("Item"); ok(!item.set({"foo^bar": "baz"}), 'Item should not be updated with invalid key.'); item.save({ "foo^bar": "baz" }).then(fail, done); }); it("invalid __type", function(done) { - var item = new Parse.Object("Item"); - var types = ['Pointer', 'File', 'Date', 'GeoPoint', 'Bytes', 'Polygon']; - var tests = types.map(type => { - var test = new Parse.Object("Item"); + const item = new Parse.Object("Item"); + const types = ['Pointer', 'File', 'Date', 'GeoPoint', 'Bytes', 'Polygon']; + const tests = types.map(type => { + const test = new Parse.Object("Item"); test.set('foo', { __type: type }); return test; }); - var next = function(index) { + const next = function(index) { if (index < tests.length) { tests[index].save().then(fail, error => { expect(error.code).toEqual(Parse.Error.INCORRECT_TYPE); @@ -370,7 +370,7 @@ describe('Parse.Object testing', () => { }); it("simple field deletion", function(done) { - var simple = new Parse.Object("SimpleObject"); + const simple = new Parse.Object("SimpleObject"); simple.save({ foo: "bar" }, { @@ -385,7 +385,7 @@ describe('Parse.Object testing', () => { ok(!simple.dirty("foo"), "the whole object was just saved."); ok(!simple.dirty(), "the whole object was just saved."); - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simple.id, { success: function(simpleAgain) { ok(!simpleAgain.has("foo"), "foo should have been removed."); @@ -411,7 +411,7 @@ describe('Parse.Object testing', () => { }); it("field deletion before first save", function(done) { - var simple = new Parse.Object("SimpleObject"); + const simple = new Parse.Object("SimpleObject"); simple.set("foo", "bar"); simple.unset("foo"); @@ -424,7 +424,7 @@ describe('Parse.Object testing', () => { ok(!simple.dirty("foo"), "the whole object was just saved."); ok(!simple.dirty(), "the whole object was just saved."); - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simple.id, { success: function(simpleAgain) { ok(!simpleAgain.has("foo"), "foo should have been removed."); @@ -444,8 +444,8 @@ describe('Parse.Object testing', () => { }); it("relation deletion", function(done) { - var simple = new Parse.Object("SimpleObject"); - var child = new Parse.Object("Child"); + const simple = new Parse.Object("SimpleObject"); + const child = new Parse.Object("Child"); simple.save({ child: child }, { @@ -460,7 +460,7 @@ describe('Parse.Object testing', () => { ok(!simple.dirty("child"), "the whole object was just saved."); ok(!simple.dirty(), "the whole object was just saved."); - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simple.id, { success: function(simpleAgain) { ok(!simpleAgain.has("child"), "child should have been removed."); @@ -486,7 +486,7 @@ describe('Parse.Object testing', () => { }); it("deleted keys get cleared", function(done) { - var simpleObject = new Parse.Object("SimpleObject"); + const simpleObject = new Parse.Object("SimpleObject"); simpleObject.set("foo", "bar"); simpleObject.unset("foo"); simpleObject.save(null, { @@ -494,7 +494,7 @@ describe('Parse.Object testing', () => { simpleObject.set("foo", "baz"); simpleObject.save(null, { success: function(simpleObject) { - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simpleObject.id, { success: function(simpleObjectAgain) { equal(simpleObjectAgain.get("foo"), "baz"); @@ -520,7 +520,7 @@ describe('Parse.Object testing', () => { }); it("setting after deleting", function(done) { - var simpleObject = new Parse.Object("SimpleObject"); + const simpleObject = new Parse.Object("SimpleObject"); simpleObject.set("foo", "bar"); simpleObject.save(null, { success: function(simpleObject) { @@ -528,7 +528,7 @@ describe('Parse.Object testing', () => { simpleObject.set("foo", "baz"); simpleObject.save(null, { success: function(simpleObject) { - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simpleObject.id, { success: function(simpleObjectAgain) { equal(simpleObjectAgain.get("foo"), "baz"); @@ -554,7 +554,7 @@ describe('Parse.Object testing', () => { }); it("increment", function(done) { - var simple = new Parse.Object("SimpleObject"); + const simple = new Parse.Object("SimpleObject"); simple.save({ foo: 5 }, { @@ -569,7 +569,7 @@ describe('Parse.Object testing', () => { ok(!simple.dirty("foo"), "the whole object was just saved."); ok(!simple.dirty(), "the whole object was just saved."); - var query = new Parse.Query("SimpleObject"); + const query = new Parse.Query("SimpleObject"); query.get(simple.id, { success: function(simpleAgain) { equal(simpleAgain.get("foo"), 6); @@ -583,23 +583,23 @@ describe('Parse.Object testing', () => { }); it("addUnique", function(done) { - var x1 = new Parse.Object('X'); + const x1 = new Parse.Object('X'); x1.set('stuff', [1, 2]); x1.save().then(() => { - var objectId = x1.id; - var x2 = new Parse.Object('X', {objectId: objectId}); + const objectId = x1.id; + const x2 = new Parse.Object('X', {objectId: objectId}); x2.addUnique('stuff', 2); x2.addUnique('stuff', 4); expect(x2.get('stuff')).toEqual([2, 4]); return x2.save(); }).then(() => { - var query = new Parse.Query('X'); + const query = new Parse.Query('X'); return query.get(x1.id); }).then((x3) => { const stuff = x3.get('stuff'); const expected = [1, 2, 4]; expect(stuff.length).toBe(expected.length); - for (var i of stuff) { + for (const i of stuff) { expect(expected.indexOf(i) >= 0).toBe(true); } done(); @@ -615,17 +615,17 @@ describe('Parse.Object testing', () => { }); it("addUnique with object", function(done) { - var x1 = new Parse.Object('X'); + const x1 = new Parse.Object('X'); x1.set('stuff', [ 1, {'hello': 'world'}, {'foo': 'bar'}]); x1.save().then(() => { - var objectId = x1.id; - var x2 = new Parse.Object('X', {objectId: objectId}); + const objectId = x1.id; + const x2 = new Parse.Object('X', {objectId: objectId}); x2.addUnique('stuff', {'hello': 'world'}); x2.addUnique('stuff', {'bar': 'baz'}); expect(x2.get('stuff')).toEqual([{'hello': 'world'}, {'bar': 'baz'}]); return x2.save(); }).then(() => { - var query = new Parse.Query('X'); + const query = new Parse.Query('X'); return query.get(x1.id); }).then((x3) => { const stuff = x3.get('stuff'); @@ -648,16 +648,16 @@ describe('Parse.Object testing', () => { }); it("removes with object", function(done) { - var x1 = new Parse.Object('X'); + const x1 = new Parse.Object('X'); x1.set('stuff', [ 1, {'hello': 'world'}, {'foo': 'bar'}]); x1.save().then(() => { - var objectId = x1.id; - var x2 = new Parse.Object('X', {objectId: objectId}); + const objectId = x1.id; + const x2 = new Parse.Object('X', {objectId: objectId}); x2.remove('stuff', {'hello': 'world'}); expect(x2.get('stuff')).toEqual([]); return x2.save(); }).then(() => { - var query = new Parse.Query('X'); + const query = new Parse.Query('X'); return query.get(x1.id); }).then((x3) => { expect(x3.get('stuff')).toEqual([1, {'foo': 'bar'}]); @@ -669,7 +669,7 @@ describe('Parse.Object testing', () => { }); it("dirty attributes", function(done) { - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.set("cat", "good"); object.set("dog", "bad"); object.save({ @@ -694,11 +694,11 @@ describe('Parse.Object testing', () => { }); it("dirty keys", function(done) { - var object = new Parse.Object("TestObject"); + const object = new Parse.Object("TestObject"); object.set("gogo", "good"); object.set("sito", "sexy"); ok(object.dirty()); - var dirtyKeys = object.dirtyKeys(); + let dirtyKeys = object.dirtyKeys(); equal(dirtyKeys.length, 2); ok(arrayContains(dirtyKeys, "gogo")); ok(arrayContains(dirtyKeys, "sito")); @@ -735,8 +735,8 @@ describe('Parse.Object testing', () => { it("length attribute", function(done) { Parse.User.signUp("bob", "password", null, { success: function(user) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject({ + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject({ length: 5, ACL: new Parse.ACL(user) // ACLs cause things like validation to run }); @@ -748,13 +748,13 @@ describe('Parse.Object testing', () => { equal(obj.get("length"), 5); ok(obj.get("ACL") instanceof Parse.ACL); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(obj) { equal(obj.get("length"), 5); ok(obj.get("ACL") instanceof Parse.ACL); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { obj = results[0]; @@ -789,8 +789,8 @@ describe('Parse.Object testing', () => { }); it("old attribute unset then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 3); obj.save({ success: function() { @@ -800,7 +800,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -815,8 +815,8 @@ describe('Parse.Object testing', () => { }); it("new attribute unset then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 5); obj.unset("x"); obj.unset("x"); @@ -824,7 +824,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -837,15 +837,15 @@ describe('Parse.Object testing', () => { }); it("unknown attribute unset then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.unset("x"); obj.unset("x"); obj.save({ success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -858,8 +858,8 @@ describe('Parse.Object testing', () => { }); it("old attribute unset then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 3); obj.save({ success: function() { @@ -869,7 +869,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -884,8 +884,8 @@ describe('Parse.Object testing', () => { }); it("new attribute unset then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 5); obj.unset("x"); obj.clear(); @@ -893,7 +893,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -906,15 +906,15 @@ describe('Parse.Object testing', () => { }); it("unknown attribute unset then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.unset("x"); obj.clear(); obj.save({ success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -927,8 +927,8 @@ describe('Parse.Object testing', () => { }); it("old attribute clear then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 3); obj.save({ success: function() { @@ -938,7 +938,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -953,8 +953,8 @@ describe('Parse.Object testing', () => { }); it("new attribute clear then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 5); obj.clear(); obj.unset("x"); @@ -962,7 +962,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -975,15 +975,15 @@ describe('Parse.Object testing', () => { }); it("unknown attribute clear then unset", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.clear(); obj.unset("x"); obj.save({ success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -996,8 +996,8 @@ describe('Parse.Object testing', () => { }); it("old attribute clear then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 3); obj.save({ success: function() { @@ -1007,7 +1007,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -1022,8 +1022,8 @@ describe('Parse.Object testing', () => { }); it("new attribute clear then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("x", 5); obj.clear(); obj.clear(); @@ -1031,7 +1031,7 @@ describe('Parse.Object testing', () => { success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -1044,15 +1044,15 @@ describe('Parse.Object testing', () => { }); it("unknown attribute clear then clear", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.clear(); obj.clear(); obj.save({ success: function() { equal(obj.has("x"), false); equal(obj.get("x"), undefined); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(obj.id, { success: function(objAgain) { equal(objAgain.has("x"), false); @@ -1065,12 +1065,12 @@ describe('Parse.Object testing', () => { }); it("saving children in an array", function(done) { - var Parent = Parse.Object.extend("Parent"); - var Child = Parse.Object.extend("Child"); + const Parent = Parse.Object.extend("Parent"); + const Child = Parse.Object.extend("Child"); - var child1 = new Child(); - var child2 = new Child(); - var parent = new Parent(); + const child1 = new Child(); + const child2 = new Child(); + const parent = new Parent(); child1.set('name', 'jamie'); child2.set('name', 'cersei'); @@ -1078,7 +1078,7 @@ describe('Parse.Object testing', () => { parent.save(null, { success: function() { - var query = new Parse.Query(Child); + const query = new Parse.Query(Child); query.ascending('name'); query.find({ success: function(results) { @@ -1098,16 +1098,16 @@ describe('Parse.Object testing', () => { it("two saves at the same time", function(done) { - var object = new Parse.Object("TestObject"); - var firstSave = true; + const object = new Parse.Object("TestObject"); + let firstSave = true; - var success = function() { + const success = function() { if (firstSave) { firstSave = false; return; } - var query = new Parse.Query("TestObject"); + const query = new Parse.Query("TestObject"); query.find({ success: function(results) { equal(results.length, 1); @@ -1118,7 +1118,7 @@ describe('Parse.Object testing', () => { }); }; - var options = { success: success, error: fail }; + const options = { success: success, error: fail }; object.save({ cat: "meow" }, options); object.save({ dog: "bark" }, options); @@ -1131,9 +1131,9 @@ describe('Parse.Object testing', () => { // If this fails, it's probably a schema issue. it('many saves after a failure', function(done) { // Make a class with a number in the schema. - var o1 = new Parse.Object('TestObject'); + const o1 = new Parse.Object('TestObject'); o1.set('number', 1); - var object = null; + let object = null; o1.save().then(() => { object = new Parse.Object('TestObject'); object.set('number', 'two'); @@ -1156,7 +1156,7 @@ describe('Parse.Object testing', () => { }); it("is not dirty after save", function(done) { - var obj = new Parse.Object("TestObject"); + const obj = new Parse.Object("TestObject"); obj.save(expectSuccess({ success: function() { obj.set({ "content": "x" }); @@ -1171,8 +1171,8 @@ describe('Parse.Object testing', () => { }); it("add with an object", function(done) { - var child = new Parse.Object("Person"); - var parent = new Parse.Object("Person"); + const child = new Parse.Object("Person"); + const parent = new Parse.Object("Person"); Parse.Promise.as().then(function() { return child.save(); @@ -1182,7 +1182,7 @@ describe('Parse.Object testing', () => { return parent.save(); }).then(function() { - var query = new Parse.Query("Person"); + const query = new Parse.Query("Person"); return query.get(parent.id); }).then(function(parentAgain) { @@ -1198,7 +1198,7 @@ describe('Parse.Object testing', () => { it("toJSON saved object", function(done) { create({ "foo" : "bar" }, function(model) { - var objJSON = model.toJSON(); + const objJSON = model.toJSON(); ok(objJSON.foo, "expected json to contain key 'foo'"); ok(objJSON.objectId, "expected json to contain key 'objectId'"); ok(objJSON.createdAt, "expected json to contain key 'createdAt'"); @@ -1208,15 +1208,15 @@ describe('Parse.Object testing', () => { }); it("remove object from array", function(done) { - var obj = new TestObject(); + const obj = new TestObject(); obj.save(null, expectSuccess({ success: function() { - var container = new TestObject(); + const container = new TestObject(); container.add("array", obj); equal(container.get("array").length, 1); container.save(null, expectSuccess({ success: function() { - var objAgain = new TestObject(); + const objAgain = new TestObject(); objAgain.id = obj.id; container.remove("array", objAgain); equal(container.get("array").length, 0); @@ -1228,12 +1228,12 @@ describe('Parse.Object testing', () => { }); it("async methods", function(done) { - var obj = new TestObject(); + const obj = new TestObject(); obj.set("time", "adventure"); obj.save().then(function(obj) { ok(obj.id, "objectId should not be null."); - var objAgain = new TestObject(); + const objAgain = new TestObject(); objAgain.id = obj.id; return objAgain.fetch(); @@ -1242,7 +1242,7 @@ describe('Parse.Object testing', () => { return objAgain.destroy(); }).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.find(); }).then(function(results) { @@ -1255,7 +1255,7 @@ describe('Parse.Object testing', () => { }); it("fail validation with promise", function(done) { - var PickyEater = Parse.Object.extend("PickyEater", { + const PickyEater = Parse.Object.extend("PickyEater", { validate: function(attrs) { if (attrs.meal === "tomatoes") { return "Ew. Tomatoes are gross."; @@ -1264,7 +1264,7 @@ describe('Parse.Object testing', () => { } }); - var bryan = new PickyEater(); + const bryan = new PickyEater(); bryan.save({ meal: "burrito" }).then(function() { @@ -1282,8 +1282,8 @@ describe('Parse.Object testing', () => { }); it("beforeSave doesn't make object dirty with new field", function(done) { - var restController = Parse.CoreManager.getRESTController(); - var r = restController.request; + const restController = Parse.CoreManager.getRESTController(); + const r = restController.request; restController.request = function() { return r.apply(this, arguments).then(function(result) { result.aDate = {"__type":"Date", "iso":"2014-06-24T06:06:06.452Z"}; @@ -1291,7 +1291,7 @@ describe('Parse.Object testing', () => { }); }; - var obj = new Parse.Object("Thing"); + const obj = new Parse.Object("Thing"); obj.save().then(function() { ok(!obj.dirty(), "The object should not be dirty"); ok(obj.get('aDate')); @@ -1303,8 +1303,8 @@ describe('Parse.Object testing', () => { }); it("beforeSave doesn't make object dirty with existing field", function(done) { - var restController = Parse.CoreManager.getRESTController(); - var r = restController.request; + const restController = Parse.CoreManager.getRESTController(); + const r = restController.request; restController.request = function() { return r.apply(this, arguments).then(function(result) { result.aDate = {"__type":"Date", "iso":"2014-06-24T06:06:06.452Z"}; @@ -1312,10 +1312,10 @@ describe('Parse.Object testing', () => { }); }; - var now = new Date(); + const now = new Date(); - var obj = new Parse.Object("Thing"); - var promise = obj.save(); + const obj = new Parse.Object("Thing"); + const promise = obj.save(); obj.set('aDate', now); promise.then(function() { @@ -1330,12 +1330,12 @@ describe('Parse.Object testing', () => { it("bytes work", function(done) { Parse.Promise.as().then(function() { - var obj = new TestObject(); + const obj = new TestObject(); obj.set("bytes", { __type: "Bytes", base64: "ZnJveW8=" }); return obj.save(); }).then(function(obj) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.get(obj.id); }).then(function(obj) { @@ -1359,7 +1359,7 @@ describe('Parse.Object testing', () => { it("destroyAll new objects only", function(done) { - var objects = [new TestObject(), new TestObject()]; + const objects = [new TestObject(), new TestObject()]; Parse.Object.destroyAll(objects, function(success, error) { ok(success && !error, "Should be able to destroy only new objects"); done(); @@ -1367,11 +1367,11 @@ describe('Parse.Object testing', () => { }); it("fetchAll", function(done) { - var numItems = 11; - var container = new Container(); - var items = []; - for (var i = 0; i < numItems; i++) { - var item = new Item(); + const numItems = 11; + const container = new Container(); + const items = []; + for (let i = 0; i < numItems; i++) { + const item = new Item(); item.set("x", i); items.push(item); } @@ -1379,10 +1379,10 @@ describe('Parse.Object testing', () => { container.set("items", items); return container.save(); }).then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var itemsAgain = containerAgain.get("items"); + const itemsAgain = containerAgain.get("items"); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); @@ -1390,7 +1390,7 @@ describe('Parse.Object testing', () => { } equal(itemsAgain.length, numItems, "Should get the array back"); itemsAgain.forEach(function(item, i) { - var newValue = i * 2; + const newValue = i * 2; item.set("x", newValue); }); return Parse.Object.saveAll(itemsAgain); @@ -1414,11 +1414,11 @@ describe('Parse.Object testing', () => { }); it("fetchAll updates dates", function(done) { - var updatedObject; - var object = new TestObject(); + let updatedObject; + const object = new TestObject(); object.set("x", 7); object.save().then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.find(object.id); }).then(function(results) { updatedObject = results[0]; @@ -1434,11 +1434,11 @@ describe('Parse.Object testing', () => { }); it("fetchAll backbone-style callbacks", function(done) { - var numItems = 11; - var container = new Container(); - var items = []; - for (var i = 0; i < numItems; i++) { - var item = new Item(); + const numItems = 11; + const container = new Container(); + const items = []; + for (let i = 0; i < numItems; i++) { + const item = new Item(); item.set("x", i); items.push(item); } @@ -1446,10 +1446,10 @@ describe('Parse.Object testing', () => { container.set("items", items); return container.save(); }).then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var itemsAgain = containerAgain.get("items"); + const itemsAgain = containerAgain.get("items"); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); @@ -1457,7 +1457,7 @@ describe('Parse.Object testing', () => { } equal(itemsAgain.length, numItems, "Should get the array back"); itemsAgain.forEach(function(item, i) { - var newValue = i * 2; + const newValue = i * 2; item.set("x", newValue); }); return Parse.Object.saveAll(itemsAgain); @@ -1480,16 +1480,16 @@ describe('Parse.Object testing', () => { }); it("fetchAll error on multiple classes", function(done) { - var container = new Container(); + const container = new Container(); container.set("item", new Item()); container.set("subcontainer", new Container()); return container.save().then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var subContainerAgain = containerAgain.get("subcontainer"); - var itemAgain = containerAgain.get("item"); - var multiClassArray = [subContainerAgain, itemAgain]; + const subContainerAgain = containerAgain.get("subcontainer"); + const itemAgain = containerAgain.get("item"); + const multiClassArray = [subContainerAgain, itemAgain]; return Parse.Object.fetchAll( multiClassArray, expectError(Parse.Error.INVALID_CLASS_NAME, done)); @@ -1497,27 +1497,27 @@ describe('Parse.Object testing', () => { }); it("fetchAll error on unsaved object", function(done) { - var unsavedObjectArray = [new TestObject()]; + const unsavedObjectArray = [new TestObject()]; Parse.Object.fetchAll(unsavedObjectArray, expectError(Parse.Error.MISSING_OBJECT_ID, done)); }); it("fetchAll error on deleted object", function(done) { - var numItems = 11; - var items = []; - for (var i = 0; i < numItems; i++) { - var item = new Item(); + const numItems = 11; + const items = []; + for (let i = 0; i < numItems; i++) { + const item = new Item(); item.set("x", i); items.push(item); } Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(Item); + const query = new Parse.Query(Item); return query.get(items[0].id); }).then(function(objectToDelete) { return objectToDelete.destroy(); }).then(function(deletedObject) { - var nonExistentObject = new Item({ objectId: deletedObject.id }); - var nonExistentObjectArray = [nonExistentObject, items[1]]; + const nonExistentObject = new Item({ objectId: deletedObject.id }); + const nonExistentObjectArray = [nonExistentObject, items[1]]; return Parse.Object.fetchAll( nonExistentObjectArray, expectError(Parse.Error.OBJECT_NOT_FOUND, done)); @@ -1527,14 +1527,14 @@ describe('Parse.Object testing', () => { // TODO: Verify that with Sessions, this test is wrong... A fetch on // user should not bring down a session token. xit("fetchAll User attributes get merged", function(done) { - var sameUser; - var user = new Parse.User(); + let sameUser; + let user = new Parse.User(); user.set("username", "asdf"); user.set("password", "zxcv"); user.set("foo", "bar"); user.signUp().then(function() { Parse.User.logOut(); - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); return query.get(user.id); }).then(function(userAgain) { user = userAgain; @@ -1559,11 +1559,11 @@ describe('Parse.Object testing', () => { }); it("fetchAllIfNeeded", function(done) { - var numItems = 11; - var container = new Container(); - var items = []; - for (var i = 0; i < numItems; i++) { - var item = new Item(); + const numItems = 11; + const container = new Container(); + const items = []; + for (let i = 0; i < numItems; i++) { + const item = new Item(); item.set("x", i); items.push(item); } @@ -1571,10 +1571,10 @@ describe('Parse.Object testing', () => { container.set("items", items); return container.save(); }).then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var itemsAgain = containerAgain.get("items"); + const itemsAgain = containerAgain.get("items"); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); @@ -1597,11 +1597,11 @@ describe('Parse.Object testing', () => { }); it("fetchAllIfNeeded backbone-style callbacks", function(done) { - var numItems = 11; - var container = new Container(); - var items = []; - for (var i = 0; i < numItems; i++) { - var item = new Item(); + const numItems = 11; + const container = new Container(); + const items = []; + for (let i = 0; i < numItems; i++) { + const item = new Item(); item.set("x", i); items.push(item); } @@ -1609,10 +1609,10 @@ describe('Parse.Object testing', () => { container.set("items", items); return container.save(); }).then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var itemsAgain = containerAgain.get("items"); + const itemsAgain = containerAgain.get("items"); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); @@ -1623,7 +1623,7 @@ describe('Parse.Object testing', () => { }); return Parse.Object.saveAll(itemsAgain); }).then(function() { - var items = container.get("items"); + const items = container.get("items"); return Parse.Object.fetchAllIfNeeded(items, { success: function(fetchedItems) { equal(fetchedItems.length, numItems, @@ -1650,23 +1650,23 @@ describe('Parse.Object testing', () => { }); it("fetchAllIfNeeded unsaved object", function(done) { - var unsavedObjectArray = [new TestObject()]; + const unsavedObjectArray = [new TestObject()]; Parse.Object.fetchAllIfNeeded( unsavedObjectArray, expectError(Parse.Error.MISSING_OBJECT_ID, done)); }); it("fetchAllIfNeeded error on multiple classes", function(done) { - var container = new Container(); + const container = new Container(); container.set("item", new Item()); container.set("subcontainer", new Container()); return container.save().then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); return query.get(container.id); }).then(function(containerAgain) { - var subContainerAgain = containerAgain.get("subcontainer"); - var itemAgain = containerAgain.get("item"); - var multiClassArray = [subContainerAgain, itemAgain]; + const subContainerAgain = containerAgain.get("subcontainer"); + const itemAgain = containerAgain.get("item"); + const multiClassArray = [subContainerAgain, itemAgain]; return Parse.Object.fetchAllIfNeeded( multiClassArray, expectError(Parse.Error.INVALID_CLASS_NAME, done)); @@ -1675,7 +1675,7 @@ describe('Parse.Object testing', () => { it("Objects with className User", function(done) { equal(Parse.CoreManager.get('PERFORM_USER_REWRITE'), true); - var User1 = Parse.Object.extend({ + const User1 = Parse.Object.extend({ className: "User" }); @@ -1684,7 +1684,7 @@ describe('Parse.Object testing', () => { Parse.User.allowCustomUserClass(true); equal(Parse.CoreManager.get('PERFORM_USER_REWRITE'), false); - var User2 = Parse.Object.extend({ + const User2 = Parse.Object.extend({ className: "User" }); @@ -1695,14 +1695,14 @@ describe('Parse.Object testing', () => { Parse.User.allowCustomUserClass(false); equal(Parse.CoreManager.get('PERFORM_USER_REWRITE'), true, "PERFORM_USER_REWRITE is reset"); - var user = new User2(); + const user = new User2(); user.set("name", "Me"); user.save({height: 181}, expectSuccess({ success: function(user) { equal(user.get("name"), "Me"); equal(user.get("height"), 181); - var query = new Parse.Query(User2); + const query = new Parse.Query(User2); query.get(user.id, expectSuccess({ success: function(user) { equal(user.className, "User"); @@ -1717,14 +1717,14 @@ describe('Parse.Object testing', () => { }); it("create without data", function(done) { - var t1 = new TestObject({ "test" : "test" }); + const t1 = new TestObject({ "test" : "test" }); t1.save().then(function(t1) { - var t2 = TestObject.createWithoutData(t1.id); + const t2 = TestObject.createWithoutData(t1.id); return t2.fetch(); }).then(function(t2) { equal(t2.get("test"), "test", "Fetch should have grabbed " + "'test' property."); - var t3 = TestObject.createWithoutData(t2.id); + const t3 = TestObject.createWithoutData(t2.id); t3.set("test", "not test"); return t3.fetch(); }).then(function(t3) { @@ -1738,13 +1738,13 @@ describe('Parse.Object testing', () => { }); it("remove from new field creates array key", (done) => { - var obj = new TestObject(); + const obj = new TestObject(); obj.remove('shouldBeArray', 'foo'); obj.save().then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); return query.get(obj.id); }).then((objAgain) => { - var arr = objAgain.get('shouldBeArray'); + const arr = objAgain.get('shouldBeArray'); ok(Array.isArray(arr), 'Should have created array key'); ok(!arr || arr.length === 0, 'Should have an empty array.'); done(); @@ -1752,10 +1752,10 @@ describe('Parse.Object testing', () => { }); it("increment with type conflict fails", (done) => { - var obj = new TestObject(); + const obj = new TestObject(); obj.set('astring', 'foo'); obj.save().then(() => { - var obj2 = new TestObject(); + const obj2 = new TestObject(); obj2.increment('astring'); return obj2.save(); }).then(() => { @@ -1768,10 +1768,10 @@ describe('Parse.Object testing', () => { }); it("increment with empty field solidifies type", (done) => { - var obj = new TestObject(); + const obj = new TestObject(); obj.increment('aninc'); obj.save().then(() => { - var obj2 = new TestObject(); + const obj2 = new TestObject(); obj2.set('aninc', 'foo'); return obj2.save(); }).then(() => { @@ -1784,10 +1784,10 @@ describe('Parse.Object testing', () => { }); it("increment update with type conflict fails", (done) => { - var obj = new TestObject(); + const obj = new TestObject(); obj.set('someString', 'foo'); obj.save().then((objAgain) => { - var obj2 = new TestObject(); + const obj2 = new TestObject(); obj2.id = objAgain.id; obj2.increment('someString'); return obj2.save(); @@ -1801,11 +1801,11 @@ describe('Parse.Object testing', () => { }); it('dictionary fetched pointers do not lose data on fetch', (done) => { - var parent = new Parse.Object('Parent'); - var dict = {}; - for (var i = 0; i < 5; i++) { - var proc = (iter) => { - var child = new Parse.Object('Child'); + const parent = new Parse.Object('Parent'); + const dict = {}; + for (let i = 0; i < 5; i++) { + const proc = (iter) => { + const child = new Parse.Object('Child'); child.set('name', 'testname' + i); dict[iter] = child; }; @@ -1815,7 +1815,7 @@ describe('Parse.Object testing', () => { parent.save().then(() => { return parent.fetch(); }).then((parentAgain) => { - var dictAgain = parentAgain.get('childDict'); + const dictAgain = parentAgain.get('childDict'); if (!dictAgain) { fail('Should have been a dictionary.'); return done(); diff --git a/spec/ParsePolygon.spec.js b/spec/ParsePolygon.spec.js index ca38ad44..19091ce7 100644 --- a/spec/ParsePolygon.spec.js +++ b/spec/ParsePolygon.spec.js @@ -180,7 +180,7 @@ describe('Parse.Polygon testing', () => { 'X-Parse-Javascript-Key': Parse.javaScriptKey } }); - }).then(done.fail, done); + }).then(done.fail, () => done()); }); it('polygonContain invalid geoPoint', (done) => { @@ -203,7 +203,7 @@ describe('Parse.Polygon testing', () => { 'X-Parse-Javascript-Key': Parse.javaScriptKey } }); - }).then(done.fail, done); + }).then(done.fail, () => done()); }); }); diff --git a/spec/ParsePubSub.spec.js b/spec/ParsePubSub.spec.js index 17d523b1..3c7014f7 100644 --- a/spec/ParsePubSub.spec.js +++ b/spec/ParsePubSub.spec.js @@ -1,16 +1,16 @@ -var ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; +const ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; describe('ParsePubSub', function() { beforeEach(function(done) { // Mock RedisPubSub - var mockRedisPubSub = { + const mockRedisPubSub = { createPublisher: jasmine.createSpy('createPublisherRedis'), createSubscriber: jasmine.createSpy('createSubscriberRedis') }; jasmine.mockLibrary('../src/Adapters/PubSub/RedisPubSub', 'RedisPubSub', mockRedisPubSub); // Mock EventEmitterPubSub - var mockEventEmitterPubSub = { + const mockEventEmitterPubSub = { createPublisher: jasmine.createSpy('createPublisherEventEmitter'), createSubscriber: jasmine.createSpy('createSubscriberEventEmitter') }; @@ -23,8 +23,8 @@ describe('ParsePubSub', function() { redisURL: 'redisURL' }); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createPublisher).toHaveBeenCalledWith({redisURL: 'redisURL'}); expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled(); }); @@ -32,8 +32,8 @@ describe('ParsePubSub', function() { it('can create event emitter publisher', function() { ParsePubSub.createPublisher({}); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createPublisher).toHaveBeenCalled(); }); @@ -43,8 +43,8 @@ describe('ParsePubSub', function() { redisURL: 'redisURL' }); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createSubscriber).toHaveBeenCalledWith({redisURL: 'redisURL'}); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); }); @@ -52,8 +52,8 @@ describe('ParsePubSub', function() { it('can create event emitter subscriber', function() { ParsePubSub.createSubscriber({}); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).toHaveBeenCalled(); }); @@ -73,8 +73,8 @@ describe('ParsePubSub', function() { }); expect(adapter.createSubscriber).toHaveBeenCalled(); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); @@ -100,8 +100,8 @@ describe('ParsePubSub', function() { }); expect(adapter.createSubscriber).toHaveBeenCalled(); - var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; - var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; + const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; + const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); diff --git a/spec/ParseQuery.spec.js b/spec/ParseQuery.spec.js index 000fbe62..662b58fa 100644 --- a/spec/ParseQuery.spec.js +++ b/spec/ParseQuery.spec.js @@ -8,10 +8,10 @@ const Parse = require('parse/node'); describe('Parse.Query testing', () => { it("basic query", function(done) { - var baz = new TestObject({ foo: 'baz' }); - var qux = new TestObject({ foo: 'qux' }); + const baz = new TestObject({ foo: 'baz' }); + const qux = new TestObject({ foo: 'qux' }); Parse.Object.saveAll([baz, qux], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo('foo', 'baz'); query.find({ success: function(results) { @@ -24,11 +24,11 @@ describe('Parse.Query testing', () => { }); it("searching for null", function(done) { - var baz = new TestObject({ foo: null }); - var qux = new TestObject({ foo: 'qux' }); - var qux2 = new TestObject({ }); + const baz = new TestObject({ foo: null }); + const qux = new TestObject({ foo: 'qux' }); + const qux2 = new TestObject({ }); Parse.Object.saveAll([baz, qux, qux2], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo('foo', null); query.find({ success: function(results) { @@ -50,11 +50,11 @@ describe('Parse.Query testing', () => { }); it("searching for not null", function(done) { - var baz = new TestObject({ foo: null }); - var qux = new TestObject({ foo: 'qux' }); - var qux2 = new TestObject({ }); + const baz = new TestObject({ foo: null }); + const qux = new TestObject({ foo: 'qux' }); + const qux2 = new TestObject({ }); Parse.Object.saveAll([baz, qux, qux2], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.notEqualTo('foo', null); query.find({ success: function(results) { @@ -78,22 +78,22 @@ describe('Parse.Query testing', () => { }); it("notEqualTo with Relation is working", function(done) { - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); - var user1 = new Parse.User(); + const user1 = new Parse.User(); user1.setPassword("asdf"); user1.setUsername("qwerty"); - var user2 = new Parse.User(); + const user2 = new Parse.User(); user2.setPassword("asdf"); user2.setUsername("asdf"); - var Cake = Parse.Object.extend("Cake"); - var cake1 = new Cake(); - var cake2 = new Cake(); - var cake3 = new Cake(); + const Cake = Parse.Object.extend("Cake"); + const cake1 = new Cake(); + const cake2 = new Cake(); + const cake3 = new Cake(); user.signUp().then(function(){ @@ -101,40 +101,40 @@ describe('Parse.Query testing', () => { }).then(function(){ return user2.signUp(); }).then(function(){ - var relLike1 = cake1.relation("liker"); + const relLike1 = cake1.relation("liker"); relLike1.add([user, user1]); - var relDislike1 = cake1.relation("hater"); + const relDislike1 = cake1.relation("hater"); relDislike1.add(user2); return cake1.save(); }).then(function(){ - var rellike2 = cake2.relation("liker"); + const rellike2 = cake2.relation("liker"); rellike2.add([user, user1]); - var relDislike2 = cake2.relation("hater"); + const relDislike2 = cake2.relation("hater"); relDislike2.add(user2); - var relSomething = cake2.relation("something"); + const relSomething = cake2.relation("something"); relSomething.add(user); return cake2.save(); }).then(function(){ - var rellike3 = cake3.relation("liker"); + const rellike3 = cake3.relation("liker"); rellike3.add(user); - var relDislike3 = cake3.relation("hater"); + const relDislike3 = cake3.relation("hater"); relDislike3.add([user1, user2]); return cake3.save(); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // User2 likes nothing so we should receive 0 query.equalTo("liker", user2); return query.find().then(function(results){ equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // User1 likes two of three cakes query.equalTo("liker", user1); return query.find().then(function(results){ @@ -142,7 +142,7 @@ describe('Parse.Query testing', () => { equal(results.length, 2); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // We want to know which cake the user1 is not appreciating -> cake3 query.notEqualTo("liker", user1); return query.find().then(function(results){ @@ -150,21 +150,21 @@ describe('Parse.Query testing', () => { equal(results.length, 1); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // User2 is a hater of everything so we should receive 0 query.notEqualTo("hater", user2); return query.find().then(function(results){ equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // Only cake3 is liked by user query.notContainedIn("liker", [user1]); return query.find().then(function(results){ equal(results.length, 1); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // All the users query.containedIn("liker", [user, user1, user2]); // Exclude user 1 @@ -176,7 +176,7 @@ describe('Parse.Query testing', () => { expect(cake.id).toBe(cake3.id); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); // Exclude user1 query.notEqualTo("liker", user1); // Only cake1 @@ -186,7 +186,7 @@ describe('Parse.Query testing', () => { equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); query.notEqualTo("hater", user2); query.notEqualTo("liker", user2); // user2 doesn't like any cake so this should be 0 @@ -194,7 +194,7 @@ describe('Parse.Query testing', () => { equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); query.equalTo("hater", user); query.equalTo("liker", user); // user doesn't hate any cake so this should be 0 @@ -202,7 +202,7 @@ describe('Parse.Query testing', () => { equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); query.equalTo("hater", null); query.equalTo("liker", null); // user doesn't hate any cake so this should be 0 @@ -210,7 +210,7 @@ describe('Parse.Query testing', () => { equal(results.length, 0); }); }).then(function(){ - var query = new Parse.Query(Cake); + const query = new Parse.Query(Cake); query.equalTo("something", null); // user doesn't hate any cake so this should be 0 return query.find().then(function(results){ @@ -225,10 +225,10 @@ describe('Parse.Query testing', () => { }); it("query with limit", function(done) { - var baz = new TestObject({ foo: 'baz' }); - var qux = new TestObject({ foo: 'qux' }); + const baz = new TestObject({ foo: 'baz' }); + const qux = new TestObject({ foo: 'qux' }); Parse.Object.saveAll([baz, qux], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.limit(1); query.find({ success: function(results) { @@ -240,11 +240,11 @@ describe('Parse.Query testing', () => { }); it("query with limit equal to maxlimit", function(done) { - var baz = new TestObject({ foo: 'baz' }); - var qux = new TestObject({ foo: 'qux' }); + const baz = new TestObject({ foo: 'baz' }); + const qux = new TestObject({ foo: 'qux' }); reconfigureServer({ maxLimit: 1 }) Parse.Object.saveAll([baz, qux], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.limit(1); query.find({ success: function(results) { @@ -256,11 +256,11 @@ describe('Parse.Query testing', () => { }); it("query with limit exceeding maxlimit", function(done) { - var baz = new TestObject({ foo: 'baz' }); - var qux = new TestObject({ foo: 'qux' }); + const baz = new TestObject({ foo: 'baz' }); + const qux = new TestObject({ foo: 'qux' }); reconfigureServer({ maxLimit: 1 }) Parse.Object.saveAll([baz, qux], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.limit(2); query.find({ success: function(results) { @@ -272,9 +272,9 @@ describe('Parse.Query testing', () => { }); it("containedIn object array queries", function(done) { - var messageList = []; - for (var i = 0; i < 4; ++i) { - var message = new TestObject({}); + const messageList = []; + for (let i = 0; i < 4; ++i) { + const message = new TestObject({}); if (i > 0) { message.set('prior', messageList[i - 1]); } @@ -284,11 +284,11 @@ describe('Parse.Query testing', () => { Parse.Object.saveAll(messageList, function() { equal(messageList.length, 4); - var inList = []; + const inList = []; inList.push(messageList[0]); inList.push(messageList[2]); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.containedIn('prior', inList); query.find({ success: function(results) { @@ -356,14 +356,14 @@ describe('Parse.Query testing', () => { }); it("containsAll number array queries", function(done) { - var NumberSet = Parse.Object.extend({ className: "NumberSet" }); + const NumberSet = Parse.Object.extend({ className: "NumberSet" }); - var objectsList = []; + const objectsList = []; objectsList.push(new NumberSet({ "numbers" : [1, 2, 3, 4, 5] })); objectsList.push(new NumberSet({ "numbers" : [1, 3, 4, 5] })); Parse.Object.saveAll(objectsList, function() { - var query = new Parse.Query(NumberSet); + const query = new Parse.Query(NumberSet); query.containsAll("numbers", [1, 2, 3]); query.find({ success: function(results) { @@ -382,14 +382,14 @@ describe('Parse.Query testing', () => { }); it("containsAll string array queries", function(done) { - var StringSet = Parse.Object.extend({ className: "StringSet" }); + const StringSet = Parse.Object.extend({ className: "StringSet" }); - var objectsList = []; + const objectsList = []; objectsList.push(new StringSet({ "strings" : ["a", "b", "c", "d", "e"] })); objectsList.push(new StringSet({ "strings" : ["a", "c", "d", "e"] })); Parse.Object.saveAll(objectsList, function() { - var query = new Parse.Query(StringSet); + const query = new Parse.Query(StringSet); query.containsAll("strings", ["a", "b", "c"]); query.find({ success: function(results) { @@ -404,36 +404,36 @@ describe('Parse.Query testing', () => { }); it("containsAll date array queries", function(done) { - var DateSet = Parse.Object.extend({ className: "DateSet" }); + const DateSet = Parse.Object.extend({ className: "DateSet" }); function parseDate(iso8601) { - var regexp = new RegExp( + const regexp = new RegExp( '^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})' + 'T' + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' + '(.([0-9]+))?' + 'Z$'); - var match = regexp.exec(iso8601); + const match = regexp.exec(iso8601); if (!match) { return null; } - var year = match[1] || 0; - var month = (match[2] || 1) - 1; - var day = match[3] || 0; - var hour = match[4] || 0; - var minute = match[5] || 0; - var second = match[6] || 0; - var milli = match[8] || 0; + const year = match[1] || 0; + const month = (match[2] || 1) - 1; + const day = match[3] || 0; + const hour = match[4] || 0; + const minute = match[5] || 0; + const second = match[6] || 0; + const milli = match[8] || 0; return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); } - var makeDates = function(stringArray) { + const makeDates = function(stringArray) { return stringArray.map(function(dateStr) { return parseDate(dateStr + "T00:00:00Z"); }); }; - var objectsList = []; + const objectsList = []; objectsList.push(new DateSet({ "dates" : makeDates(["2013-02-01", "2013-02-02", "2013-02-03", "2013-02-04"]) @@ -443,7 +443,7 @@ describe('Parse.Query testing', () => { })); Parse.Object.saveAll(objectsList, function() { - var query = new Parse.Query(DateSet); + const query = new Parse.Query(DateSet); query.containsAll("dates", makeDates( ["2013-02-01", "2013-02-02", "2013-02-03"])); query.find({ @@ -461,31 +461,31 @@ describe('Parse.Query testing', () => { it("containsAll object array queries", function(done) { - var MessageSet = Parse.Object.extend({ className: "MessageSet" }); + const MessageSet = Parse.Object.extend({ className: "MessageSet" }); - var messageList = []; - for (var i = 0; i < 4; ++i) { + const messageList = []; + for (let i = 0; i < 4; ++i) { messageList.push(new TestObject({ 'i' : i })); } Parse.Object.saveAll(messageList, function() { equal(messageList.length, 4); - var messageSetList = []; + const messageSetList = []; messageSetList.push(new MessageSet({ 'messages' : messageList })); - var someList = []; + const someList = []; someList.push(messageList[0]); someList.push(messageList[1]); someList.push(messageList[3]); messageSetList.push(new MessageSet({ 'messages' : someList })); Parse.Object.saveAll(messageSetList, function() { - var inList = []; + const inList = []; inList.push(messageList[0]); inList.push(messageList[2]); - var query = new Parse.Query(MessageSet); + const query = new Parse.Query(MessageSet); query.containsAll('messages', inList); query.find({ success: function(results) { @@ -497,17 +497,17 @@ describe('Parse.Query testing', () => { }); }); - var BoxedNumber = Parse.Object.extend({ + const BoxedNumber = Parse.Object.extend({ className: "BoxedNumber" }); it("equalTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('number', 3); query.find({ success: function(results) { @@ -519,12 +519,12 @@ describe('Parse.Query testing', () => { }); it("equalTo undefined", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('number', undefined); query.find(expectSuccess({ success: function(results) { @@ -536,12 +536,12 @@ describe('Parse.Query testing', () => { }); it("lessThan queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.lessThan('number', 7); query.find({ success: function(results) { @@ -553,13 +553,13 @@ describe('Parse.Query testing', () => { }); it("lessThanOrEqualTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.lessThanOrEqualTo('number', 7); query.find({ success: function(results) { @@ -571,13 +571,13 @@ describe('Parse.Query testing', () => { }); it("greaterThan queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.greaterThan('number', 7); query.find({ success: function(results) { @@ -589,13 +589,13 @@ describe('Parse.Query testing', () => { }); it("greaterThanOrEqualTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.greaterThanOrEqualTo('number', 7); query.find({ success: function(results) { @@ -607,13 +607,13 @@ describe('Parse.Query testing', () => { }); it("lessThanOrEqualTo greaterThanOrEqualTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.lessThanOrEqualTo('number', 7); query.greaterThanOrEqualTo('number', 7); query.find({ @@ -626,13 +626,13 @@ describe('Parse.Query testing', () => { }); it("lessThan greaterThan queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.lessThan('number', 9); query.greaterThan('number', 3); query.find({ @@ -645,13 +645,13 @@ describe('Parse.Query testing', () => { }); it("notEqualTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.notEqualTo('number', 5); query.find({ success: function(results) { @@ -663,13 +663,13 @@ describe('Parse.Query testing', () => { }); it("containedIn queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.containedIn('number', [3,5,7,9,11]); query.find({ success: function(results) { @@ -681,13 +681,13 @@ describe('Parse.Query testing', () => { }); it("notContainedIn queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.notContainedIn('number', [3,5,7,9,11]); query.find({ success: function(results) { @@ -700,13 +700,13 @@ describe('Parse.Query testing', () => { it("objectId containedIn queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function(list) { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.containedIn('objectId', [list[2].id, list[3].id, list[0].id, "NONSENSE"]); @@ -727,13 +727,13 @@ describe('Parse.Query testing', () => { }); it("objectId equalTo queries", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function(list) { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('objectId', list[4].id); query.find({ success: function(results) { @@ -750,13 +750,13 @@ describe('Parse.Query testing', () => { }); it("find no elements", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('number', 17); query.find(expectSuccess({ success: function(results) { @@ -768,7 +768,7 @@ describe('Parse.Query testing', () => { }); it("find with error", function(done) { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('$foo', 'bar'); query.find(expectError(Parse.Error.INVALID_KEY_NAME, done)); }); @@ -776,8 +776,8 @@ describe('Parse.Query testing', () => { it("get", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'})], function(items) { ok(items[0]); - var objectId = items[0].id; - var query = new Parse.Query(TestObject); + const objectId = items[0].id; + const query = new Parse.Query(TestObject); query.get(objectId, { success: function(result) { ok(result); @@ -794,7 +794,7 @@ describe('Parse.Query testing', () => { it("get undefined", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'})], function(items) { ok(items[0]); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(undefined, { success: fail, error: done, @@ -805,7 +805,7 @@ describe('Parse.Query testing', () => { it("get error", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'})], function(items) { ok(items[0]); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get("InvalidObjectID", { success: function() { ok(false, "The get should have failed."); @@ -821,7 +821,7 @@ describe('Parse.Query testing', () => { it("first", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo('foo', 'bar'); query.first({ success: function(result) { @@ -834,7 +834,7 @@ describe('Parse.Query testing', () => { it("first no result", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo('foo', 'baz'); query.first({ success: function(result) { @@ -848,7 +848,7 @@ describe('Parse.Query testing', () => { it("first with two results", function(done) { Parse.Object.saveAll([new TestObject({foo: 'bar'}), new TestObject({foo: 'bar'})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo('foo', 'bar'); query.first({ success: function(result) { @@ -860,22 +860,22 @@ describe('Parse.Query testing', () => { }); it("first with error", function(done) { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.equalTo('$foo', 'bar'); query.first(expectError(Parse.Error.INVALID_KEY_NAME, done)); }); - var Container = Parse.Object.extend({ + const Container = Parse.Object.extend({ className: "Container" }); it("notEqualTo object", function(done) { - var item1 = new TestObject(); - var item2 = new TestObject(); - var container1 = new Container({item: item1}); - var container2 = new Container({item: item2}); + const item1 = new TestObject(); + const item2 = new TestObject(); + const container1 = new Container({item: item1}); + const container2 = new Container({item: item2}); Parse.Object.saveAll([item1, item2, container1, container2], function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.notEqualTo('item', item1); query.find({ success: function(results) { @@ -888,7 +888,7 @@ describe('Parse.Query testing', () => { it("skip", function(done) { Parse.Object.saveAll([new TestObject(), new TestObject()], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.skip(1); query.find({ success: function(results) { @@ -907,7 +907,7 @@ describe('Parse.Query testing', () => { it("skip doesn't affect count", function(done) { Parse.Object.saveAll([new TestObject(), new TestObject()], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.count({ success: function(count) { equal(count, 2); @@ -930,13 +930,13 @@ describe('Parse.Query testing', () => { }); it("count", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.greaterThan("number", 1); query.count({ success: function(count) { @@ -948,11 +948,11 @@ describe('Parse.Query testing', () => { }); it("order by ascending number", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([3, 1, 2].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.ascending("number"); query.find(expectSuccess({ success: function(results) { @@ -967,11 +967,11 @@ describe('Parse.Query testing', () => { }); it("order by descending number", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([3, 1, 2].map(makeBoxedNumber)).then(function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("number"); query.find(expectSuccess({ success: function(results) { @@ -986,14 +986,14 @@ describe('Parse.Query testing', () => { }); it("order by ascending number then descending string", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function(num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function(num, i) { return new BoxedNumber({ number: num, string: strings[i] }); }; Parse.Object.saveAll( [3, 1, 3, 2].map(makeBoxedNumber)).then( function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.ascending("number").addDescending("string"); query.find(expectSuccess({ success: function(results) { @@ -1013,15 +1013,15 @@ describe('Parse.Query testing', () => { }); it("order by descending number then ascending string", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function(num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function(num, i) { return new BoxedNumber({ number: num, string: strings[i] }); }; const objects = [3, 1, 3, 2].map(makeBoxedNumber); Parse.Object.saveAll(objects) .then(() => { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("number").addAscending("string"); return query.find(); }).then((results) => { @@ -1042,13 +1042,13 @@ describe('Parse.Query testing', () => { }); it("order by descending number and string", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function(num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function(num, i) { return new BoxedNumber({ number: num, string: strings[i] }); }; Parse.Object.saveAll([3, 1, 3, 2].map(makeBoxedNumber)).then( function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("number,string"); query.find(expectSuccess({ success: function(results) { @@ -1068,13 +1068,13 @@ describe('Parse.Query testing', () => { }); it("order by descending number and string, with space", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function (num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function (num, i) { return new BoxedNumber({number: num, string: strings[i]}); }; Parse.Object.saveAll([3, 1, 3, 2].map(makeBoxedNumber)).then( function () { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("number, string"); query.find(expectSuccess({ success: function (results) { @@ -1098,13 +1098,13 @@ describe('Parse.Query testing', () => { }); it("order by descending number and string, with array arg", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function(num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function(num, i) { return new BoxedNumber({ number: num, string: strings[i] }); }; Parse.Object.saveAll([3, 1, 3, 2].map(makeBoxedNumber)).then( function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending(["number", "string"]); query.find(expectSuccess({ success: function(results) { @@ -1124,13 +1124,13 @@ describe('Parse.Query testing', () => { }); it("order by descending number and string, with multiple args", function(done) { - var strings = ["a", "b", "c", "d"]; - var makeBoxedNumber = function(num, i) { + const strings = ["a", "b", "c", "d"]; + const makeBoxedNumber = function(num, i) { return new BoxedNumber({ number: num, string: strings[i] }); }; Parse.Object.saveAll([3, 1, 3, 2].map(makeBoxedNumber)).then( function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("number", "string"); query.find(expectSuccess({ success: function(results) { @@ -1150,27 +1150,27 @@ describe('Parse.Query testing', () => { }); it("can't order by password", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; Parse.Object.saveAll([3, 1, 2].map(makeBoxedNumber), function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.ascending("_password"); query.find(expectError(Parse.Error.INVALID_KEY_NAME, done)); }); }); it("order by _created_at", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; - var numbers = [3, 1, 2].map(makeBoxedNumber); + const numbers = [3, 1, 2].map(makeBoxedNumber); numbers[0].save().then(() => { return numbers[1].save(); }).then(() => { return numbers[2].save(); }).then(function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.ascending("_created_at"); query.find({ success: function(results) { @@ -1189,16 +1189,16 @@ describe('Parse.Query testing', () => { }); it("order by createdAt", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; - var numbers = [3, 1, 2].map(makeBoxedNumber); + const numbers = [3, 1, 2].map(makeBoxedNumber); numbers[0].save().then(() => { return numbers[1].save(); }).then(() => { return numbers[2].save(); }).then(function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("createdAt"); query.find({ success: function(results) { @@ -1213,10 +1213,10 @@ describe('Parse.Query testing', () => { }); it("order by _updated_at", function(done) { - var makeBoxedNumber = function(i) { + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; - var numbers = [3, 1, 2].map(makeBoxedNumber); + const numbers = [3, 1, 2].map(makeBoxedNumber); numbers[0].save().then(() => { return numbers[1].save(); }).then(() => { @@ -1225,7 +1225,7 @@ describe('Parse.Query testing', () => { numbers[1].set("number", 4); numbers[1].save(null, { success: function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.ascending("_updated_at"); query.find({ success: function(results) { @@ -1242,8 +1242,8 @@ describe('Parse.Query testing', () => { }); it("order by updatedAt", function(done) { - var makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; - var numbers = [3, 1, 2].map(makeBoxedNumber); + const makeBoxedNumber = function(i) { return new BoxedNumber({ number: i }); }; + const numbers = [3, 1, 2].map(makeBoxedNumber); numbers[0].save().then(() => { return numbers[1].save(); }).then(() => { @@ -1252,7 +1252,7 @@ describe('Parse.Query testing', () => { numbers[1].set("number", 4); numbers[1].save(null, { success: function() { - var query = new Parse.Query(BoxedNumber); + const query = new Parse.Query(BoxedNumber); query.descending("_updated_at"); query.find({ success: function(results) { @@ -1270,16 +1270,16 @@ describe('Parse.Query testing', () => { // Returns a promise function makeTimeObject(start, i) { - var time = new Date(); + const time = new Date(); time.setSeconds(start.getSeconds() + i); - var item = new TestObject({name: "item" + i, time: time}); + const item = new TestObject({name: "item" + i, time: time}); return item.save(); } // Returns a promise for all the time objects function makeThreeTimeObjects() { - var start = new Date(); - var one, two, three; + const start = new Date(); + let one, two, three; return makeTimeObject(start, 1).then((o1) => { one = o1; return makeTimeObject(start, 2); @@ -1294,7 +1294,7 @@ describe('Parse.Query testing', () => { it("time equality", function(done) { makeThreeTimeObjects().then(function(list) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.equalTo("time", list[1].get("time")); query.find({ success: function(results) { @@ -1308,7 +1308,7 @@ describe('Parse.Query testing', () => { it("time lessThan", function(done) { makeThreeTimeObjects().then(function(list) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("time", list[2].get("time")); query.find({ success: function(results) { @@ -1322,7 +1322,7 @@ describe('Parse.Query testing', () => { // This test requires Date objects to be consistently stored as a Date. it("time createdAt", function(done) { makeThreeTimeObjects().then(function(list) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.greaterThanOrEqualTo("createdAt", list[0].createdAt); query.find({ success: function(results) { @@ -1334,12 +1334,12 @@ describe('Parse.Query testing', () => { }); it("matches string", function(done) { - var thing1 = new TestObject(); + const thing1 = new TestObject(); thing1.set("myString", "football"); - var thing2 = new TestObject(); + const thing2 = new TestObject(); thing2.set("myString", "soccer"); Parse.Object.saveAll([thing1, thing2], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches("myString", "^fo*\\wb[^o]l+$"); query.find({ success: function(results) { @@ -1351,12 +1351,12 @@ describe('Parse.Query testing', () => { }); it("matches regex", function(done) { - var thing1 = new TestObject(); + const thing1 = new TestObject(); thing1.set("myString", "football"); - var thing2 = new TestObject(); + const thing2 = new TestObject(); thing2.set("myString", "soccer"); Parse.Object.saveAll([thing1, thing2], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches("myString", /^fo*\wb[^o]l+$/); query.find({ success: function(results) { @@ -1368,10 +1368,10 @@ describe('Parse.Query testing', () => { }); it("case insensitive regex success", function(done) { - var thing = new TestObject(); + const thing = new TestObject(); thing.set("myString", "football"); Parse.Object.saveAll([thing], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches("myString", "FootBall", "i"); query.find({ success: function() { @@ -1382,16 +1382,16 @@ describe('Parse.Query testing', () => { }); it("regexes with invalid options fail", function(done) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches("myString", "FootBall", "some invalid option"); query.find(expectError(Parse.Error.INVALID_QUERY, done)); }); it("Use a regex that requires all modifiers", function(done) { - var thing = new TestObject(); + const thing = new TestObject(); thing.set("myString", "PArSe\nCom"); Parse.Object.saveAll([thing], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches( "myString", "parse # First fragment. We'll write this in one case but match " + @@ -1412,10 +1412,10 @@ describe('Parse.Query testing', () => { }); it("Regular expression constructor includes modifiers inline", function(done) { - var thing = new TestObject(); + const thing = new TestObject(); thing.set("myString", "\n\nbuffer\n\nparse.COM"); Parse.Object.saveAll([thing], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.matches("myString", /parse\.com/mi); query.find({ success: function(results) { @@ -1426,7 +1426,7 @@ describe('Parse.Query testing', () => { }); }); - var someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" + + const someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" + "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; it("contains", function(done) { @@ -1434,7 +1434,7 @@ describe('Parse.Query testing', () => { new TestObject({myString: "start" + someAscii}), new TestObject({myString: someAscii + "end"}), new TestObject({myString: someAscii})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.contains("myString", someAscii); query.find({ success: function(results) { @@ -1467,7 +1467,7 @@ describe('Parse.Query testing', () => { new TestObject({myString: "start" + someAscii}), new TestObject({myString: someAscii + "end"}), new TestObject({myString: someAscii})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.startsWith("myString", someAscii); query.find({ success: function(results) { @@ -1483,7 +1483,7 @@ describe('Parse.Query testing', () => { new TestObject({myString: "start" + someAscii}), new TestObject({myString: someAscii + "end"}), new TestObject({myString: someAscii})], function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.endsWith("myString", someAscii); query.find({ success: function(results) { @@ -1495,9 +1495,9 @@ describe('Parse.Query testing', () => { }); it("exists", function(done) { - var objects = []; - for (var i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { - var item = new TestObject(); + const objects = []; + for (const i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { + const item = new TestObject(); if (i % 2 === 0) { item.set('x', i + 1); } else { @@ -1506,12 +1506,12 @@ describe('Parse.Query testing', () => { objects.push(item); } Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.exists("x"); query.find({ success: function(results) { equal(results.length, 5); - for (var result of results) { + for (const result of results) { ok(result.get("x")); } done(); @@ -1521,9 +1521,9 @@ describe('Parse.Query testing', () => { }); it("doesNotExist", function(done) { - var objects = []; - for (var i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { - var item = new TestObject(); + const objects = []; + for (const i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { + const item = new TestObject(); if (i % 2 === 0) { item.set('x', i + 1); } else { @@ -1532,12 +1532,12 @@ describe('Parse.Query testing', () => { objects.push(item); } Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.doesNotExist("x"); query.find({ success: function(results) { equal(results.length, 4); - for (var result of results) { + for (const result of results) { ok(result.get("y")); } done(); @@ -1547,11 +1547,11 @@ describe('Parse.Query testing', () => { }); it("exists relation", function(done) { - var objects = []; - for (var i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { - var container = new Container(); + const objects = []; + for (const i of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { + const container = new Container(); if (i % 2 === 0) { - var item = new TestObject(); + const item = new TestObject(); item.set('x', i); container.set('x', item); objects.push(item); @@ -1561,12 +1561,12 @@ describe('Parse.Query testing', () => { objects.push(container); } Parse.Object.saveAll(objects).then(function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.exists("x"); query.find({ success: function(results) { equal(results.length, 5); - for (var result of results) { + for (const result of results) { ok(result.get("x")); } done(); @@ -1576,11 +1576,11 @@ describe('Parse.Query testing', () => { }); it("doesNotExist relation", function(done) { - var objects = []; - for (var i of [0, 1, 2, 3, 4, 5, 6, 7]) { - var container = new Container(); + const objects = []; + for (const i of [0, 1, 2, 3, 4, 5, 6, 7]) { + const container = new Container(); if (i % 2 === 0) { - var item = new TestObject(); + const item = new TestObject(); item.set('x', i); container.set('x', item); objects.push(item); @@ -1590,12 +1590,12 @@ describe('Parse.Query testing', () => { objects.push(container); } Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.doesNotExist("x"); query.find({ success: function(results) { equal(results.length, 4); - for (var result of results) { + for (const result of results) { ok(result.get("y")); } done(); @@ -1605,20 +1605,20 @@ describe('Parse.Query testing', () => { }); it("don't include by default", function(done) { - var child = new TestObject(); - var parent = new Container(); + const child = new TestObject(); + const parent = new Container(); child.set("foo", "bar"); parent.set("child", child); Parse.Object.saveAll([child, parent], function() { child._clearServerData(); - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.find({ success: function(results) { equal(results.length, 1); - var parentAgain = results[0]; - var goodURL = Parse.serverURL; + const parentAgain = results[0]; + const goodURL = Parse.serverURL; Parse.serverURL = "YAAAAAAAAARRRRRGGGGGGGGG"; - var childAgain = parentAgain.get("child"); + const childAgain = parentAgain.get("child"); ok(childAgain); equal(childAgain.get("foo"), undefined); Parse.serverURL = goodURL; @@ -1629,20 +1629,20 @@ describe('Parse.Query testing', () => { }); it("include relation", function(done) { - var child = new TestObject(); - var parent = new Container(); + const child = new TestObject(); + const parent = new Container(); child.set("foo", "bar"); parent.set("child", child); Parse.Object.saveAll([child, parent], function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.include("child"); query.find({ success: function(results) { equal(results.length, 1); - var parentAgain = results[0]; - var goodURL = Parse.serverURL; + const parentAgain = results[0]; + const goodURL = Parse.serverURL; Parse.serverURL = "YAAAAAAAAARRRRRGGGGGGGGG"; - var childAgain = parentAgain.get("child"); + const childAgain = parentAgain.get("child"); ok(childAgain); equal(childAgain.get("foo"), "bar"); Parse.serverURL = goodURL; @@ -1653,20 +1653,20 @@ describe('Parse.Query testing', () => { }); it("include relation array", function(done) { - var child = new TestObject(); - var parent = new Container(); + const child = new TestObject(); + const parent = new Container(); child.set("foo", "bar"); parent.set("child", child); Parse.Object.saveAll([child, parent], function() { - var query = new Parse.Query(Container); + const query = new Parse.Query(Container); query.include(["child"]); query.find({ success: function(results) { equal(results.length, 1); - var parentAgain = results[0]; - var goodURL = Parse.serverURL; + const parentAgain = results[0]; + const goodURL = Parse.serverURL; Parse.serverURL = "YAAAAAAAAARRRRRGGGGGGGGG"; - var childAgain = parentAgain.get("child"); + const childAgain = parentAgain.get("child"); ok(childAgain); equal(childAgain.get("foo"), "bar"); Parse.serverURL = goodURL; @@ -1677,12 +1677,12 @@ describe('Parse.Query testing', () => { }); it("nested include", function(done) { - var Child = Parse.Object.extend("Child"); - var Parent = Parse.Object.extend("Parent"); - var Grandparent = Parse.Object.extend("Grandparent"); - var objects = []; - for (var i = 0; i < 5; ++i) { - var grandparent = new Grandparent({ + const Child = Parse.Object.extend("Child"); + const Parent = Parse.Object.extend("Parent"); + const Grandparent = Parse.Object.extend("Grandparent"); + const objects = []; + for (let i = 0; i < 5; ++i) { + const grandparent = new Grandparent({ z:i, parent: new Parent({ y:i, @@ -1695,12 +1695,12 @@ describe('Parse.Query testing', () => { } Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(Grandparent); + const query = new Parse.Query(Grandparent); query.include(["parent.child"]); query.find({ success: function(results) { equal(results.length, 5); - for (var object of results) { + for (const object of results) { equal(object.get("z"), object.get("parent").get("y")); equal(object.get("z"), object.get("parent").get("child").get("x")); } @@ -1711,21 +1711,21 @@ describe('Parse.Query testing', () => { }); it("include doesn't make dirty wrong", function(done) { - var Parent = Parse.Object.extend("ParentObject"); - var Child = Parse.Object.extend("ChildObject"); - var parent = new Parent(); - var child = new Child(); + const Parent = Parse.Object.extend("ParentObject"); + const Child = Parse.Object.extend("ChildObject"); + const parent = new Parent(); + const child = new Child(); child.set("foo", "bar"); parent.set("child", child); Parse.Object.saveAll([child, parent], function() { - var query = new Parse.Query(Parent); + const query = new Parse.Query(Parent); query.include("child"); query.find({ success: function(results) { equal(results.length, 1); - var parentAgain = results[0]; - var childAgain = parentAgain.get("child"); + const parentAgain = results[0]; + const childAgain = parentAgain.get("child"); equal(childAgain.id, child.id); equal(parentAgain.id, parent.id); equal(childAgain.get("foo"), "bar"); @@ -1825,7 +1825,7 @@ describe('Parse.Query testing', () => { } Parse.Object.saveAll(objects).then(() => { const object = new Parse.Object("AContainer"); - for (var i = 0; i < objects.length; i++) { + for (let i = 0; i < objects.length; i++) { if (i % 2 == 0) { objects[i].id = 'randomThing' } else { @@ -1886,16 +1886,16 @@ describe('Parse.Query testing', () => { }); it("result object creation uses current extension", function(done) { - var ParentObject = Parse.Object.extend({ className: "ParentObject" }); + const ParentObject = Parse.Object.extend({ className: "ParentObject" }); // Add a foo() method to ChildObject. - var ChildObject = Parse.Object.extend("ChildObject", { + let ChildObject = Parse.Object.extend("ChildObject", { foo: function() { return "foo"; } }); - var parent = new ParentObject(); - var child = new ChildObject(); + const parent = new ParentObject(); + const child = new ChildObject(); parent.set("child", child); Parse.Object.saveAll([child, parent], function() { // Add a bar() method to ChildObject. @@ -1905,13 +1905,13 @@ describe('Parse.Query testing', () => { } }); - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.include("child"); query.find({ success: function(results) { equal(results.length, 1); - var parentAgain = results[0]; - var childAgain = parentAgain.get("child"); + const parentAgain = results[0]; + const childAgain = parentAgain.get("child"); equal(childAgain.foo(), "foo"); equal(childAgain.bar(), "bar"); done(); @@ -1921,10 +1921,10 @@ describe('Parse.Query testing', () => { }); it("matches query", function(done) { - var ParentObject = Parse.Object.extend("ParentObject"); - var ChildObject = Parse.Object.extend("ChildObject"); - var objects = []; - for (var i = 0; i < 10; ++i) { + const ParentObject = Parse.Object.extend("ParentObject"); + const ChildObject = Parse.Object.extend("ChildObject"); + const objects = []; + for (let i = 0; i < 10; ++i) { objects.push( new ParentObject({ child: new ChildObject({x: i}), @@ -1932,22 +1932,22 @@ describe('Parse.Query testing', () => { })); } Parse.Object.saveAll(objects, function() { - var subQuery = new Parse.Query(ChildObject); + const subQuery = new Parse.Query(ChildObject); subQuery.greaterThan("x", 5); - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.matchesQuery("child", subQuery); query.find({ success: function(results) { equal(results.length, 4); - for (var object of results) { + for (const object of results) { ok(object.get("x") > 15); } - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.doesNotMatchQuery("child", subQuery); query.find({ success: function (results) { equal(results.length, 6); - for (var object of results) { + for (const object of results) { ok(object.get("x") >= 10); ok(object.get("x") <= 15); done(); @@ -1960,9 +1960,9 @@ describe('Parse.Query testing', () => { }); it("select query", function(done) { - var RestaurantObject = Parse.Object.extend("Restaurant"); - var PersonObject = Parse.Object.extend("Person"); - var objects = [ + const RestaurantObject = Parse.Object.extend("Restaurant"); + const PersonObject = Parse.Object.extend("Person"); + const objects = [ new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), new PersonObject({ name: "Bob", hometown: "Djibouti" }), @@ -1971,9 +1971,9 @@ describe('Parse.Query testing', () => { ]; Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(RestaurantObject); + const query = new Parse.Query(RestaurantObject); query.greaterThan("ratings", 4); - var mainQuery = new Parse.Query(PersonObject); + const mainQuery = new Parse.Query(PersonObject); mainQuery.matchesKeyInQuery("hometown", "location", query); mainQuery.find(expectSuccess({ success: function(results) { @@ -1986,9 +1986,9 @@ describe('Parse.Query testing', () => { }); it('$select inside $or', (done) => { - var Restaurant = Parse.Object.extend('Restaurant'); - var Person = Parse.Object.extend('Person'); - var objects = [ + const Restaurant = Parse.Object.extend('Restaurant'); + const Person = Parse.Object.extend('Person'); + const objects = [ new Restaurant({ ratings: 5, location: "Djibouti" }), new Restaurant({ ratings: 3, location: "Ouagadougou" }), new Person({ name: "Bob", hometown: "Djibouti" }), @@ -1997,13 +1997,13 @@ describe('Parse.Query testing', () => { ]; Parse.Object.saveAll(objects).then(() => { - var subquery = new Parse.Query(Restaurant); + const subquery = new Parse.Query(Restaurant); subquery.greaterThan('ratings', 4); - var query1 = new Parse.Query(Person); + const query1 = new Parse.Query(Person); query1.matchesKeyInQuery('hometown', 'location', subquery); - var query2 = new Parse.Query(Person); + const query2 = new Parse.Query(Person); query2.equalTo('name', 'Tom'); - var query = Parse.Query.or(query1, query2); + const query = Parse.Query.or(query1, query2); return query.find(); }).then((results) => { expect(results.length).toEqual(2); @@ -2015,9 +2015,9 @@ describe('Parse.Query testing', () => { }); it("dontSelect query", function(done) { - var RestaurantObject = Parse.Object.extend("Restaurant"); - var PersonObject = Parse.Object.extend("Person"); - var objects = [ + const RestaurantObject = Parse.Object.extend("Restaurant"); + const PersonObject = Parse.Object.extend("Person"); + const objects = [ new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), new PersonObject({ name: "Bob", hometown: "Djibouti" }), @@ -2026,9 +2026,9 @@ describe('Parse.Query testing', () => { ]; Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(RestaurantObject); + const query = new Parse.Query(RestaurantObject); query.greaterThan("ratings", 4); - var mainQuery = new Parse.Query(PersonObject); + const mainQuery = new Parse.Query(PersonObject); mainQuery.doesNotMatchKeyInQuery("hometown", "location", query); mainQuery.find(expectSuccess({ success: function(results) { @@ -2064,19 +2064,19 @@ describe('Parse.Query testing', () => { }); it("equalTo on same column as $dontSelect should not break $dontSelect functionality (#3678)", function(done) { - var AuthorObject = Parse.Object.extend("Author"); - var BlockedObject = Parse.Object.extend("Blocked"); - var PostObject = Parse.Object.extend("Post"); + const AuthorObject = Parse.Object.extend("Author"); + const BlockedObject = Parse.Object.extend("Blocked"); + const PostObject = Parse.Object.extend("Post"); - var postAuthor = null; - var requestUser = null; + let postAuthor = null; + let requestUser = null; return new AuthorObject({ name: "Julius"}).save().then((user) => { postAuthor = user; return new AuthorObject({ name: "Bob"}).save(); }).then((user) => { requestUser = user; - var objects = [ + const objects = [ new PostObject({ author: postAuthor, title: "Lorem ipsum" }), new PostObject({ author: requestUser, title: "Kafka" }), new PostObject({ author: requestUser, title: "Brown fox" }), @@ -2084,7 +2084,7 @@ describe('Parse.Query testing', () => { ]; return Parse.Object.saveAll(objects); }).then(() => { - var banListQuery = new Parse.Query(BlockedObject); + const banListQuery = new Parse.Query(BlockedObject); banListQuery.equalTo("blockedUser", requestUser); return new Parse.Query(PostObject) @@ -2099,9 +2099,9 @@ describe('Parse.Query testing', () => { }); it("multiple dontSelect query", function(done) { - var RestaurantObject = Parse.Object.extend("Restaurant"); - var PersonObject = Parse.Object.extend("Person"); - var objects = [ + const RestaurantObject = Parse.Object.extend("Restaurant"); + const PersonObject = Parse.Object.extend("Person"); + const objects = [ new RestaurantObject({ ratings: 7, location: "Djibouti2" }), new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), @@ -2111,15 +2111,15 @@ describe('Parse.Query testing', () => { ]; Parse.Object.saveAll(objects, function() { - var query = new Parse.Query(RestaurantObject); + const query = new Parse.Query(RestaurantObject); query.greaterThan("ratings", 6); - var query2 = new Parse.Query(RestaurantObject); + const query2 = new Parse.Query(RestaurantObject); query2.lessThan("ratings", 4); - var subQuery = new Parse.Query(PersonObject); + const subQuery = new Parse.Query(PersonObject); subQuery.matchesKeyInQuery("hometown", "location", query); - var subQuery2 = new Parse.Query(PersonObject); + const subQuery2 = new Parse.Query(PersonObject); subQuery2.matchesKeyInQuery("hometown", "location", query2); - var mainQuery = new Parse.Query(PersonObject); + const mainQuery = new Parse.Query(PersonObject); mainQuery.doesNotMatchKeyInQuery("objectId", "objectId", Parse.Query.or(subQuery, subQuery2)); mainQuery.find(expectSuccess({ success: function(results) { @@ -2132,13 +2132,13 @@ describe('Parse.Query testing', () => { }); it("object with length", function(done) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.set("length", 5); equal(obj.get("length"), 5); obj.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.find({ success: function(results) { equal(results.length, 1); @@ -2161,13 +2161,13 @@ describe('Parse.Query testing', () => { it("include user", function(done) { Parse.User.signUp("bob", "password", { age: 21 }, { success: function(user) { - var TestObject = Parse.Object.extend("TestObject"); - var obj = new TestObject(); + const TestObject = Parse.Object.extend("TestObject"); + const obj = new TestObject(); obj.save({ owner: user }, { success: function(obj) { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.include("owner"); query.get(obj.id, { success: function(objAgain) { @@ -2196,22 +2196,22 @@ describe('Parse.Query testing', () => { }); it("or queries", function(done) { - var objects = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { - var object = new Parse.Object('BoxedNumber'); + const objects = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { + const object = new Parse.Object('BoxedNumber'); object.set('x', x); return object; }); Parse.Object.saveAll(objects, expectSuccess({ success: function() { - var query1 = new Parse.Query('BoxedNumber'); + const query1 = new Parse.Query('BoxedNumber'); query1.lessThan('x', 2); - var query2 = new Parse.Query('BoxedNumber'); + const query2 = new Parse.Query('BoxedNumber'); query2.greaterThan('x', 5); - var orQuery = Parse.Query.or(query1, query2); + const orQuery = Parse.Query.or(query1, query2); orQuery.find(expectSuccess({ success: function(results) { equal(results.length, 6); - for (var number of results) { + for (const number of results) { ok(number.get('x') < 2 || number.get('x') > 5); } done(); @@ -2223,10 +2223,10 @@ describe('Parse.Query testing', () => { // This relies on matchesQuery aka the $inQuery operator it("or complex queries", function(done) { - var objects = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { - var child = new Parse.Object('Child'); + const objects = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { + const child = new Parse.Object('Child'); child.set('x', x); - var parent = new Parse.Object('Parent'); + const parent = new Parse.Object('Parent'); parent.set('child', child); parent.set('y', x); return parent; @@ -2234,13 +2234,13 @@ describe('Parse.Query testing', () => { Parse.Object.saveAll(objects, expectSuccess({ success: function() { - var subQuery = new Parse.Query('Child'); + const subQuery = new Parse.Query('Child'); subQuery.equalTo('x', 4); - var query1 = new Parse.Query('Parent'); + const query1 = new Parse.Query('Parent'); query1.matchesQuery('child', subQuery); - var query2 = new Parse.Query('Parent'); + const query2 = new Parse.Query('Parent'); query2.lessThan('y', 2); - var orQuery = Parse.Query.or(query1, query2); + const orQuery = Parse.Query.or(query1, query2); orQuery.find(expectSuccess({ success: function(results) { equal(results.length, 3); @@ -2252,31 +2252,31 @@ describe('Parse.Query testing', () => { }); it("async methods", function(done) { - var saves = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { - var obj = new Parse.Object("TestObject"); + const saves = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(x) { + const obj = new Parse.Object("TestObject"); obj.set("x", x + 1); return obj.save(); }); Parse.Promise.when(saves).then(function() { - var query = new Parse.Query("TestObject"); + const query = new Parse.Query("TestObject"); query.ascending("x"); return query.first(); }).then(function(obj) { equal(obj.get("x"), 1); - var query = new Parse.Query("TestObject"); + const query = new Parse.Query("TestObject"); query.descending("x"); return query.find(); }).then(function(results) { equal(results.length, 10); - var query = new Parse.Query("TestObject"); + const query = new Parse.Query("TestObject"); return query.get(results[0].id); }).then(function(obj1) { equal(obj1.get("x"), 10); - var query = new Parse.Query("TestObject"); + const query = new Parse.Query("TestObject"); return query.count(); }).then(function(count) { @@ -2289,20 +2289,20 @@ describe('Parse.Query testing', () => { }); it("query.each", function(done) { - var TOTAL = 50; - var COUNT = 25; + const TOTAL = 50; + const COUNT = 25; - var items = range(TOTAL).map(function(x) { - var obj = new TestObject(); + const items = range(TOTAL).map(function(x) { + const obj = new TestObject(); obj.set("x", x); return obj; }); Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("x", COUNT); - var seen = []; + const seen = []; query.each(function(obj) { seen[obj.get("x")] = (seen[obj.get("x")] || 0) + 1; @@ -2310,7 +2310,7 @@ describe('Parse.Query testing', () => { batchSize: 10, success: function() { equal(seen.length, COUNT); - for (var i = 0; i < COUNT; i++) { + for (let i = 0; i < COUNT; i++) { equal(seen[i], 1, "Should have seen object number " + i); } done(); @@ -2324,24 +2324,24 @@ describe('Parse.Query testing', () => { }); it("query.each async", function(done) { - var TOTAL = 50; - var COUNT = 25; + const TOTAL = 50; + const COUNT = 25; expect(COUNT + 1); - var items = range(TOTAL).map(function(x) { - var obj = new TestObject(); + const items = range(TOTAL).map(function(x) { + const obj = new TestObject(); obj.set("x", x); return obj; }); - var seen = []; + const seen = []; Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("x", COUNT); return query.each(function(obj) { - var promise = new Parse.Promise(); + const promise = new Parse.Promise(); process.nextTick(function() { seen[obj.get("x")] = (seen[obj.get("x")] || 0) + 1; promise.resolve(); @@ -2353,7 +2353,7 @@ describe('Parse.Query testing', () => { }).then(function() { equal(seen.length, COUNT); - for (var i = 0; i < COUNT; i++) { + for (let i = 0; i < COUNT; i++) { equal(seen[i], 1, "Should have seen object number " + i); } done(); @@ -2361,19 +2361,19 @@ describe('Parse.Query testing', () => { }); it("query.each fails with order", function(done) { - var TOTAL = 50; - var COUNT = 25; + const TOTAL = 50; + const COUNT = 25; - var items = range(TOTAL).map(function(x) { - var obj = new TestObject(); + const items = range(TOTAL).map(function(x) { + const obj = new TestObject(); obj.set("x", x); return obj; }); - var seen = []; + const seen = []; Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("x", COUNT); query.ascending("x"); return query.each(function(obj) { @@ -2389,19 +2389,19 @@ describe('Parse.Query testing', () => { }); it("query.each fails with skip", function(done) { - var TOTAL = 50; - var COUNT = 25; + const TOTAL = 50; + const COUNT = 25; - var items = range(TOTAL).map(function(x) { - var obj = new TestObject(); + const items = range(TOTAL).map(function(x) { + const obj = new TestObject(); obj.set("x", x); return obj; }); - var seen = []; + const seen = []; Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("x", COUNT); query.skip(5); return query.each(function(obj) { @@ -2417,21 +2417,21 @@ describe('Parse.Query testing', () => { }); it("query.each fails with limit", function(done) { - var TOTAL = 50; - var COUNT = 25; + const TOTAL = 50; + const COUNT = 25; expect(0); - var items = range(TOTAL).map(function(x) { - var obj = new TestObject(); + const items = range(TOTAL).map(function(x) { + const obj = new TestObject(); obj.set("x", x); return obj; }); - var seen = []; + const seen = []; Parse.Object.saveAll(items).then(function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.lessThan("x", COUNT); query.limit(5); return query.each(function(obj) { @@ -2447,11 +2447,11 @@ describe('Parse.Query testing', () => { }); it("select keys query", function(done) { - var obj = new TestObject({ foo: 'baz', bar: 1 }); + const obj = new TestObject({ foo: 'baz', bar: 1 }); obj.save().then(function () { obj._clearServerData(); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.select('foo'); return query.first(); }).then(function(result) { @@ -2468,7 +2468,7 @@ describe('Parse.Query testing', () => { strictEqual(result.get('bar'), 1); }).then(function() { obj._clearServerData(); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.select([]); return query.first(); }).then(function(result) { @@ -2480,7 +2480,7 @@ describe('Parse.Query testing', () => { "expected 'bar' field to be unset"); }).then(function() { obj._clearServerData(); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.select(['foo','bar']); return query.first(); }).then(function(result) { @@ -2490,7 +2490,7 @@ describe('Parse.Query testing', () => { strictEqual(result.get('bar'), 1); }).then(function() { obj._clearServerData(); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.select('foo', 'bar'); return query.first(); }).then(function(result) { @@ -2507,11 +2507,11 @@ describe('Parse.Query testing', () => { }); it('select keys with each query', function(done) { - var obj = new TestObject({ foo: 'baz', bar: 1 }); + const obj = new TestObject({ foo: 'baz', bar: 1 }); obj.save().then(function() { obj._clearServerData(); - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.select('foo'); query.each(function(result) { ok(result.id, 'expected object id to be set'); @@ -2531,14 +2531,14 @@ describe('Parse.Query testing', () => { }); it('notEqual with array of pointers', (done) => { - var children = []; - var parents = []; - var promises = []; - for (var i = 0; i < 2; i++) { - var proc = (iter) => { - var child = new Parse.Object('Child'); + const children = []; + const parents = []; + const promises = []; + for (let i = 0; i < 2; i++) { + const proc = (iter) => { + const child = new Parse.Object('Child'); children.push(child); - var parent = new Parse.Object('Parent'); + const parent = new Parse.Object('Parent'); parents.push(parent); promises.push( child.save().then(() => { @@ -2550,7 +2550,7 @@ describe('Parse.Query testing', () => { proc(i); } Promise.all(promises).then(() => { - var query = new Parse.Query('Parent'); + const query = new Parse.Query('Parent'); query.notEqualTo('child', children[0]); return query.find(); }).then((results) => { @@ -2562,10 +2562,10 @@ describe('Parse.Query testing', () => { // PG don't support creating a null column it_exclude_dbs(['postgres'])('querying for null value', (done) => { - var obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.set('aNull', null); obj.save().then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); query.equalTo('aNull', null); return query.find(); }).then((results) => { @@ -2576,17 +2576,17 @@ describe('Parse.Query testing', () => { }); it('query within dictionary', (done) => { - var promises = []; - for (var i = 0; i < 2; i++) { - var proc = (iter) => { - var obj = new Parse.Object('TestObject'); + const promises = []; + for (let i = 0; i < 2; i++) { + const proc = (iter) => { + const obj = new Parse.Object('TestObject'); obj.set('aDict', { x: iter + 1, y: iter + 2 }); promises.push(obj.save()); }; proc(i); } Promise.all(promises).then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); query.equalTo('aDict.x', 1); return query.find(); }).then((results) => { @@ -2624,11 +2624,11 @@ describe('Parse.Query testing', () => { }); it('query match on array with single object', (done) => { - var target = {__type: 'Pointer', className: 'TestObject', objectId: 'abc123'}; - var obj = new Parse.Object('TestObject'); + const target = {__type: 'Pointer', className: 'TestObject', objectId: 'abc123'}; + const obj = new Parse.Object('TestObject'); obj.set('someObjs', [target]); obj.save().then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); query.equalTo('someObjs', target); return query.find(); }).then((results) => { @@ -2640,12 +2640,12 @@ describe('Parse.Query testing', () => { }); it('query match on array with multiple objects', (done) => { - var target1 = {__type: 'Pointer', className: 'TestObject', objectId: 'abc'}; - var target2 = {__type: 'Pointer', className: 'TestObject', objectId: '123'}; - var obj = new Parse.Object('TestObject'); + const target1 = {__type: 'Pointer', className: 'TestObject', objectId: 'abc'}; + const target2 = {__type: 'Pointer', className: 'TestObject', objectId: '123'}; + const obj = new Parse.Object('TestObject'); obj.set('someObjs', [target1, target2]); obj.save().then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); query.equalTo('someObjs', target1); return query.find(); }).then((results) => { @@ -2657,12 +2657,12 @@ describe('Parse.Query testing', () => { }); it('query should not match on array when searching for null', (done) => { - var target = {__type: 'Pointer', className: 'TestObject', objectId: '123'}; - var obj = new Parse.Object('TestObject'); + const target = {__type: 'Pointer', className: 'TestObject', objectId: '123'}; + const obj = new Parse.Object('TestObject'); obj.set('someKey', 'someValue'); obj.set('someObjs', [target]); obj.save().then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); query.equalTo('someKey', 'someValue'); query.equalTo('someObjs', null); return query.find(); @@ -2676,8 +2676,8 @@ describe('Parse.Query testing', () => { // #371 it('should properly interpret a query v1', (done) => { - var query = new Parse.Query("C1"); - var auxQuery = new Parse.Query("C1"); + const query = new Parse.Query("C1"); + const auxQuery = new Parse.Query("C1"); query.matchesKeyInQuery("A1", "A2", auxQuery); query.include("A3"); query.include("A2"); @@ -2691,30 +2691,30 @@ describe('Parse.Query testing', () => { }); it('should properly interpret a query v2', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "foo"); user.set("password", "bar"); return user.save().then((user) => { - var objIdQuery = new Parse.Query("_User").equalTo("objectId", user.id); - var blockedUserQuery = user.relation("blockedUsers").query(); + const objIdQuery = new Parse.Query("_User").equalTo("objectId", user.id); + const blockedUserQuery = user.relation("blockedUsers").query(); - var aResponseQuery = new Parse.Query("MatchRelationshipActivityResponse"); + const aResponseQuery = new Parse.Query("MatchRelationshipActivityResponse"); aResponseQuery.equalTo("userA", user); aResponseQuery.equalTo("userAResponse", 1); - var bResponseQuery = new Parse.Query("MatchRelationshipActivityResponse"); + const bResponseQuery = new Parse.Query("MatchRelationshipActivityResponse"); bResponseQuery.equalTo("userB", user); bResponseQuery.equalTo("userBResponse", 1); - var matchOr = Parse.Query.or(aResponseQuery, bResponseQuery); - var matchRelationshipA = new Parse.Query("_User"); + const matchOr = Parse.Query.or(aResponseQuery, bResponseQuery); + const matchRelationshipA = new Parse.Query("_User"); matchRelationshipA.matchesKeyInQuery("objectId", "userAObjectId", matchOr); - var matchRelationshipB = new Parse.Query("_User"); + const matchRelationshipB = new Parse.Query("_User"); matchRelationshipB.matchesKeyInQuery("objectId", "userBObjectId", matchOr); - var orQuery = Parse.Query.or(objIdQuery, blockedUserQuery, matchRelationshipA, matchRelationshipB); - var query = new Parse.Query("_User"); + const orQuery = Parse.Query.or(objIdQuery, blockedUserQuery, matchRelationshipA, matchRelationshipB); + const query = new Parse.Query("_User"); query.doesNotMatchQuery("objectId", orQuery); return query.find(); }).then(() => { @@ -2727,9 +2727,9 @@ describe('Parse.Query testing', () => { }); it("should match a key in an array (#3195)", function(done) { - var AuthorObject = Parse.Object.extend("Author"); - var GroupObject = Parse.Object.extend("Group"); - var PostObject = Parse.Object.extend("Post"); + const AuthorObject = Parse.Object.extend("Author"); + const GroupObject = Parse.Object.extend("Group"); + const PostObject = Parse.Object.extend("Post"); return new AuthorObject().save().then((user) => { const post = new PostObject({ @@ -2756,16 +2756,16 @@ describe('Parse.Query testing', () => { }); it('should find objects with array of pointers', (done) => { - var objects = []; + const objects = []; while(objects.length != 5) { - var object = new Parse.Object('ContainedObject'); + const object = new Parse.Object('ContainedObject'); object.set('index', objects.length); objects.push(object); } Parse.Object.saveAll(objects).then((objects) => { - var container = new Parse.Object('Container'); - var pointers = objects.map((obj) => { + const container = new Parse.Object('Container'); + const pointers = objects.map((obj) => { return { __type: 'Pointer', className: 'ContainedObject', @@ -2882,17 +2882,17 @@ describe('Parse.Query testing', () => { }); it('include for specific object', function(done){ - var child = new Parse.Object('Child'); - var parent = new Parse.Object('Parent'); + const child = new Parse.Object('Child'); + const parent = new Parse.Object('Parent'); child.set('foo', 'bar'); parent.set('child', child); Parse.Object.saveAll([child, parent], function(response){ - var savedParent = response[1]; - var parentQuery = new Parse.Query('Parent'); + const savedParent = response[1]; + const parentQuery = new Parse.Query('Parent'); parentQuery.include('child'); parentQuery.get(savedParent.id, { success: function(parentObj) { - var childPointer = parentObj.get('child'); + const childPointer = parentObj.get('child'); ok(childPointer); equal(childPointer.get('foo'), 'bar'); done(); @@ -2901,13 +2901,13 @@ describe('Parse.Query testing', () => { }); }); - it('select keys for specific object', function(done){ - var Foobar = new Parse.Object('Foobar'); + it('select keys for specific object', function(done) { + const Foobar = new Parse.Object('Foobar'); Foobar.set('foo', 'bar'); Foobar.set('fizz', 'buzz'); Foobar.save({ success: function(savedFoobar){ - var foobarQuery = new Parse.Query('Foobar'); + const foobarQuery = new Parse.Query('Foobar'); foobarQuery.select('fizz'); foobarQuery.get(savedFoobar.id,{ success: function(foobarObj){ @@ -2921,8 +2921,8 @@ describe('Parse.Query testing', () => { }); it('select nested keys (issue #1567)', function(done) { - var Foobar = new Parse.Object('Foobar'); - var BarBaz = new Parse.Object('Barbaz'); + const Foobar = new Parse.Object('Foobar'); + const BarBaz = new Parse.Object('Barbaz'); BarBaz.set('key', 'value'); BarBaz.set('otherKey', 'value'); BarBaz.save().then(() => { @@ -2931,7 +2931,7 @@ describe('Parse.Query testing', () => { Foobar.set('barBaz', BarBaz); return Foobar.save(); }).then(function(savedFoobar){ - var foobarQuery = new Parse.Query('Foobar'); + const foobarQuery = new Parse.Query('Foobar'); foobarQuery.include('barBaz'); foobarQuery.select(['fizz', 'barBaz.key']); foobarQuery.get(savedFoobar.id,{ @@ -2951,9 +2951,9 @@ describe('Parse.Query testing', () => { }); it('select nested keys 2 level (issue #1567)', function(done) { - var Foobar = new Parse.Object('Foobar'); - var BarBaz = new Parse.Object('Barbaz'); - var Bazoo = new Parse.Object('Bazoo'); + const Foobar = new Parse.Object('Foobar'); + const BarBaz = new Parse.Object('Barbaz'); + const Bazoo = new Parse.Object('Bazoo'); Bazoo.set('some', 'thing'); Bazoo.set('otherSome', 'value'); @@ -2968,7 +2968,7 @@ describe('Parse.Query testing', () => { Foobar.set('barBaz', BarBaz); return Foobar.save(); }).then(function(savedFoobar){ - var foobarQuery = new Parse.Query('Foobar'); + const foobarQuery = new Parse.Query('Foobar'); foobarQuery.include('barBaz'); foobarQuery.include('barBaz.bazoo'); foobarQuery.select(['fizz', 'barBaz.key', 'barBaz.bazoo.some']); @@ -2991,9 +2991,9 @@ describe('Parse.Query testing', () => { }); it('select nested keys 2 level without include (issue #3185)', function(done) { - var Foobar = new Parse.Object('Foobar'); - var BarBaz = new Parse.Object('Barbaz'); - var Bazoo = new Parse.Object('Bazoo'); + const Foobar = new Parse.Object('Foobar'); + const BarBaz = new Parse.Object('Barbaz'); + const Bazoo = new Parse.Object('Bazoo'); Bazoo.set('some', 'thing'); Bazoo.set('otherSome', 'value'); @@ -3008,7 +3008,7 @@ describe('Parse.Query testing', () => { Foobar.set('barBaz', BarBaz); return Foobar.save(); }).then(function(savedFoobar){ - var foobarQuery = new Parse.Query('Foobar'); + const foobarQuery = new Parse.Query('Foobar'); foobarQuery.select(['fizz', 'barBaz.key', 'barBaz.bazoo.some']); return foobarQuery.get(savedFoobar.id); }).then((foobarObj) => { @@ -3031,9 +3031,9 @@ describe('Parse.Query testing', () => { }); it('properly handles nested ors', function(done) { - var objects = []; + const objects = []; while(objects.length != 4) { - var obj = new Parse.Object('Object'); + const obj = new Parse.Object('Object'); obj.set('x', objects.length); objects.push(obj) } diff --git a/spec/ParseRelation.spec.js b/spec/ParseRelation.spec.js index ffbbb04b..ad5ba361 100644 --- a/spec/ParseRelation.spec.js +++ b/spec/ParseRelation.spec.js @@ -2,16 +2,16 @@ // This is a port of the test suite: // hungry/js/test/parse_relation_test.js -var ChildObject = Parse.Object.extend({className: "ChildObject"}); -var ParentObject = Parse.Object.extend({className: "ParentObject"}); +const ChildObject = Parse.Object.extend({className: "ChildObject"}); +const ParentObject = Parse.Object.extend({className: "ParentObject"}); describe('Parse.Relation testing', () => { it("simple add and remove relation", (done) => { - var child = new ChildObject(); + const child = new ChildObject(); child.set("x", 2); - var parent = new ParentObject(); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("child"); + const relation = parent.relation("child"); child.save().then(() => { relation.add(child); @@ -42,24 +42,24 @@ describe('Parse.Relation testing', () => { }); it("query relation without schema", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x:i})); } Parse.Object.saveAll(childObjects, expectSuccess({ success: function() { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("child"); + const relation = parent.relation("child"); relation.add(childObjects[0]); parent.save(null, expectSuccess({ success: function() { - var parentAgain = new ParentObject(); + const parentAgain = new ParentObject(); parentAgain.id = parent.id; - var relation = parentAgain.relation("child"); + const relation = parentAgain.relation("child"); relation.query().find(expectSuccess({ success: function(list) { equal(list.length, 1, @@ -77,25 +77,25 @@ describe('Parse.Relation testing', () => { it("relations are constructed right from query", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects, { success: function() { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("child"); + const relation = parent.relation("child"); relation.add(childObjects[0]); parent.save(null, { success: function() { - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.get(parent.id, { success: function(object) { - var relationAgain = object.relation("child"); + const relationAgain = object.relation("child"); relationAgain.query().find({ success: function(list) { equal(list.length, 1, @@ -122,17 +122,17 @@ describe('Parse.Relation testing', () => { }); it("compound add and remove relation", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } - var parent; - var relation; + let parent; + let relation; Parse.Object.saveAll(childObjects).then(function() { - var ParentObject = Parse.Object.extend('ParentObject'); + const ParentObject = Parse.Object.extend('ParentObject'); parent = new ParentObject(); parent.set('x', 4); relation = parent.relation('child'); @@ -164,17 +164,17 @@ describe('Parse.Relation testing', () => { }); it("related at ordering optimizations", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } - var parent; - var relation; + let parent; + let relation; Parse.Object.saveAll(childObjects).then(function() { - var ParentObject = Parse.Object.extend('ParentObject'); + const ParentObject = Parse.Object.extend('ParentObject'); parent = new ParentObject(); parent.set('x', 4); relation = parent.relation('child'); @@ -193,24 +193,24 @@ describe('Parse.Relation testing', () => { it_exclude_dbs(['postgres'])("queries with relations", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects, { success: function() { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("child"); + const relation = parent.relation("child"); relation.add(childObjects[0]); relation.add(childObjects[1]); relation.add(childObjects[2]); parent.save(null, { success: function() { - var query = relation.query(); + const query = relation.query(); query.equalTo("x", 2); query.find({ success: function(list) { @@ -230,34 +230,34 @@ describe('Parse.Relation testing', () => { }); it("queries on relation fields", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects, { success: function() { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("child"); + const relation = parent.relation("child"); relation.add(childObjects[0]); relation.add(childObjects[1]); relation.add(childObjects[2]); - var parent2 = new ParentObject(); + const parent2 = new ParentObject(); parent2.set("x", 3); - var relation2 = parent2.relation("child"); + const relation2 = parent2.relation("child"); relation2.add(childObjects[4]); relation2.add(childObjects[5]); relation2.add(childObjects[6]); - var parents = []; + const parents = []; parents.push(parent); parents.push(parent2); Parse.Object.saveAll(parents, { success: function() { - var query = new Parse.Query(ParentObject); - var objects = []; + const query = new Parse.Query(ParentObject); + const objects = []; objects.push(childObjects[4]); objects.push(childObjects[9]); query.containedIn("child", objects); @@ -324,32 +324,32 @@ describe('Parse.Relation testing', () => { }); it_exclude_dbs(['postgres'])("query on pointer and relation fields with equal", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects).then(() => { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("toChilds"); + const relation = parent.relation("toChilds"); relation.add(childObjects[0]); relation.add(childObjects[1]); relation.add(childObjects[2]); - var parent2 = new ParentObject(); + const parent2 = new ParentObject(); parent2.set("x", 3); parent2.set("toChild", childObjects[2]); - var parents = []; + const parents = []; parents.push(parent); parents.push(parent2); parents.push(new ParentObject()); return Parse.Object.saveAll(parents).then(() => { - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.equalTo("objectId", parent.id); query.equalTo("toChilds", childObjects[2]); @@ -365,32 +365,32 @@ describe('Parse.Relation testing', () => { }); it("query on pointer and relation fields with equal bis", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects).then(() => { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("toChilds"); + const relation = parent.relation("toChilds"); relation.add(childObjects[0]); relation.add(childObjects[1]); relation.add(childObjects[2]); - var parent2 = new ParentObject(); + const parent2 = new ParentObject(); parent2.set("x", 3); parent2.relation("toChilds").add(childObjects[2]); - var parents = []; + const parents = []; parents.push(parent); parents.push(parent2); parents.push(new ParentObject()); return Parse.Object.saveAll(parents).then(() => { - var query = new Parse.Query(ParentObject); + const query = new Parse.Query(ParentObject); query.equalTo("objectId", parent2.id); // childObjects[2] is in 2 relations // before the fix, that woul yield 2 results @@ -405,38 +405,38 @@ describe('Parse.Relation testing', () => { }); it_exclude_dbs(['postgres'])("or queries on pointer and relation fields", (done) => { - var ChildObject = Parse.Object.extend("ChildObject"); - var childObjects = []; - for (var i = 0; i < 10; i++) { + const ChildObject = Parse.Object.extend("ChildObject"); + const childObjects = []; + for (let i = 0; i < 10; i++) { childObjects.push(new ChildObject({x: i})); } Parse.Object.saveAll(childObjects).then(() => { - var ParentObject = Parse.Object.extend("ParentObject"); - var parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - var relation = parent.relation("toChilds"); + const relation = parent.relation("toChilds"); relation.add(childObjects[0]); relation.add(childObjects[1]); relation.add(childObjects[2]); - var parent2 = new ParentObject(); + const parent2 = new ParentObject(); parent2.set("x", 3); parent2.set("toChild", childObjects[2]); - var parents = []; + const parents = []; parents.push(parent); parents.push(parent2); parents.push(new ParentObject()); return Parse.Object.saveAll(parents).then(() => { - var query1 = new Parse.Query(ParentObject); + const query1 = new Parse.Query(ParentObject); query1.containedIn("toChilds", [childObjects[2]]); - var query2 = new Parse.Query(ParentObject); + const query2 = new Parse.Query(ParentObject); query2.equalTo("toChild", childObjects[2]); - var query = Parse.Query.or(query1, query2); + const query = Parse.Query.or(query1, query2); return query.find().then((list) => { - var objectIds = list.map(function(item){ + const objectIds = list.map(function(item){ return item.id; }); expect(objectIds.indexOf(parent.id)).not.toBe(-1); @@ -451,21 +451,21 @@ describe('Parse.Relation testing', () => { it("Get query on relation using un-fetched parent object", (done) => { // Setup data model - var Wheel = Parse.Object.extend('Wheel'); - var Car = Parse.Object.extend('Car'); - var origWheel = new Wheel(); + const Wheel = Parse.Object.extend('Wheel'); + const Car = Parse.Object.extend('Car'); + const origWheel = new Wheel(); origWheel.save().then(function() { - var car = new Car(); - var relation = car.relation('wheels'); + const car = new Car(); + const relation = car.relation('wheels'); relation.add(origWheel); return car.save(); }).then(function(car) { // Test starts here. // Create an un-fetched shell car object - var unfetchedCar = new Car(); + const unfetchedCar = new Car(); unfetchedCar.id = car.id; - var relation = unfetchedCar.relation('wheels'); - var query = relation.query(); + const relation = unfetchedCar.relation('wheels'); + const query = relation.query(); // Parent object is un-fetched, so this will call /1/classes/Car instead // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. @@ -484,28 +484,28 @@ describe('Parse.Relation testing', () => { it("Find query on relation using un-fetched parent object", (done) => { // Setup data model - var Wheel = Parse.Object.extend('Wheel'); - var Car = Parse.Object.extend('Car'); - var origWheel = new Wheel(); + const Wheel = Parse.Object.extend('Wheel'); + const Car = Parse.Object.extend('Car'); + const origWheel = new Wheel(); origWheel.save().then(function() { - var car = new Car(); - var relation = car.relation('wheels'); + const car = new Car(); + const relation = car.relation('wheels'); relation.add(origWheel); return car.save(); }).then(function(car) { // Test starts here. // Create an un-fetched shell car object - var unfetchedCar = new Car(); + const unfetchedCar = new Car(); unfetchedCar.id = car.id; - var relation = unfetchedCar.relation('wheels'); - var query = relation.query(); + const relation = unfetchedCar.relation('wheels'); + const query = relation.query(); // Parent object is un-fetched, so this will call /1/classes/Car instead // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. return query.find(origWheel.id); }).then(function(results) { // Make sure this is Wheel and not Car. - var wheel = results[0]; + const wheel = results[0]; strictEqual(wheel.className, 'Wheel'); strictEqual(wheel.id, origWheel.id); }).then(function() { @@ -518,16 +518,16 @@ describe('Parse.Relation testing', () => { it('Find objects with a related object using equalTo', (done) => { // Setup the objects - var Card = Parse.Object.extend('Card'); - var House = Parse.Object.extend('House'); - var card = new Card(); + const Card = Parse.Object.extend('Card'); + const House = Parse.Object.extend('House'); + const card = new Card(); card.save().then(() => { - var house = new House(); - var relation = house.relation('cards'); + const house = new House(); + const relation = house.relation('cards'); relation.add(card); return house.save(); }).then(() => { - var query = new Parse.Query('House'); + const query = new Parse.Query('House'); query.equalTo('cards', card); return query.find(); }).then((results) => { @@ -609,10 +609,10 @@ describe('Parse.Relation testing', () => { }); it("select query", function(done) { - var RestaurantObject = Parse.Object.extend("Restaurant"); - var PersonObject = Parse.Object.extend("Person"); - var OwnerObject = Parse.Object.extend('Owner'); - var restaurants = [ + const RestaurantObject = Parse.Object.extend("Restaurant"); + const PersonObject = Parse.Object.extend("Person"); + const OwnerObject = Parse.Object.extend('Owner'); + const restaurants = [ new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), ]; @@ -630,9 +630,9 @@ describe('Parse.Relation testing', () => { }).then(() => { const unfetchedOwner = new OwnerObject(); unfetchedOwner.id = owner.id; - var query = unfetchedOwner.relation('restaurants').query(); + const query = unfetchedOwner.relation('restaurants').query(); query.greaterThan("ratings", 4); - var mainQuery = new Parse.Query(PersonObject); + const mainQuery = new Parse.Query(PersonObject); mainQuery.matchesKeyInQuery("hometown", "location", query); mainQuery.find(expectSuccess({ success: function(results) { @@ -650,10 +650,10 @@ describe('Parse.Relation testing', () => { }); it("dontSelect query", function(done) { - var RestaurantObject = Parse.Object.extend("Restaurant"); - var PersonObject = Parse.Object.extend("Person"); - var OwnerObject = Parse.Object.extend('Owner'); - var restaurants = [ + const RestaurantObject = Parse.Object.extend("Restaurant"); + const PersonObject = Parse.Object.extend("Person"); + const OwnerObject = Parse.Object.extend('Owner'); + const restaurants = [ new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), ]; @@ -671,9 +671,9 @@ describe('Parse.Relation testing', () => { }).then(() => { const unfetchedOwner = new OwnerObject(); unfetchedOwner.id = owner.id; - var query = unfetchedOwner.relation('restaurants').query(); + const query = unfetchedOwner.relation('restaurants').query(); query.greaterThan("ratings", 4); - var mainQuery = new Parse.Query(PersonObject); + const mainQuery = new Parse.Query(PersonObject); mainQuery.doesNotMatchKeyInQuery("hometown", "location", query); mainQuery.ascending('name'); mainQuery.find(expectSuccess({ diff --git a/spec/ParseRole.spec.js b/spec/ParseRole.spec.js index 17c30942..b9d31506 100644 --- a/spec/ParseRole.spec.js +++ b/spec/ParseRole.spec.js @@ -2,14 +2,14 @@ // Roles are not accessible without the master key, so they are not intended // for use by clients. We can manually test them using the master key. -var RestQuery = require("../src/RestQuery"); -var Auth = require("../src/Auth").Auth; -var Config = require("../src/Config"); +const RestQuery = require("../src/RestQuery"); +const Auth = require("../src/Auth").Auth; +const Config = require("../src/Config"); describe('Parse Role testing', () => { it('Do a bunch of basic role testing', done => { - var user; - var role; + let user; + let role; createTestUser().then((x) => { user = x; @@ -19,23 +19,23 @@ describe('Parse Role testing', () => { role = new Parse.Object('_Role'); role.set('name', 'Foos'); role.setACL(acl); - var users = role.relation('users'); + const users = role.relation('users'); users.add(user); return role.save({}, { useMasterKey: true }); }).then(() => { - var query = new Parse.Query('_Role'); + const query = new Parse.Query('_Role'); return query.find({ useMasterKey: true }); }).then((x) => { expect(x.length).toEqual(1); - var relation = x[0].relation('users').query(); + const relation = x[0].relation('users').query(); return relation.first({ useMasterKey: true }); }).then((x) => { expect(x.id).toEqual(user.id); // Here we've got a valid role and a user assigned. // Lets create an object only the role can read/write and test // the different scenarios. - var obj = new Parse.Object('TestObject'); - var acl = new Parse.ACL(); + const obj = new Parse.Object('TestObject'); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); acl.setPublicWriteAccess(false); acl.setRoleReadAccess('Foos', true); @@ -43,11 +43,11 @@ describe('Parse Role testing', () => { obj.setACL(acl); return obj.save(); }).then(() => { - var query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); return query.find({ sessionToken: user.getSessionToken() }); }).then((x) => { expect(x.length).toEqual(1); - var objAgain = x[0]; + const objAgain = x[0]; objAgain.set('foo', 'bar'); // This should succeed: return objAgain.save({}, {sessionToken: user.getSessionToken()}); @@ -64,10 +64,10 @@ describe('Parse Role testing', () => { }); - var createRole = function(name, sibling, user) { - var role = new Parse.Role(name, new Parse.ACL()); + const createRole = function(name, sibling, user) { + const role = new Parse.Role(name, new Parse.ACL()); if (user) { - var users = role.relation('users'); + const users = role.relation('users'); users.add(user); } if (sibling) { @@ -77,13 +77,13 @@ describe('Parse Role testing', () => { }; it("should not recursively load the same role multiple times", (done) => { - var rootRole = "RootRole"; - var roleNames = ["FooRole", "BarRole", "BazRole"]; - var allRoles = [rootRole].concat(roleNames); + const rootRole = "RootRole"; + const roleNames = ["FooRole", "BarRole", "BazRole"]; + const allRoles = [rootRole].concat(roleNames); - var roleObjs = {}; - var createAllRoles = function(user) { - var promises = allRoles.map(function(roleName) { + const roleObjs = {}; + const createAllRoles = function(user) { + const promises = allRoles.map(function(roleName) { return createRole(roleName, null, user) .then(function(roleObj) { roleObjs[roleName] = roleObj; @@ -93,16 +93,16 @@ describe('Parse Role testing', () => { return Promise.all(promises); }; - var restExecute = spyOn(RestQuery.prototype, "execute").and.callThrough(); + const restExecute = spyOn(RestQuery.prototype, "execute").and.callThrough(); - var user, + let user, auth, getAllRolesSpy; createTestUser().then((newUser) => { user = newUser; return createAllRoles(user); }).then ((roles) => { - var rootRoleObj = roleObjs[rootRole]; + const rootRoleObj = roleObjs[rootRole]; roles.forEach(function(role, i) { // Add all roles to the RootRole if (role.id !== rootRoleObj.id) { @@ -143,8 +143,8 @@ describe('Parse Role testing', () => { }); it("should recursively load roles", (done) => { - var rolesNames = ["FooRole", "BarRole", "BazRole"]; - var roleIds = {}; + const rolesNames = ["FooRole", "BarRole", "BazRole"]; + const roleIds = {}; createTestUser().then((user) => { // Put the user on the 1st role return createRole(rolesNames[0], null, user).then((aRole) => { @@ -159,7 +159,7 @@ describe('Parse Role testing', () => { return createRole(rolesNames[2], anotherRole, null); }).then((lastRole) => { roleIds[lastRole.get("name")] = lastRole.id; - var auth = new Auth({ config: Config.get("test"), isMaster: true, user: user }); + const auth = new Auth({ config: Config.get("test"), isMaster: true, user: user }); return auth._loadRoles(); }) }).then((roles) => { @@ -175,7 +175,7 @@ describe('Parse Role testing', () => { }); it("_Role object should not save without name.", (done) => { - var role = new Parse.Role(); + const role = new Parse.Role(); role.save(null,{useMasterKey:true}) .then(() => { fail("_Role object should not save without name."); @@ -222,7 +222,7 @@ describe('Parse Role testing', () => { superContentManager.getRoles().add(superModerator); return Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], {useMasterKey: true}); }).then(() => { - var auth = new Auth({ config: Config.get("test"), isMaster: true }); + const auth = new Auth({ config: Config.get("test"), isMaster: true }); // For each role, fetch their sibling, what they inherit // return with result and roleId for later comparison const promises = [admin, moderator, contentManager, superModerator].map((role) => { @@ -264,12 +264,12 @@ describe('Parse Role testing', () => { }); it('can create role and query empty users', (done)=> { - var roleACL = new Parse.ACL(); + const roleACL = new Parse.ACL(); roleACL.setPublicReadAccess(true); - var role = new Parse.Role('subscribers', roleACL); + const role = new Parse.Role('subscribers', roleACL); role.save({}, {useMasterKey : true}) .then(()=>{ - var query = role.relation('users').query(); + const query = role.relation('users').query(); query.find({useMasterKey : true}) .then(()=>{ done(); @@ -284,13 +284,13 @@ describe('Parse Role testing', () => { // Based on various scenarios described in issues #827 and #683, it('should properly handle role permissions on objects', (done) => { - var user, user2, user3; - var role, role2, role3; - var obj, obj2; + let user, user2, user3; + let role, role2, role3; + let obj, obj2; - var prACL = new Parse.ACL(); + const prACL = new Parse.ACL(); prACL.setPublicReadAccess(true); - var adminACL, superACL, customerACL; + let adminACL, superACL, customerACL; createTestUser().then((x) => { user = x; @@ -328,7 +328,7 @@ describe('Parse Role testing', () => { customerACL.setRoleReadAccess("Customer", true); customerACL.setRoleWriteAccess("Customer", true); - var query = new Parse.Query('_Role'); + const query = new Parse.Query('_Role'); return query.find({ useMasterKey: true }); }).then((x) => { expect(x.length).toEqual(3); @@ -366,11 +366,11 @@ describe('Parse Role testing', () => { }); it('should add multiple users to a role and remove users', (done) => { - var user, user2, user3; - var role; - var obj; + let user, user2, user3; + let role; + let obj; - var prACL = new Parse.ACL(); + const prACL = new Parse.ACL(); prACL.setPublicReadAccess(true); prACL.setPublicWriteAccess(true); @@ -383,19 +383,19 @@ describe('Parse Role testing', () => { return user3.save({ username: 'user3', password: 'omgbbq' }); }).then(() => { role = new Parse.Role('sharedRole', prACL); - var users = role.relation('users'); + const users = role.relation('users'); users.add(user); users.add(user2); users.add(user3); return role.save({}, { useMasterKey: true }); }).then(() => { // query for saved role and get 3 users - var query = new Parse.Query('_Role'); + const query = new Parse.Query('_Role'); query.equalTo('name', 'sharedRole'); return query.find({ useMasterKey: true }); }).then((role) => { expect(role.length).toEqual(1); - var users = role[0].relation('users').query(); + const users = role[0].relation('users').query(); return users.find({ useMasterKey: true }); }).then((users) => { expect(users.length).toEqual(3); @@ -409,17 +409,17 @@ describe('Parse Role testing', () => { return obj.save(null, { sessionToken: user.getSessionToken() }); }).then(() => { // query for saved role and get 3 users - var query = new Parse.Query('_Role'); + const query = new Parse.Query('_Role'); query.equalTo('name', 'sharedRole'); return query.find({ useMasterKey: true }); }).then((role) => { expect(role.length).toEqual(1); - var users = role[0].relation('users'); + const users = role[0].relation('users'); users.remove(user); users.remove(user3); return role[0].save({}, { useMasterKey: true }); }).then((role) =>{ - var users = role.relation('users').query(); + const users = role.relation('users').query(); return users.find({ useMasterKey: true }); }).then((users) => { expect(users.length).toEqual(1); @@ -449,20 +449,20 @@ describe('Parse Role testing', () => { }); it('should match when matching in users relation', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user .save({ username: 'admin', password: 'admin' }) .then((user) => { - var aCL = new Parse.ACL(); + const aCL = new Parse.ACL(); aCL.setPublicReadAccess(true); aCL.setPublicWriteAccess(true); - var role = new Parse.Role('admin', aCL); - var users = role.relation('users'); + const role = new Parse.Role('admin', aCL); + const users = role.relation('users'); users.add(user); role .save({}, { useMasterKey: true }) .then(() => { - var query = new Parse.Query(Parse.Role); + const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.equalTo('users', user); query.find().then(function (roles) { @@ -474,24 +474,24 @@ describe('Parse Role testing', () => { }); it('should not match any entry when not matching in users relation', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user .save({ username: 'admin', password: 'admin' }) .then((user) => { - var aCL = new Parse.ACL(); + const aCL = new Parse.ACL(); aCL.setPublicReadAccess(true); aCL.setPublicWriteAccess(true); - var role = new Parse.Role('admin', aCL); - var users = role.relation('users'); + const role = new Parse.Role('admin', aCL); + const users = role.relation('users'); users.add(user); role .save({}, { useMasterKey: true }) .then(() => { - var otherUser = new Parse.User(); + const otherUser = new Parse.User(); otherUser .save({ username: 'otherUser', password: 'otherUser' }) .then((otherUser) => { - var query = new Parse.Query(Parse.Role); + const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.equalTo('users', otherUser); query.find().then(function(roles) { @@ -504,20 +504,20 @@ describe('Parse Role testing', () => { }); it('should not match any entry when searching for null in users relation', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user .save({ username: 'admin', password: 'admin' }) .then((user) => { - var aCL = new Parse.ACL(); + const aCL = new Parse.ACL(); aCL.setPublicReadAccess(true); aCL.setPublicWriteAccess(true); - var role = new Parse.Role('admin', aCL); - var users = role.relation('users'); + const role = new Parse.Role('admin', aCL); + const users = role.relation('users'); users.add(user); role .save({}, { useMasterKey: true }) .then(() => { - var query = new Parse.Query(Parse.Role); + const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.equalTo('users', null); query.find().then(function (roles) { diff --git a/spec/ParseUser.spec.js b/spec/ParseUser.spec.js index af554bf0..f714cf90 100644 --- a/spec/ParseUser.spec.js +++ b/spec/ParseUser.spec.js @@ -7,9 +7,9 @@ "use strict"; -var request = require('request'); -var passwordCrypto = require('../src/password'); -var Config = require('../src/Config'); +const request = require('request'); +const passwordCrypto = require('../src/password'); +const Config = require('../src/Config'); const rp = require('request-promise'); function verifyACL(user) { @@ -37,7 +37,7 @@ describe('Parse.User testing', () => { }); it("user sign up instance method", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.signUp(null, { @@ -232,7 +232,7 @@ describe('Parse.User testing', () => { it('become sends token back', done => { let user = null; - var sessionToken = null; + let sessionToken = null; Parse.User.signUp('Jason', 'Parse', { 'code': 'red' }).then(newUser => { user = newUser; @@ -256,8 +256,8 @@ describe('Parse.User testing', () => { }); it("become", (done) => { - var user = null; - var sessionToken = null; + let user = null; + let sessionToken = null; Parse.Promise.as().then(function() { return Parse.User.signUp("Jason", "Parse", { "code": "red" }); @@ -306,7 +306,7 @@ describe('Parse.User testing', () => { }); it("cannot save non-authed user", (done) => { - var user = new Parse.User(); + let user = new Parse.User(); user.set({ "password": "asdf", "email": "asdf@example.com", @@ -315,7 +315,7 @@ describe('Parse.User testing', () => { user.signUp(null, { success: function(userAgain) { equal(userAgain, user); - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(userNotAuthed) { user = new Parse.User(); @@ -346,14 +346,14 @@ describe('Parse.User testing', () => { }); it("cannot delete non-authed user", (done) => { - var user = new Parse.User(); + let user = new Parse.User(); user.signUp({ "password": "asdf", "email": "asdf@example.com", "username": "zxcv" }, { success: function() { - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(userNotAuthed) { user = new Parse.User(); @@ -375,14 +375,14 @@ describe('Parse.User testing', () => { }); it("cannot saveAll with non-authed user", (done) => { - var user = new Parse.User(); + let user = new Parse.User(); user.signUp({ "password": "asdf", "email": "asdf@example.com", "username": "zxcv" }, { success: function() { - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(userNotAuthed) { user = new Parse.User(); @@ -394,18 +394,18 @@ describe('Parse.User testing', () => { query.get(user.id, { success: function(userNotAuthedNotChanged) { userNotAuthed.set("username", "changed"); - var object = new TestObject(); + const object = new TestObject(); object.save({ user: userNotAuthedNotChanged }, { success: function() { - var item1 = new TestObject(); + const item1 = new TestObject(); item1.save({ number: 0 }, { success: function(item1) { item1.set("number", 1); - var item2 = new TestObject(); + const item2 = new TestObject(); item2.set("number", 2); Parse.Object.saveAll( [item1, item2, userNotAuthed], @@ -425,16 +425,16 @@ describe('Parse.User testing', () => { }); it("current user", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("password", "asdf"); user.set("email", "asdf@example.com"); user.set("username", "zxcv"); user.signUp().then(() => { - var currentUser = Parse.User.current(); + const currentUser = Parse.User.current(); equal(user.id, currentUser.id); ok(user.getSessionToken()); - var currentUserAgain = Parse.User.current(); + const currentUserAgain = Parse.User.current(); // should be the same object equal(currentUser, currentUserAgain); @@ -447,9 +447,9 @@ describe('Parse.User testing', () => { }); it("user.isCurrent", (done) => { - var user1 = new Parse.User(); - var user2 = new Parse.User(); - var user3 = new Parse.User(); + const user1 = new Parse.User(); + const user2 = new Parse.User(); + const user3 = new Parse.User(); user1.set("username", "a"); user2.set("username", "b"); @@ -496,24 +496,24 @@ describe('Parse.User testing', () => { }); it("user associations", (done) => { - var child = new TestObject(); + const child = new TestObject(); child.save(null, { success: function() { - var user = new Parse.User(); + const user = new Parse.User(); user.set("password", "asdf"); user.set("email", "asdf@example.com"); user.set("username", "zxcv"); user.set("child", child); user.signUp(null, { success: function() { - var object = new TestObject(); + const object = new TestObject(); object.set("user", user); object.save(null, { success: function() { - var query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); query.get(object.id, { success: function(objectAgain) { - var userAgain = objectAgain.get("user"); + const userAgain = objectAgain.get("user"); userAgain.fetch({ success: function() { equal(user.id, userAgain.id); @@ -532,13 +532,13 @@ describe('Parse.User testing', () => { }); it("user queries", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("password", "asdf"); user.set("email", "asdf@example.com"); user.set("username", "zxcv"); user.signUp(null, { success: function() { - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(userAgain) { equal(userAgain.id, user.id); @@ -557,7 +557,7 @@ describe('Parse.User testing', () => { }); function signUpAll(list, optionsOrCallback) { - var promise = Parse.Promise.as(); + let promise = Parse.Promise.as(); list.forEach((user) => { promise = promise.then(function() { return user.signUp(); @@ -568,12 +568,12 @@ describe('Parse.User testing', () => { } it("contained in user array queries", (done) => { - var USERS = 4; - var MESSAGES = 5; + const USERS = 4; + const MESSAGES = 5; // Make a list of users. - var userList = range(USERS).map(function(i) { - var user = new Parse.User(); + const userList = range(USERS).map(function(i) { + const user = new Parse.User(); user.set("password", "user_num_" + i); user.set("email", "user_num_" + i + "@example.com"); user.set("username", "xinglblog_num_" + i); @@ -587,8 +587,8 @@ describe('Parse.User testing', () => { done(); return; } - var messageList = range(MESSAGES).map(function(i) { - var message = new TestObject(); + const messageList = range(MESSAGES).map(function(i) { + const message = new TestObject(); message.set("to", users[(i + 1) % USERS]); message.set("from", users[i % USERS]); return message; @@ -598,8 +598,8 @@ describe('Parse.User testing', () => { Parse.Object.saveAll(messageList, function() { // Assemble an "in" list. - var inList = [users[0], users[3], users[3]]; // Intentional dupe - var query = new Parse.Query(TestObject); + const inList = [users[0], users[3], users[3]]; // Intentional dupe + const query = new Parse.Query(TestObject); query.containedIn("from", inList); query.find({ success: function(results) { @@ -613,7 +613,7 @@ describe('Parse.User testing', () => { }); it("saving a user signs them up but doesn't log them in", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.save({ password: "asdf", email: "asdf@example.com", @@ -627,7 +627,7 @@ describe('Parse.User testing', () => { }); it("user updates", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.signUp({ password: "asdf", email: "asdf@example.com", @@ -642,7 +642,7 @@ describe('Parse.User testing', () => { ok(user.attributes["email"]); user.destroy({ success: function() { - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { error: function(model, error) { // The user should no longer exist. @@ -668,17 +668,17 @@ describe('Parse.User testing', () => { }); it("count users", (done) => { - var james = new Parse.User(); + const james = new Parse.User(); james.set("username", "james"); james.set("password", "mypass"); james.signUp(null, { success: function() { - var kevin = new Parse.User(); + const kevin = new Parse.User(); kevin.set("username", "kevin"); kevin.set("password", "mypass"); kevin.signUp(null, { success: function() { - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.count({ success: function(count) { equal(count, 2); @@ -701,14 +701,14 @@ describe('Parse.User testing', () => { it("user modified while saving", (done) => { Parse.Object.disableSingleInstance(); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "password"); user.signUp(null, { success: function(userAgain) { equal(userAgain.get("username"), "bob"); ok(userAgain.dirty("username")); - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(freshUser) { equal(freshUser.id, user.id); @@ -724,7 +724,7 @@ describe('Parse.User testing', () => { it("user modified while saving with unsaved child", (done) => { Parse.Object.disableSingleInstance(); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "alice"); user.set("password", "password"); user.set("child", new TestObject()); @@ -733,7 +733,7 @@ describe('Parse.User testing', () => { equal(userAgain.get("username"), "bob"); // Should be dirty, but it depends on batch support. // ok(userAgain.dirty("username")); - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); query.get(user.id, { success: function(freshUser) { equal(freshUser.id, user.id); @@ -760,7 +760,7 @@ describe('Parse.User testing', () => { Parse.User._currentUser = null; Parse.User._currentUserMatchesDisk = false; - var aliceAgain = Parse.User.current(); + const aliceAgain = Parse.User.current(); equal(aliceAgain.get("username"), "alice"); equal(aliceAgain.id, alice.id, "currentUser should have objectId"); ok(aliceAgain.getSessionToken(), @@ -774,7 +774,7 @@ describe('Parse.User testing', () => { it("user loaded from localStorage from login", (done) => { - var id; + let id; Parse.User.signUp("alice", "password").then((alice) => { id = alice.id; return Parse.User.logOut(); @@ -785,7 +785,7 @@ describe('Parse.User testing', () => { delete Parse.User._currentUser; delete Parse.User._currentUserMatchesDisk; - var userFromDisk = Parse.User.current(); + const userFromDisk = Parse.User.current(); equal(userFromDisk.get("password"), undefined, "password should not be in attributes"); equal(userFromDisk.id, id, "id should be set"); @@ -796,7 +796,7 @@ describe('Parse.User testing', () => { }); it("saving user after browser refresh", (done) => { - var id; + let id; Parse.User.signUp("alice", "password", null).then(function(alice) { id = alice.id; @@ -811,7 +811,7 @@ describe('Parse.User testing', () => { return Parse.User.current().save({some_field: 1}); }).then(function() { // Check the user in memory just after save operation - var userInMemory = Parse.User.current(); + const userInMemory = Parse.User.current(); equal(userInMemory.getUsername(), "alice", "saving user should not remove existing fields"); @@ -840,7 +840,7 @@ describe('Parse.User testing', () => { // Force the current user to read from localStorage, and check again delete Parse.User._currentUser; delete Parse.User._currentUserMatchesDisk; - var userFromDisk = Parse.User.current(); + const userFromDisk = Parse.User.current(); equal(userFromDisk.getUsername(), "alice", "userFromDisk should have previously existing fields"); @@ -874,7 +874,7 @@ describe('Parse.User testing', () => { }); it("user with missing username", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("password", "foo"); user.signUp(null, { success: function() { @@ -889,7 +889,7 @@ describe('Parse.User testing', () => { }); it("user with missing password", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "foo"); user.signUp(null, { success: function() { @@ -905,8 +905,8 @@ describe('Parse.User testing', () => { it("user stupid subclassing", (done) => { - var SuperUser = Parse.Object.extend("User"); - var user = new SuperUser(); + const SuperUser = Parse.Object.extend("User"); + const user = new SuperUser(); user.set("username", "bob"); user.set("password", "welcome"); ok(user instanceof Parse.User, "Subclassing User should have worked"); @@ -923,7 +923,7 @@ describe('Parse.User testing', () => { it("user signup class method uses subclassing", (done) => { - var SuperUser = Parse.User.extend({ + const SuperUser = Parse.User.extend({ secret: function() { return 1337; } @@ -957,7 +957,7 @@ describe('Parse.User testing', () => { delete Parse.User._currentUser; delete Parse.User._currentUserMatchesDisk; - var userFromDisk = Parse.User.current(); + const userFromDisk = Parse.User.current(); equal(userFromDisk.get("secret"), 1337); ok(userFromDisk.isSuper(), "The subclass should have been used"); done(); @@ -982,14 +982,14 @@ describe('Parse.User testing', () => { ok(!user.dirty("style"), "The user just signed up."); Parse.User._currentUser = null; Parse.User._currentUserMatchesDisk = false; - var userAgain = Parse.User.current(); + const userAgain = Parse.User.current(); ok(!userAgain.dirty("style"), "The user was just read from disk."); done(); } })); }); - var getMockFacebookProviderWithIdToken = function(id, token) { + const getMockFacebookProviderWithIdToken = function(id, token) { return { authData: { id: id, @@ -1035,11 +1035,11 @@ describe('Parse.User testing', () => { // Note that this mocks out client-side Facebook action rather than // server-side. - var getMockFacebookProvider = function() { + const getMockFacebookProvider = function() { return getMockFacebookProviderWithIdToken('8675309', 'jenny'); }; - var getMockMyOauthProvider = function() { + const getMockMyOauthProvider = function() { return { authData: { id: "12345", @@ -1090,7 +1090,7 @@ describe('Parse.User testing', () => { }); it("log in with provider", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1119,7 +1119,7 @@ describe('Parse.User testing', () => { res.success(); }); - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1142,9 +1142,9 @@ describe('Parse.User testing', () => { }); it("log in with provider and update token", (done) => { - var provider = getMockFacebookProvider(); - var secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); - var errorHandler = function() { + const provider = getMockFacebookProvider(); + const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); + const errorHandler = function() { fail('should not fail'); done(); } @@ -1243,7 +1243,7 @@ describe('Parse.User testing', () => { }); it("log in with provider twice", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1289,7 +1289,7 @@ describe('Parse.User testing', () => { }); it("log in with provider failed", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); provider.shouldError = true; Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { @@ -1304,7 +1304,7 @@ describe('Parse.User testing', () => { }); it("log in with provider cancelled", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); provider.shouldCancel = true; Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { @@ -1319,7 +1319,7 @@ describe('Parse.User testing', () => { }); it("login with provider should not call beforeSave trigger", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function() { @@ -1343,9 +1343,9 @@ describe('Parse.User testing', () => { }); it("link with provider", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "testLinkWithProvider"); user.set("password", "mypass"); user.signUp(null, { @@ -1376,9 +1376,9 @@ describe('Parse.User testing', () => { // What this means is, only one Parse User can be linked to a // particular Facebook account. it("link with provider for already linked user", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "testLinkWithProviderToAlreadyLinkedUser"); user.set("password", "mypass"); user.signUp(null, { @@ -1391,7 +1391,7 @@ describe('Parse.User testing', () => { strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked("facebook"), "User should be linked."); - var user2 = new Parse.User(); + const user2 = new Parse.User(); user2.set("username", "testLinkWithProviderToAlreadyLinkedUser2"); user2.set("password", "mypass"); user2.signUp(null, { @@ -1428,10 +1428,10 @@ describe('Parse.User testing', () => { }); it("link with provider failed", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); provider.shouldError = true; Parse.User._registerAuthenticationProvider(provider); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "testLinkWithProvider"); user.set("password", "mypass"); user.signUp(null, { @@ -1457,10 +1457,10 @@ describe('Parse.User testing', () => { }); it("link with provider cancelled", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); provider.shouldCancel = true; Parse.User._registerAuthenticationProvider(provider); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "testLinkWithProvider"); user.set("password", "mypass"); user.signUp(null, { @@ -1486,7 +1486,7 @@ describe('Parse.User testing', () => { }); it("unlink with provider", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1522,7 +1522,7 @@ describe('Parse.User testing', () => { }); it("unlink and link", (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1574,8 +1574,8 @@ describe('Parse.User testing', () => { }); it("link multiple providers", (done) => { - var provider = getMockFacebookProvider(); - var mockProvider = getMockMyOauthProvider(); + const provider = getMockFacebookProvider(); + const mockProvider = getMockMyOauthProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1610,15 +1610,15 @@ describe('Parse.User testing', () => { }); it("link multiple providers and updates token", (done) => { - var provider = getMockFacebookProvider(); - var secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); + const provider = getMockFacebookProvider(); + const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); - var errorHandler = function(model, error) { + const errorHandler = function(model, error) { jfail(error); fail('Should not fail'); done(); } - var mockProvider = getMockMyOauthProvider(); + const mockProvider = getMockMyOauthProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1651,8 +1651,8 @@ describe('Parse.User testing', () => { }); it("link multiple providers and update token", (done) => { - var provider = getMockFacebookProvider(); - var mockProvider = getMockMyOauthProvider(); + const provider = getMockFacebookProvider(); + const mockProvider = getMockMyOauthProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1697,7 +1697,7 @@ describe('Parse.User testing', () => { }); it('should fail linking with existing', (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function() { @@ -1723,7 +1723,7 @@ describe('Parse.User testing', () => { }); it('should fail linking with existing', (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { @@ -1834,7 +1834,7 @@ describe('Parse.User testing', () => { }); it('should properly error when password is missing', (done) => { - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(user) { @@ -1882,7 +1882,7 @@ describe('Parse.User testing', () => { response.success(); }); - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function() { @@ -1907,7 +1907,7 @@ describe('Parse.User testing', () => { }); it("authenticated check", (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "darkhelmet"); user.set("password", "onetwothreefour"); ok(!user.authenticated()); @@ -1973,7 +1973,7 @@ describe('Parse.User testing', () => { }); it("async methods", (done) => { - var data = { foo: "bar" }; + const data = { foo: "bar" }; Parse.User.signUp("finn", "human", data).then(function(user) { equal(Parse.User.current(), user); @@ -1986,7 +1986,7 @@ describe('Parse.User testing', () => { equal(user.get("foo"), "bar"); return Parse.User.logOut(); }).then(function() { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "jake"); user.set("password", "dog"); user.set("foo", "baz"); @@ -2001,7 +2001,7 @@ describe('Parse.User testing', () => { }).then(function(user) { equal(user, Parse.User.current()); equal(user.get("foo"), "baz"); - var userAgain = new Parse.User(); + const userAgain = new Parse.User(); userAgain.id = user.id; return userAgain.fetch(); }).then(function(userAgain) { @@ -2015,7 +2015,7 @@ describe('Parse.User testing', () => { .then(function() { return Parse.User.logOut(); }).then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "jake"); user.set("password", "dog"); user.set("foo", "baz"); @@ -2024,15 +2024,14 @@ describe('Parse.User testing', () => { }).then(function() { return Parse.User.logOut(); }).then(() => { - var query = new Parse.Query(Parse.User); - return query.find(); - + const query = new Parse.Query(Parse.User); + return query.find({ sessionToken: null }); }).then(function(users) { equal(users.length, 2); - for (var user of users) { + users.forEach((user) => { + expect(user.getSessionToken()).toBeUndefined(); ok(!user.getSessionToken(), "user should not have a session token."); - } - + }); done(); }, function(error) { ok(false, error); @@ -2049,9 +2048,9 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/users', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.results.length).toEqual(1); - var user = b.results[0]; + const user = b.results[0]; expect(Object.keys(user).length).toEqual(6); done(); }); @@ -2059,10 +2058,10 @@ describe('Parse.User testing', () => { }); it('retrieve user data from fetch, make sure the session token hasn\'t changed', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); - var currentSessionToken = ""; + let currentSessionToken = ""; Parse.Promise.as().then(function() { return user.signUp(); }).then(function(){ @@ -2078,7 +2077,7 @@ describe('Parse.User testing', () => { }); it('user save should fail with invalid email', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'teste'); user.set('password', 'test'); user.set('email', 'invalid'); @@ -2092,12 +2091,12 @@ describe('Parse.User testing', () => { }); it('user signup should error if email taken', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'test1'); user.set('password', 'test'); user.set('email', 'test@test.com'); user.signUp().then(() => { - var user2 = new Parse.User(); + const user2 = new Parse.User(); user2.set('username', 'test2'); user2.set('password', 'test'); user2.set('email', 'test@test.com'); @@ -2111,12 +2110,12 @@ describe('Parse.User testing', () => { }); it('user cannot update email to existing user', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'test1'); user.set('password', 'test'); user.set('email', 'test@test.com'); user.signUp().then(() => { - var user2 = new Parse.User(); + const user2 = new Parse.User(); user2.set('username', 'test2'); user2.set('password', 'test'); return user2.signUp(); @@ -2132,7 +2131,7 @@ describe('Parse.User testing', () => { }); it('unset user email', (done) => { - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'test'); user.set('password', 'test'); user.set('email', 'test@test.com'); @@ -2160,7 +2159,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b.sessionToken).toEqual('string'); expect(typeof b.createdWith).toEqual('object'); expect(b.createdWith.action).toEqual('create'); @@ -2184,7 +2183,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions/me', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b.sessionToken).toEqual('string'); expect(typeof b.createdWith).toEqual('object'); expect(b.createdWith.action).toEqual('signup'); @@ -2212,7 +2211,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions/me', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b.sessionToken).toEqual('string'); expect(typeof b.createdWith).toEqual('object'); expect(b.createdWith.action).toEqual('login'); @@ -2236,7 +2235,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions/me', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.put({ headers: { 'X-Parse-Application-Id': 'test', @@ -2267,7 +2266,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions/me', }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); request.put({ headers: { 'X-Parse-Application-Id': 'test', @@ -2278,7 +2277,7 @@ describe('Parse.User testing', () => { body: JSON.stringify({ foo: 'bar' }) }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toBe('invalid session token'); request.put({ headers: { @@ -2289,7 +2288,7 @@ describe('Parse.User testing', () => { body: JSON.stringify({ foo: 'bar' }) }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.error).toBe('Session token required.'); done(); }); @@ -2314,7 +2313,7 @@ describe('Parse.User testing', () => { }, (error, response, body) => { expect(error).toBe(null); try { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.results.length).toEqual(1); expect(typeof b.results[0].user).toEqual('object'); expect(b.results[0].user.objectId).toEqual(user.id); @@ -2341,9 +2340,9 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions' }, (error, response, body) => { expect(error).toBe(null); - var objId; + let objId; try { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.results.length).toEqual(1); objId = b.results[0].objectId; } catch(e) { @@ -2369,7 +2368,7 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions' }, (error, response, body) => { expect(error).toBe(null); - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.code).toEqual(209); expect(b.error).toBe('invalid session token'); done(); @@ -2394,9 +2393,9 @@ describe('Parse.User testing', () => { url: 'http://localhost:8378/1/sessions' }, (error, response, body) => { expect(error).toBe(null); - var objId; + let objId; try { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.results.length).toEqual(1); objId = b.results[0].objectId; } catch(e) { @@ -2411,7 +2410,7 @@ describe('Parse.User testing', () => { }, url: 'http://localhost:8378/1/sessions/' + objId }, (error,response,body) => { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.code).toEqual(209); expect(b.error).toBe('invalid session token'); done(); @@ -2421,7 +2420,7 @@ describe('Parse.User testing', () => { }); it('password format matches hosted parse', (done) => { - var hashed = '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie'; + const hashed = '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie'; passwordCrypto.compare('test', hashed) .then((pass) => { expect(pass).toBe(true); @@ -2433,7 +2432,7 @@ describe('Parse.User testing', () => { }); it('changing password clears sessions', (done) => { - var sessionToken = null; + let sessionToken = null; Parse.Promise.as().then(function() { return Parse.User.signUp("fosco", "parse"); @@ -2456,7 +2455,7 @@ describe('Parse.User testing', () => { }); it('test parse user become', (done) => { - var sessionToken = null; + let sessionToken = null; Parse.Promise.as().then(function() { return Parse.User.signUp("flessard", "folo",{'foo':1}); }).then(function(newUser) { @@ -2477,8 +2476,8 @@ describe('Parse.User testing', () => { }); it('ensure logout works', (done) => { - var user = null; - var sessionToken = null; + let user = null; + let sessionToken = null; Parse.Promise.as().then(function() { return Parse.User.signUp('log', 'out'); @@ -2687,7 +2686,7 @@ describe('Parse.User testing', () => { let emailCalled = false; let emailOptions; - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: (options) => { emailOptions = options; emailCalled = true; @@ -2739,7 +2738,7 @@ describe('Parse.User testing', () => { it('should not send email when email is not a string', (done) => { let emailCalled = false; let emailOptions; - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: (options) => { emailOptions = options; emailCalled = true; @@ -2753,7 +2752,7 @@ describe('Parse.User testing', () => { emailAdapter: emailAdapter, publicServerURL: 'http://localhost:8378/1', }); - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'asdf@jkl.com'); user.set('password', 'zxcv'); user.set('email', 'asdf@jkl.com'); @@ -2785,7 +2784,7 @@ describe('Parse.User testing', () => { it('should aftersave with full object', (done) => { - var hit = 0; + let hit = 0; Parse.Cloud.afterSave('_User', (req, res) => { hit++; expect(req.object.get('username')).toEqual('User'); @@ -2838,8 +2837,8 @@ describe('Parse.User testing', () => { }, })) .then(body => { - var id = body.results[0].objectId; - var expiresAt = new Date((new Date()).setYear(2015)); + const id = body.results[0].objectId; + const expiresAt = new Date((new Date()).setYear(2015)); token = body.results[0].sessionToken; return rp({ method: 'PUT', @@ -2892,9 +2891,9 @@ describe('Parse.User testing', () => { it('should not overwrite username when unlinking facebook user (regression test for #1532)', done => { Parse.Object.disableSingleInstance(); - var provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "testLinkWithProvider"); user.set("password", "mypass"); user.signUp() @@ -3007,7 +3006,7 @@ describe('Parse.User testing', () => { }); it('should not allow updates to emailVerified', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => {}, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -3040,7 +3039,7 @@ describe('Parse.User testing', () => { it('should not retrieve hidden fields on GET users/me (#3432)', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => {}, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -3081,7 +3080,7 @@ describe('Parse.User testing', () => { it('should not retrieve hidden fields on GET users/id (#3432)', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => {}, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -3121,7 +3120,7 @@ describe('Parse.User testing', () => { it('should not retrieve hidden fields on login (#3432)', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => {}, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -3159,7 +3158,7 @@ describe('Parse.User testing', () => { }); it('should not allow updates to hidden fields', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => {}, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -3327,7 +3326,7 @@ describe('Parse.User testing', () => { json: { email: "yo@lo.com", password: 'yolopass2'} } return rp.get(options); - }).then(done.fail).catch(done); + }).then(done.fail).catch(() => done()); }); it('can login with email through query string', (done) => { @@ -3515,12 +3514,12 @@ describe('Parse.User testing', () => { password: 'yolo', email: 'yo@lo.com' }).then(() => { + const token = user.getSessionToken(); const promises = []; while(promises.length != 5) { - Parse.User.logIn('yolo', 'yolo') promises.push(Parse.User.logIn('yolo', 'yolo').then((res) => { // ensure a new session token is generated at each login - expect(res.getSessionToken()).not.toBe(user.getSessionToken()); + expect(res.getSessionToken()).not.toBe(token); })); } return Promise.all(promises); diff --git a/spec/ParseWebSocket.spec.js b/spec/ParseWebSocket.spec.js index 11a7ae21..bd61807a 100644 --- a/spec/ParseWebSocket.spec.js +++ b/spec/ParseWebSocket.spec.js @@ -1,41 +1,41 @@ -var ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; +const ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; describe('ParseWebSocket', function() { it('can be initialized', function() { - var ws = {}; - var parseWebSocket = new ParseWebSocket(ws); + const ws = {}; + const parseWebSocket = new ParseWebSocket(ws); expect(parseWebSocket.ws).toBe(ws); }); it('can handle events defined in typeMap', function() { - var ws = { + const ws = { on: jasmine.createSpy('on') }; - var callback = {}; - var parseWebSocket = new ParseWebSocket(ws); + const callback = {}; + const parseWebSocket = new ParseWebSocket(ws); parseWebSocket.on('disconnect', callback); expect(parseWebSocket.ws.on).toHaveBeenCalledWith('close', callback); }); it('can handle events which are not defined in typeMap', function() { - var ws = { + const ws = { on: jasmine.createSpy('on') }; - var callback = {}; - var parseWebSocket = new ParseWebSocket(ws); + const callback = {}; + const parseWebSocket = new ParseWebSocket(ws); parseWebSocket.on('open', callback); expect(parseWebSocket.ws.on).toHaveBeenCalledWith('open', callback); }); it('can send a message', function() { - var ws = { + const ws = { send: jasmine.createSpy('send') }; - var parseWebSocket = new ParseWebSocket(ws); + const parseWebSocket = new ParseWebSocket(ws); parseWebSocket.send('message') expect(parseWebSocket.ws.send).toHaveBeenCalledWith('message'); diff --git a/spec/ParseWebSocketServer.spec.js b/spec/ParseWebSocketServer.spec.js index 7dc70fdb..a16f6a01 100644 --- a/spec/ParseWebSocketServer.spec.js +++ b/spec/ParseWebSocketServer.spec.js @@ -1,11 +1,11 @@ -var ParseWebSocketServer = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocketServer; +const ParseWebSocketServer = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocketServer; describe('ParseWebSocketServer', function() { beforeEach(function(done) { // Mock ws server - var EventEmitter = require('events'); - var mockServer = function() { + const EventEmitter = require('events'); + const mockServer = function() { return new EventEmitter(); }; jasmine.mockLibrary('ws', 'Server', mockServer); @@ -13,11 +13,11 @@ describe('ParseWebSocketServer', function() { }); it('can handle connect event when ws is open', function(done) { - var onConnectCallback = jasmine.createSpy('onConnectCallback'); - var http = require('http'); - var server = http.createServer(); - var parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, 5).server; - var ws = { + const onConnectCallback = jasmine.createSpy('onConnectCallback'); + const http = require('http'); + const server = http.createServer(); + const parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, 5).server; + const ws = { readyState: 0, OPEN: 0, ping: jasmine.createSpy('ping') diff --git a/spec/PointerPermissions.spec.js b/spec/PointerPermissions.spec.js index 94562073..32830059 100644 --- a/spec/PointerPermissions.spec.js +++ b/spec/PointerPermissions.spec.js @@ -1,5 +1,5 @@ 'use strict'; -var Config = require('../src/Config'); +const Config = require('../src/Config'); describe('Pointer Permissions', () => { diff --git a/spec/PostgresConfigParser.spec.js b/spec/PostgresConfigParser.spec.js index 0cb84cf4..0d41f320 100644 --- a/spec/PostgresConfigParser.spec.js +++ b/spec/PostgresConfigParser.spec.js @@ -43,7 +43,7 @@ dbOptionsTest[`${baseURI}?ssl=&binary=aa`] = { describe('PostgresConfigParser.getDatabaseOptionsFromURI', () => { it('creates a db options map from a query string', () => { - for (const key in dbOptionsTest) { + for (const key in dbOptionsTest) { const result = parser.getDatabaseOptionsFromURI(key); const testObj = dbOptionsTest[key]; diff --git a/spec/PostgresInitOptions.spec.js b/spec/PostgresInitOptions.spec.js index f191adb4..1297963a 100644 --- a/spec/PostgresInitOptions.spec.js +++ b/spec/PostgresInitOptions.spec.js @@ -38,7 +38,7 @@ function createParseServer(options) { promise .then(() => { expect(Parse.applicationId).toEqual("test"); - var app = express(); + const app = express(); app.use('/parse', parseServer.app); const server = app.listen(12666); @@ -66,7 +66,7 @@ describe_only_db('postgres')('Postgres database init options', () => { createParseServer({ databaseAdapter: adapter }).then((newServer) => { server = newServer; - var score = new GameScore({ "score": 1337, "playerName": "Sean Plott", "cheatMode": false }); + const score = new GameScore({ "score": 1337, "playerName": "Sean Plott", "cheatMode": false }); return score.save(); }).then(done, done.fail); }); @@ -77,6 +77,6 @@ describe_only_db('postgres')('Postgres database init options', () => { databaseOptions: databaseOptions2 }) - createParseServer({ databaseAdapter: adapter }).then(done.fail, done); + createParseServer({ databaseAdapter: adapter }).then(done.fail, () => done()); }); }); diff --git a/spec/PostgresStorageAdapter.spec.js b/spec/PostgresStorageAdapter.spec.js index df4c5478..1ba24f65 100644 --- a/spec/PostgresStorageAdapter.spec.js +++ b/spec/PostgresStorageAdapter.spec.js @@ -5,27 +5,17 @@ const getColumns = (client, className) => { return client.map('SELECT column_name FROM information_schema.columns WHERE table_name = $', { className }, a => a.column_name); }; +const dropTable = (client, className) => { + return client.none('DROP TABLE IF EXISTS $', { className }); +} + describe_only_db('postgres')('PostgresStorageAdapter', () => { - beforeEach(done => { - const adapter = new PostgresStorageAdapter({ uri: databaseURI }) - .deleteAllClasses() - .then(() => { - adapter.handleShutdown(); - }, fail) - .catch(done); - }); - - it('handleShutdown, close connection', (done) => { - const adapter = new PostgresStorageAdapter({ uri: databaseURI }); - - expect(adapter._client.$pool.ending).toEqual(false); - adapter.handleShutdown(); - expect(adapter._client.$pool.ending).toEqual(true); - done(); + const adapter = new PostgresStorageAdapter({ uri: databaseURI }) + beforeEach(() => { + return adapter.deleteAllClasses(); }); it('schemaUpgrade, upgrade the database schema when schema changes', done => { - const adapter = new PostgresStorageAdapter({ uri: databaseURI }); const client = adapter._client; const className = '_PushStatus'; const schema = { @@ -59,7 +49,6 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { }); it('schemaUpgrade, maintain correct schema', done => { - const adapter = new PostgresStorageAdapter({ uri: databaseURI }); const client = adapter._client; const className = 'Table'; const schema = { @@ -91,24 +80,21 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { }); it('Create a table without columns and upgrade with columns', done => { - const adapter = new PostgresStorageAdapter({ uri: databaseURI }); const client = adapter._client; const className = 'EmptyTable'; - let schema = {}; - - adapter.createTable(className, schema) + dropTable(client, className).then(() => adapter.createTable(className, {})) .then(() => getColumns(client, className)) .then(columns => { expect(columns.length).toBe(0); - schema = { + const newSchema = { fields: { "columnA": { type: 'String' }, "columnB": { type: 'String' } }, }; - return adapter.schemaUpgrade(className, schema); + return adapter.schemaUpgrade(className, newSchema); }) .then(() => getColumns(client, className)) .then(columns => { @@ -117,6 +103,15 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { expect(columns).toContain('columnB'); done(); }) - .catch(error => done.fail(error)); - }) + .catch(done); + }); +}); + +describe_only_db('postgres')('PostgresStorageAdapter shutdown', () => { + it('handleShutdown, close connection', () => { + const adapter = new PostgresStorageAdapter({ uri: databaseURI }); + expect(adapter._client.$pool.ending).toEqual(false); + adapter.handleShutdown(); + expect(adapter._client.$pool.ending).toEqual(true); + }); }); diff --git a/spec/PromiseRouter.spec.js b/spec/PromiseRouter.spec.js index 0ee92c82..d0ce63b0 100644 --- a/spec/PromiseRouter.spec.js +++ b/spec/PromiseRouter.spec.js @@ -1,8 +1,8 @@ -var PromiseRouter = require("../src/PromiseRouter").default; +const PromiseRouter = require("../src/PromiseRouter").default; describe("PromiseRouter", () => { it("should properly handle rejects", (done) => { - var router = new PromiseRouter(); + const router = new PromiseRouter(); router.route("GET", "/dummy", ()=> { return Promise.reject({ error: "an error", diff --git a/spec/PublicAPI.spec.js b/spec/PublicAPI.spec.js index c28914e3..0dadf608 100644 --- a/spec/PublicAPI.spec.js +++ b/spec/PublicAPI.spec.js @@ -1,5 +1,5 @@ -var request = require('request'); +const request = require('request'); describe("public API", () => { it("should get invalid_link.html", (done) => { diff --git a/spec/PurchaseValidation.spec.js b/spec/PurchaseValidation.spec.js index 01987c68..25fdb73a 100644 --- a/spec/PurchaseValidation.spec.js +++ b/spec/PurchaseValidation.spec.js @@ -1,11 +1,11 @@ -var request = require("request"); +const request = require("request"); function createProduct() { const file = new Parse.File("name", { base64: new Buffer("download_file", "utf-8").toString("base64") }, "text"); return file.save().then(function(){ - var product = new Parse.Object("_Product"); + const product = new Parse.Object("_Product"); product.set({ download: file, icon: file, @@ -160,7 +160,7 @@ describe("test validate_receipt endpoint", () => { }); it("should not create a _Product", (done) => { - var product = new Parse.Object("_Product"); + const product = new Parse.Object("_Product"); product.save().then(function(){ fail("Should not be able to save"); done(); @@ -171,7 +171,7 @@ describe("test validate_receipt endpoint", () => { }); it("should be able to update a _Product", (done) => { - var query = new Parse.Query("_Product"); + const query = new Parse.Query("_Product"); query.first().then(function(product) { if (!product) { return Promise.reject(new Error('Product should be found')); @@ -189,7 +189,7 @@ describe("test validate_receipt endpoint", () => { }); it("should not be able to remove a require key in a _Product", (done) => { - var query = new Parse.Query("_Product"); + const query = new Parse.Query("_Product"); query.first().then(function(product){ if (!product) { return Promise.reject(new Error('Product should be found')); diff --git a/spec/PushController.spec.js b/spec/PushController.spec.js index d8510371..694df33b 100644 --- a/spec/PushController.spec.js +++ b/spec/PushController.spec.js @@ -1,8 +1,8 @@ "use strict"; -var PushController = require('../src/Controllers/PushController').PushController; -var StatusHandler = require('../src/StatusHandler'); -var Config = require('../src/Config'); -var validatePushType = require('../src/Push/utils').validatePushType; +const PushController = require('../src/Controllers/PushController').PushController; +const StatusHandler = require('../src/StatusHandler'); +const Config = require('../src/Config'); +const validatePushType = require('../src/Push/utils').validatePushType; const successfulTransmissions = function(body, installations) { @@ -31,9 +31,9 @@ const successfulIOS = function(body, installations) { describe('PushController', () => { it('can validate device type when no device type is set', (done) => { // Make query condition - var where = { + const where = { }; - var validPushTypes = ['ios', 'android']; + const validPushTypes = ['ios', 'android']; expect(function(){ validatePushType(where, validPushTypes); @@ -43,10 +43,10 @@ describe('PushController', () => { it('can validate device type when single valid device type is set', (done) => { // Make query condition - var where = { + const where = { 'deviceType': 'ios' }; - var validPushTypes = ['ios', 'android']; + const validPushTypes = ['ios', 'android']; expect(function(){ validatePushType(where, validPushTypes); @@ -56,12 +56,12 @@ describe('PushController', () => { it('can validate device type when multiple valid device types are set', (done) => { // Make query condition - var where = { + const where = { 'deviceType': { '$in': ['android', 'ios'] } }; - var validPushTypes = ['ios', 'android']; + const validPushTypes = ['ios', 'android']; expect(function(){ validatePushType(where, validPushTypes); @@ -71,10 +71,10 @@ describe('PushController', () => { it('can throw on validateDeviceType when single invalid device type is set', (done) => { // Make query condition - var where = { + const where = { 'deviceType': 'osx' }; - var validPushTypes = ['ios', 'android']; + const validPushTypes = ['ios', 'android']; expect(function(){ validatePushType(where, validPushTypes); @@ -84,10 +84,10 @@ describe('PushController', () => { it('can throw on validateDeviceType when single invalid device type is set', (done) => { // Make query condition - var where = { + const where = { 'deviceType': 'osx' }; - var validPushTypes = ['ios', 'android']; + const validPushTypes = ['ios', 'android']; expect(function(){ validatePushType(where, validPushTypes); @@ -97,31 +97,31 @@ describe('PushController', () => { it('can get expiration time in string format', (done) => { // Make mock request - var timeStr = '2015-03-19T22:05:08Z'; - var body = { + const timeStr = '2015-03-19T22:05:08Z'; + const body = { 'expiration_time': timeStr } - var time = PushController.getExpirationTime(body); + const time = PushController.getExpirationTime(body); expect(time).toEqual(new Date(timeStr).valueOf()); done(); }); it('can get expiration time in number format', (done) => { // Make mock request - var timeNumber = 1426802708; - var body = { + const timeNumber = 1426802708; + const body = { 'expiration_time': timeNumber } - var time = PushController.getExpirationTime(body); + const time = PushController.getExpirationTime(body); expect(time).toEqual(timeNumber * 1000); done(); }); it('can throw on getExpirationTime in invalid format', (done) => { // Make mock request - var body = { + const body = { 'expiration_time': 'abcd' } @@ -133,31 +133,31 @@ describe('PushController', () => { it('can get push time in string format', (done) => { // Make mock request - var timeStr = '2015-03-19T22:05:08Z'; - var body = { + const timeStr = '2015-03-19T22:05:08Z'; + const body = { 'push_time': timeStr } - var { date } = PushController.getPushTime(body); + const { date } = PushController.getPushTime(body); expect(date).toEqual(new Date(timeStr)); done(); }); it('can get push time in number format', (done) => { // Make mock request - var timeNumber = 1426802708; - var body = { + const timeNumber = 1426802708; + const body = { 'push_time': timeNumber } - var { date } = PushController.getPushTime(body); + const { date } = PushController.getPushTime(body); expect(date.valueOf()).toEqual(timeNumber * 1000); done(); }); it('can throw on getPushTime in invalid format', (done) => { // Make mock request - var body = { + const body = { 'push_time': 'abcd' } @@ -168,9 +168,9 @@ describe('PushController', () => { }); it('properly increment badges', (done) => { - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { - var badge = body.data.badge; + const badge = body.data.badge; installations.forEach((installation) => { expect(installation.badge).toEqual(badge); expect(installation.originalBadge + 1).toEqual(installation.badge); @@ -181,11 +181,11 @@ describe('PushController', () => { return ["ios", "android"]; } } - var payload = {data:{ + const payload = {data:{ alert: "Hello World!", badge: "Increment", }} - var installations = []; + const installations = []; while(installations.length != 10) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -205,12 +205,12 @@ describe('PushController', () => { installation.set("deviceType", "android"); installations.push(installation); } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { @@ -234,7 +234,7 @@ describe('PushController', () => { return query.find({ useMasterKey: true }) }).then((results) => { expect(results.length).toBe(15); - for (var i = 0; i < 15; i++) { + for (let i = 0; i < 15; i++) { const installation = results[i]; expect(installation.get('badge')).toBe(parseInt(installation.get('originalBadge')) + 1); } @@ -247,9 +247,9 @@ describe('PushController', () => { it('properly set badges to 1', (done) => { - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { - var badge = body.data.badge; + const badge = body.data.badge; installations.forEach((installation) => { expect(installation.badge).toEqual(badge); expect(1).toEqual(installation.badge); @@ -261,13 +261,13 @@ describe('PushController', () => { } } - var payload = {data: { + const payload = {data: { alert: "Hello World!", badge: 1, }} - var installations = []; + const installations = []; while(installations.length != 10) { - var installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); installation.set("deviceToken","device_token_" + installations.length) installation.set("badge", installations.length); @@ -276,12 +276,12 @@ describe('PushController', () => { installations.push(installation); } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { @@ -305,7 +305,7 @@ describe('PushController', () => { return query.find({ useMasterKey: true }) }).then((results) => { expect(results.length).toBe(10); - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { const installation = results[i]; expect(installation.get('badge')).toBe(1); } @@ -318,15 +318,15 @@ describe('PushController', () => { it('properly set badges to 1 with complex query #2903 #3022', (done) => { - var payload = { + const payload = { data: { alert: "Hello World!", badge: 1, } } - var installations = []; + const installations = []; while(installations.length != 10) { - var installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); installation.set("deviceToken","device_token_" + installations.length) installation.set("badge", installations.length); @@ -335,10 +335,10 @@ describe('PushController', () => { installations.push(installation); } let matchedInstallationsCount = 0; - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { matchedInstallationsCount += installations.length; - var badge = body.data.badge; + const badge = body.data.badge; installations.forEach((installation) => { expect(installation.badge).toEqual(badge); expect(1).toEqual(installation.badge); @@ -350,11 +350,11 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter @@ -393,7 +393,7 @@ describe('PushController', () => { }; const spy = spyOn(pushStatusAfterSave, 'handler').and.callThrough(); Parse.Cloud.afterSave('_PushStatus', pushStatusAfterSave.handler); - var installations = []; + const installations = []; while(installations.length != 10) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -411,12 +411,12 @@ describe('PushController', () => { installation.set("deviceType", "android"); installations.push(installation); } - var payload = {data: { + const payload = {data: { alert: "Hello World!", badge: 1, }} - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulIOS(body, installations); }, @@ -425,11 +425,11 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { @@ -515,12 +515,12 @@ describe('PushController', () => { installation.set("originalBadge", 0); installation.set("deviceType", "ios"); - var payload = {data: { + const payload = {data: { alert: "Hello World!", badge: 1, }} - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulIOS(body, installations); }, @@ -529,11 +529,11 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); return installation.save().then(() => { return reconfigureServer({ serverURL: 'http://localhost:8378/', // server with borked URL @@ -560,7 +560,7 @@ describe('PushController', () => { }); it('should properly report failures in _PushStatus', (done) => { - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return installations.map((installation) => { return Promise.resolve({ @@ -575,15 +575,15 @@ describe('PushController', () => { const where = { 'channels': { '$ins': ['Giants', 'Mets'] }}; - var payload = {data: { + const payload = {data: { alert: "Hello World!", badge: 1, }} - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { @@ -603,12 +603,12 @@ describe('PushController', () => { }); it('should support full RESTQuery for increment', (done) => { - var payload = {data: { + const payload = {data: { alert: "Hello World!", badge: 'Increment', }} - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulTransmissions(body, installations); }, @@ -616,8 +616,8 @@ describe('PushController', () => { return ["ios"]; } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } @@ -627,11 +627,11 @@ describe('PushController', () => { } } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var installations = []; + const installations = []; while (installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -662,13 +662,13 @@ describe('PushController', () => { }); it('should support object type for alert', (done) => { - var payload = {data: { + const payload = {data: { alert: { 'loc-key': 'hello_world', }, }} - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulTransmissions(body, installations); }, @@ -677,8 +677,8 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } @@ -686,11 +686,11 @@ describe('PushController', () => { 'deviceType': 'ios' } - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var installations = []; + const installations = []; while (installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -721,7 +721,7 @@ describe('PushController', () => { }); it('should flatten', () => { - var res = StatusHandler.flatten([1, [2], [[3, 4], 5], [[[6]]]]) + const res = StatusHandler.flatten([1, [2], [[3, 4], 5], [[[6]]]]) expect(res).toEqual([1,2,3,4,5,6]); }); @@ -762,11 +762,11 @@ describe('PushController', () => { }); it('should not schedule push when not configured', (done) => { - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulTransmissions(body, installations); }, @@ -775,7 +775,7 @@ describe('PushController', () => { } } - var pushController = new PushController(); + const pushController = new PushController(); const payload = { data: { alert: 'hello', @@ -783,7 +783,7 @@ describe('PushController', () => { push_time: new Date().getTime() } - var installations = []; + const installations = []; while(installations.length != 10) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -816,10 +816,10 @@ describe('PushController', () => { }); it('should schedule push when configured', (done) => { - var auth = { + const auth = { isMaster: true } - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { const promises = installations.map((device) => { if (!device.deviceToken) { @@ -839,7 +839,7 @@ describe('PushController', () => { } } - var pushController = new PushController(); + const pushController = new PushController(); const payload = { data: { alert: 'hello', @@ -847,7 +847,7 @@ describe('PushController', () => { push_time: new Date().getTime() / 1000 } - var installations = []; + const installations = []; while(installations.length != 10) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -862,7 +862,7 @@ describe('PushController', () => { push: { adapter: pushAdapter }, scheduledPush: true }).then(() => { - var config = Config.get(Parse.applicationId); + const config = Config.get(Parse.applicationId); return Parse.Object.saveAll(installations).then(() => { return pushController.sendPush(payload, {}, config, auth); }).then(() => new Promise(resolve => setTimeout(resolve, 300))); @@ -877,10 +877,10 @@ describe('PushController', () => { }); it('should not enqueue push when device token is not set', (done) => { - var auth = { + const auth = { isMaster: true } - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { const promises = installations.map((device) => { if (!device.deviceToken) { @@ -900,7 +900,7 @@ describe('PushController', () => { } } - var pushController = new PushController(); + const pushController = new PushController(); const payload = { data: { alert: 'hello', @@ -908,7 +908,7 @@ describe('PushController', () => { push_time: new Date().getTime() / 1000 } - var installations = []; + const installations = []; while(installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -931,7 +931,7 @@ describe('PushController', () => { reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var config = Config.get(Parse.applicationId); + const config = Config.get(Parse.applicationId); return Parse.Object.saveAll(installations).then(() => { return pushController.sendPush(payload, {}, config, auth); }).then(() => new Promise(resolve => setTimeout(resolve, 100))); @@ -952,10 +952,10 @@ describe('PushController', () => { }); it('should not mark the _PushStatus as failed when audience has no deviceToken', (done) => { - var auth = { + const auth = { isMaster: true } - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { const promises = installations.map((device) => { if (!device.deviceToken) { @@ -975,7 +975,7 @@ describe('PushController', () => { } } - var pushController = new PushController(); + const pushController = new PushController(); const payload = { data: { alert: 'hello', @@ -983,7 +983,7 @@ describe('PushController', () => { push_time: new Date().getTime() / 1000 } - var installations = []; + const installations = []; while(installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -996,7 +996,7 @@ describe('PushController', () => { reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var config = Config.get(Parse.applicationId); + const config = Config.get(Parse.applicationId); return Parse.Object.saveAll(installations).then(() => { return pushController.sendPush(payload, {}, config, auth) }).then(() => new Promise(resolve => setTimeout(resolve, 100))); @@ -1017,13 +1017,13 @@ describe('PushController', () => { }); it('should support localized payload data', (done) => { - var payload = {data: { + const payload = {data: { alert: 'Hello!', 'alert-fr': 'Bonjour', 'alert-es': 'Ola' }} - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulTransmissions(body, installations); }, @@ -1032,8 +1032,8 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } @@ -1041,11 +1041,11 @@ describe('PushController', () => { 'deviceType': 'ios' } spyOn(pushAdapter, 'send').and.callThrough(); - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var installations = []; + const installations = []; while (installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -1083,7 +1083,7 @@ describe('PushController', () => { }); it('should update audiences', (done) => { - var pushAdapter = { + const pushAdapter = { send: function(body, installations) { return successfulTransmissions(body, installations); }, @@ -1092,24 +1092,24 @@ describe('PushController', () => { } } - var config = Config.get(Parse.applicationId); - var auth = { + const config = Config.get(Parse.applicationId); + const auth = { isMaster: true } - var audienceId = null; - var now = new Date(); - var timesUsed = 0; + let audienceId = null; + const now = new Date(); + let timesUsed = 0; const where = { 'deviceType': 'ios' } spyOn(pushAdapter, 'send').and.callThrough(); - var pushController = new PushController(); + const pushController = new PushController(); reconfigureServer({ push: { adapter: pushAdapter } }).then(() => { - var installations = []; + const installations = []; while (installations.length != 5) { const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); @@ -1141,7 +1141,7 @@ describe('PushController', () => { return query.find({ useMasterKey: true }).then(parseResults); }); }).then(() => { - var body = { + const body = { data: { alert: 'hello' }, audience_id: audienceId } diff --git a/spec/PushRouter.spec.js b/spec/PushRouter.spec.js index 411076a2..6a942498 100644 --- a/spec/PushRouter.spec.js +++ b/spec/PushRouter.spec.js @@ -1,16 +1,16 @@ -var PushRouter = require('../src/Routers/PushRouter').PushRouter; -var request = require('request'); +const PushRouter = require('../src/Routers/PushRouter').PushRouter; +const request = require('request'); describe('PushRouter', () => { it('can get query condition when channels is set', (done) => { // Make mock request - var request = { + const request = { body: { channels: ['Giants', 'Mets'] } } - var where = PushRouter.getQueryCondition(request); + const where = PushRouter.getQueryCondition(request); expect(where).toEqual({ 'channels': { '$in': ['Giants', 'Mets'] @@ -21,7 +21,7 @@ describe('PushRouter', () => { it('can get query condition when where is set', (done) => { // Make mock request - var request = { + const request = { body: { 'where': { 'injuryReports': true @@ -29,7 +29,7 @@ describe('PushRouter', () => { } } - var where = PushRouter.getQueryCondition(request); + const where = PushRouter.getQueryCondition(request); expect(where).toEqual({ 'injuryReports': true }); @@ -38,7 +38,7 @@ describe('PushRouter', () => { it('can get query condition when nothing is set', (done) => { // Make mock request - var request = { + const request = { body: { } } @@ -51,7 +51,7 @@ describe('PushRouter', () => { it('can throw on getQueryCondition when channels and where are set', (done) => { // Make mock request - var request = { + const request = { body: { 'channels': { '$in': ['Giants', 'Mets'] diff --git a/spec/PushWorker.spec.js b/spec/PushWorker.spec.js index 22380275..43d49ac5 100644 --- a/spec/PushWorker.spec.js +++ b/spec/PushWorker.spec.js @@ -1,13 +1,13 @@ -var PushWorker = require('../src').PushWorker; -var PushUtils = require('../src/Push/utils'); -var Config = require('../src/Config'); -var { pushStatusHandler } = require('../src/StatusHandler'); -var rest = require('../src/rest'); +const PushWorker = require('../src').PushWorker; +const PushUtils = require('../src/Push/utils'); +const Config = require('../src/Config'); +const { pushStatusHandler } = require('../src/StatusHandler'); +const rest = require('../src/rest'); describe('PushWorker', () => { it('should run with small batch', (done) => { const batchSize = 3; - var sendCount = 0; + let sendCount = 0; reconfigureServer({ push: { queueOptions: { @@ -27,9 +27,9 @@ describe('PushWorker', () => { return ['ios', 'android'] } }); - var installations = []; + const installations = []; while(installations.length != 10) { - var installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_" + installations.length); installation.set("deviceToken","device_token_" + installations.length) installation.set("badge", 1); @@ -164,7 +164,7 @@ describe('PushWorker', () => { const config = Config.get('test'); const handler = pushStatusHandler(config); const spy = spyOn(config.database, "update").and.callFake(() => { - return Promise.resolve(); + return Promise.resolve({}); }); const toAwait = handler.trackSent([ { diff --git a/spec/QueryTools.spec.js b/spec/QueryTools.spec.js index b43ccb5e..70697252 100644 --- a/spec/QueryTools.spec.js +++ b/spec/QueryTools.spec.js @@ -1,27 +1,27 @@ -var Parse = require('parse/node'); +const Parse = require('parse/node'); -var Id = require('../src/LiveQuery/Id'); -var QueryTools = require('../src/LiveQuery/QueryTools'); -var queryHash = QueryTools.queryHash; -var matchesQuery = QueryTools.matchesQuery; +const Id = require('../src/LiveQuery/Id'); +const QueryTools = require('../src/LiveQuery/QueryTools'); +const queryHash = QueryTools.queryHash; +const matchesQuery = QueryTools.matchesQuery; -var Item = Parse.Object.extend('Item'); +const Item = Parse.Object.extend('Item'); describe('queryHash', function() { it('should always hash a query to the same string', function() { - var q = new Parse.Query(Item); + const q = new Parse.Query(Item); q.equalTo('field', 'value'); q.exists('name'); q.ascending('createdAt'); q.limit(10); - var firstHash = queryHash(q); - var secondHash = queryHash(q); + const firstHash = queryHash(q); + const secondHash = queryHash(q); expect(firstHash).toBe(secondHash); }); it('should return equivalent hashes for equivalent queries', function() { - var q1 = new Parse.Query(Item); + let q1 = new Parse.Query(Item); q1.equalTo('field', 'value'); q1.exists('name'); q1.lessThan('age', 30); @@ -30,7 +30,7 @@ describe('queryHash', function() { q1.include(['name', 'age']); q1.limit(10); - var q2 = new Parse.Query(Item); + let q2 = new Parse.Query(Item); q2.limit(10); q2.greaterThan('age', 3); q2.lessThan('age', 30); @@ -39,8 +39,8 @@ describe('queryHash', function() { q2.exists('name'); q2.equalTo('field', 'value'); - var firstHash = queryHash(q1); - var secondHash = queryHash(q2); + let firstHash = queryHash(q1); + let secondHash = queryHash(q2); expect(firstHash).toBe(secondHash); q1.containedIn('fruit', ['apple', 'banana', 'cherry']); @@ -70,10 +70,10 @@ describe('queryHash', function() { }); it('should not let fields of different types appear similar', function() { - var q1 = new Parse.Query(Item); + let q1 = new Parse.Query(Item); q1.lessThan('age', 30); - var q2 = new Parse.Query(Item); + const q2 = new Parse.Query(Item); q2.equalTo('age', '{$lt:30}'); expect(queryHash(q1)).not.toBe(queryHash(q2)); @@ -89,11 +89,11 @@ describe('queryHash', function() { describe('matchesQuery', function() { it('matches blanket queries', function() { - var obj = { + const obj = { id: new Id('Klass', 'O1'), value: 12 }; - var q = new Parse.Query('Klass'); + const q = new Parse.Query('Klass'); expect(matchesQuery(obj, q)).toBe(true); obj.id = new Id('Other', 'O1'); @@ -101,11 +101,11 @@ describe('matchesQuery', function() { }); it('matches existence queries', function() { - var obj = { + const obj = { id: new Id('Item', 'O1'), count: 15 }; - var q = new Parse.Query('Item'); + const q = new Parse.Query('Item'); q.exists('count'); expect(matchesQuery(obj, q)).toBe(true); q.exists('name'); @@ -113,11 +113,11 @@ describe('matchesQuery', function() { }); it('matches queries with doesNotExist constraint', function() { - var obj = { + const obj = { id: new Id('Item', 'O1'), count: 15 }; - var q = new Parse.Query('Item'); + let q = new Parse.Query('Item'); q.doesNotExist('name'); expect(matchesQuery(obj, q)).toBe(true); @@ -127,12 +127,12 @@ describe('matchesQuery', function() { }); it('matches on equality queries', function() { - var day = new Date(); - var location = new Parse.GeoPoint({ + const day = new Date(); + const location = new Parse.GeoPoint({ latitude: 37.484815, longitude: -122.148377 }); - var obj = { + const obj = { id: new Id('Person', 'O1'), score: 12, name: 'Bill', @@ -140,7 +140,7 @@ describe('matchesQuery', function() { lastLocation: location }; - var q = new Parse.Query('Person'); + let q = new Parse.Query('Person'); q.equalTo('score', 12); expect(matchesQuery(obj, q)).toBe(true); @@ -192,7 +192,7 @@ describe('matchesQuery', function() { q.equalTo('name', 'bill'); expect(matchesQuery(obj, q)).toBe(false); - var img = { + let img = { id: new Id('Image', 'I1'), tags: ['nofilter', 'latergram', 'tbt'] }; @@ -203,13 +203,13 @@ describe('matchesQuery', function() { q.equalTo('tags', 'tbt'); expect(matchesQuery(img, q)).toBe(true); - var q2 = new Parse.Query('Image'); + const q2 = new Parse.Query('Image'); q2.containsAll('tags', ['latergram', 'nofilter']); expect(matchesQuery(img, q2)).toBe(true); q2.containsAll('tags', ['latergram', 'selfie']); expect(matchesQuery(img, q2)).toBe(false); - var u = new Parse.User(); + const u = new Parse.User(); u.id = 'U2'; q = new Parse.Query('Image'); q.equalTo('owner', u); @@ -246,13 +246,13 @@ describe('matchesQuery', function() { }); it('matches on inequalities', function() { - var player = { + const player = { id: new Id('Person', 'O1'), score: 12, name: 'Bill', birthday: new Date(1980, 2, 4), }; - var q = new Parse.Query('Person'); + let q = new Parse.Query('Person'); q.lessThan('score', 15); expect(matchesQuery(player, q)).toBe(true); q.lessThan('score', 10); @@ -288,29 +288,29 @@ describe('matchesQuery', function() { }); it('matches an $or query', function() { - var player = { + const player = { id: new Id('Player', 'P1'), name: 'Player 1', score: 12 }; - var q = new Parse.Query('Player'); + const q = new Parse.Query('Player'); q.equalTo('name', 'Player 1'); - var q2 = new Parse.Query('Player'); + const q2 = new Parse.Query('Player'); q2.equalTo('name', 'Player 2'); - var orQuery = Parse.Query.or(q, q2); + const orQuery = Parse.Query.or(q, q2); expect(matchesQuery(player, q)).toBe(true); expect(matchesQuery(player, q2)).toBe(false); expect(matchesQuery(player, orQuery)).toBe(true); }); it('matches $regex queries', function() { - var player = { + const player = { id: new Id('Player', 'P1'), name: 'Player 1', score: 12 }; - var q = new Parse.Query('Player'); + let q = new Parse.Query('Player'); q.startsWith('name', 'Play'); expect(matchesQuery(player, q)).toBe(true); q.startsWith('name', 'Ploy'); @@ -353,17 +353,17 @@ describe('matchesQuery', function() { }); it('matches $nearSphere queries', function() { - var q = new Parse.Query('Checkin'); + let q = new Parse.Query('Checkin'); q.near('location', new Parse.GeoPoint(20, 20)); // With no max distance, any GeoPoint is 'near' - var pt = { + const pt = { id: new Id('Checkin', 'C1'), location: new Parse.GeoPoint(40, 40) }; - var ptUndefined = { + const ptUndefined = { id: new Id('Checkin', 'C1') }; - var ptNull = { + const ptNull = { id: new Id('Checkin', 'C1'), location: null }; @@ -381,30 +381,30 @@ describe('matchesQuery', function() { }); it('matches $within queries', function() { - var caltrainStation = { + const caltrainStation = { id: new Id('Checkin', 'C1'), location: new Parse.GeoPoint(37.776346, -122.394218), name: 'Caltrain' }; - var santaClara = { + const santaClara = { id: new Id('Checkin', 'C2'), location: new Parse.GeoPoint(37.325635, -121.945753), name: 'Santa Clara' }; - var noLocation = { + const noLocation = { id: new Id('Checkin', 'C2'), name: 'Santa Clara' }; - var nullLocation = { + const nullLocation = { id: new Id('Checkin', 'C2'), location: null, name: 'Santa Clara' }; - var q = new Parse.Query('Checkin').withinGeoBox( + let q = new Parse.Query('Checkin').withinGeoBox( 'location', new Parse.GeoPoint(37.708813, -122.526398), new Parse.GeoPoint(37.822802, -122.373962) @@ -435,13 +435,13 @@ describe('matchesQuery', function() { }); it('matches on subobjects with dot notation', function() { - var message = { + const message = { id: new Id('Message', 'O1'), text: "content", status: {x: "read", y: "delivered"} }; - var q = new Parse.Query('Message'); + let q = new Parse.Query('Message'); q.equalTo("status.x", "read"); expect(matchesQuery(message, q)).toBe(true); @@ -501,11 +501,11 @@ describe('matchesQuery', function() { } it('should support containedIn with pointers', () => { - var message = { + const message = { id: new Id('Message', 'O1'), profile: pointer('Profile', 'abc') }; - var q = new Parse.Query('Message'); + let q = new Parse.Query('Message'); q.containedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'abc' }), Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' })]); expect(matchesQuery(message, q)).toBe(true); @@ -517,11 +517,11 @@ describe('matchesQuery', function() { }); it('should support notContainedIn with pointers', () => { - var message = { + let message = { id: new Id('Message', 'O1'), profile: pointer('Profile', 'abc') }; - var q = new Parse.Query('Message'); + let q = new Parse.Query('Message'); q.notContainedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' }), Parse.Object.fromJSON({ className: 'Profile', objectId: 'ghi' })]); expect(matchesQuery(message, q)).toBe(true); @@ -537,11 +537,11 @@ describe('matchesQuery', function() { }); it('should support containedIn queries with [objectId]', () => { - var message = { + let message = { id: new Id('Message', 'O1'), profile: pointer('Profile', 'abc') }; - var q = new Parse.Query('Message'); + let q = new Parse.Query('Message'); q.containedIn('profile', ['abc', 'def']); expect(matchesQuery(message, q)).toBe(true); @@ -555,11 +555,11 @@ describe('matchesQuery', function() { }); it('should support notContainedIn queries with [objectId]', () => { - var message = { + let message = { id: new Id('Message', 'O1'), profile: pointer('Profile', 'ghi') }; - var q = new Parse.Query('Message'); + let q = new Parse.Query('Message'); q.notContainedIn('profile', ['abc', 'def']); expect(matchesQuery(message, q)).toBe(true); message = { diff --git a/spec/RedisCacheAdapter.spec.js b/spec/RedisCacheAdapter.spec.js index 8707da25..4669d341 100644 --- a/spec/RedisCacheAdapter.spec.js +++ b/spec/RedisCacheAdapter.spec.js @@ -1,4 +1,4 @@ -var RedisCacheAdapter = require('../src/Adapters/Cache/RedisCacheAdapter').default; +const RedisCacheAdapter = require('../src/Adapters/Cache/RedisCacheAdapter').default; /* To run this test part of the complete suite set PARSE_SERVER_TEST_CACHE='redis' @@ -7,8 +7,8 @@ and make sure a redis server is available on the default port describe_only(() => { return process.env.PARSE_SERVER_TEST_CACHE === 'redis'; })('RedisCacheAdapter', function() { - var KEY = 'hello'; - var VALUE = 'world'; + const KEY = 'hello'; + const VALUE = 'world'; function wait(sleep) { return new Promise(function(resolve) { @@ -17,7 +17,7 @@ describe_only(() => { } it('should get/set/clear', (done) => { - var cache = new RedisCacheAdapter({ + const cache = new RedisCacheAdapter({ ttl: NaN }); @@ -31,7 +31,7 @@ describe_only(() => { }); it('should expire after ttl', (done) => { - var cache = new RedisCacheAdapter(null, 1); + const cache = new RedisCacheAdapter(null, 1); cache.put(KEY, VALUE) .then(() => cache.get(KEY)) @@ -43,7 +43,7 @@ describe_only(() => { }); it('should find un-expired records', (done) => { - var cache = new RedisCacheAdapter(null, 5); + const cache = new RedisCacheAdapter(null, 5); cache.put(KEY, VALUE) .then(() => cache.get(KEY)) diff --git a/spec/RedisPubSub.spec.js b/spec/RedisPubSub.spec.js index 263bc209..32497b57 100644 --- a/spec/RedisPubSub.spec.js +++ b/spec/RedisPubSub.spec.js @@ -1,10 +1,10 @@ -var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; +const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; describe('RedisPubSub', function() { beforeEach(function(done) { // Mock redis - var createClient = jasmine.createSpy('createClient'); + const createClient = jasmine.createSpy('createClient'); jasmine.mockLibrary('redis', 'createClient', createClient); done(); }); @@ -12,14 +12,14 @@ describe('RedisPubSub', function() { it('can create publisher', function() { RedisPubSub.createPublisher({redisURL: 'redisAddress'}); - var redis = require('redis'); + const redis = require('redis'); expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true }); }); it('can create subscriber', function() { RedisPubSub.createSubscriber({redisURL: 'redisAddress'}); - var redis = require('redis'); + const redis = require('redis'); expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true }); }); diff --git a/spec/RestQuery.spec.js b/spec/RestQuery.spec.js index 5c6cc4e2..5d1c8881 100644 --- a/spec/RestQuery.spec.js +++ b/spec/RestQuery.spec.js @@ -1,15 +1,15 @@ 'use strict' // These tests check the "find" functionality of the REST API. -var auth = require('../src/Auth'); -var Config = require('../src/Config'); -var rest = require('../src/rest'); +const auth = require('../src/Auth'); +const Config = require('../src/Config'); +const rest = require('../src/rest'); -var querystring = require('querystring'); -var rp = require('request-promise'); +const querystring = require('querystring'); +const rp = require('request-promise'); -var config; +let config; let database; -var nobody = auth.nobody(config); +const nobody = auth.nobody(config); describe('rest query', () => { @@ -42,7 +42,7 @@ describe('rest query', () => { }); }); - var data = { + const data = { username: 'blah', password: 'pass', sessionToken: 'abc123', @@ -52,7 +52,7 @@ describe('rest query', () => { database.create('_User', data).then(() => { return rest.find(config, nobody, '_User') }).then((result) => { - var user = result.results[0]; + const user = result.results[0]; expect(user.username).toEqual('blah'); expect(user.sessionToken).toBeUndefined(); expect(user.password).toBeUndefined(); @@ -64,7 +64,7 @@ describe('rest query', () => { database.create('_User', data).then(() => { return rest.find(config, {isMaster: true}, '_User') }).then((result) => { - var user = result.results[0]; + const user = result.results[0]; expect(user.username).toEqual('blah'); expect(user.sessionToken).toBeUndefined(); expect(user.password).toBeUndefined(); @@ -74,14 +74,14 @@ describe('rest query', () => { // Created to test a scenario in AnyPic it_exclude_dbs(['postgres'])('query with include', (done) => { - var photo = { + let photo = { foo: 'bar' }; - var user = { + let user = { username: 'aUsername', password: 'aPassword' }; - var activity = { + const activity = { type: 'comment', photo: { __type: 'Pointer', @@ -94,7 +94,7 @@ describe('rest query', () => { objectId: '' } }; - var queryWhere = { + const queryWhere = { photo: { __type: 'Pointer', className: 'TestPhoto', @@ -102,7 +102,7 @@ describe('rest query', () => { }, type: 'comment' }; - var queryOptions = { + const queryOptions = { include: 'fromUser', order: 'createdAt', limit: 30 @@ -122,7 +122,7 @@ describe('rest query', () => { return rest.find(config, nobody, 'TestActivity', queryWhere, queryOptions); }).then((response) => { - var results = response.results; + const results = response.results; expect(results.length).toEqual(1); expect(typeof results[0].objectId).toEqual('string'); expect(typeof results[0].photo).toEqual('object'); @@ -133,7 +133,7 @@ describe('rest query', () => { }); it('query non-existent class when disabled client class creation', (done) => { - var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); + const customConfig = Object.assign({}, config, {allowClientClassCreation: false}); rest.find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}) .then(() => { fail('Should throw an error'); @@ -147,7 +147,7 @@ describe('rest query', () => { }); it('query existent class when disabled client class creation', (done) => { - var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); + const customConfig = Object.assign({}, config, {allowClientClassCreation: false}); config.database.loadSchema() .then(schema => schema.addClassIfNotExists('ClientClassCreation', {})) .then(actualSchema => { @@ -168,7 +168,7 @@ describe('rest query', () => { return rest.create(config, nobody, 'TestParameterEncode', {foo: 'baz'}); }).then(() => { - var headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; @@ -182,7 +182,7 @@ describe('rest query', () => { }) .then(fail, (response) => { const error = response.error; - var b = JSON.parse(error); + const b = JSON.parse(error); expect(b.code).toEqual(Parse.Error.INVALID_QUERY); }); @@ -194,7 +194,7 @@ describe('rest query', () => { }) .then(fail, (response) => { const error = response.error; - var b = JSON.parse(error); + const b = JSON.parse(error); expect(b.code).toEqual(Parse.Error.INVALID_QUERY); }); return Promise.all([p0, p1]); diff --git a/spec/Schema.spec.js b/spec/Schema.spec.js index 98674065..c00f930c 100644 --- a/spec/Schema.spec.js +++ b/spec/Schema.spec.js @@ -1,13 +1,13 @@ 'use strict'; -var Config = require('../src/Config'); -var SchemaController = require('../src/Controllers/SchemaController'); -var dd = require('deep-diff'); +const Config = require('../src/Config'); +const SchemaController = require('../src/Controllers/SchemaController'); +const dd = require('deep-diff'); -var config; +let config; -var hasAllPODobject = () => { - var obj = new Parse.Object('HasAllPOD'); +const hasAllPODobject = () => { + const obj = new Parse.Object('HasAllPOD'); obj.set('aNumber', 5); obj.set('aString', 'string'); obj.set('aBool', true); @@ -104,7 +104,7 @@ describe('SchemaController', () => { 'find': {} }); }).then(() => { - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then(() => { fail('Class permissions should have rejected this query.'); @@ -115,7 +115,7 @@ describe('SchemaController', () => { }); it('class-level permissions test user', (done) => { - var user; + let user; createTestUser().then((u) => { user = u; return config.database.loadSchema(); @@ -123,13 +123,13 @@ describe('SchemaController', () => { // Just to create a valid class return schema.validateObject('Stuff', {foo: 'bar'}); }).then((schema) => { - var find = {}; + const find = {}; find[user.id] = true; return schema.setPermissions('Stuff', { 'find': find }); }).then(() => { - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then(() => { done(); @@ -140,15 +140,15 @@ describe('SchemaController', () => { }); it('class-level permissions test get', (done) => { - var obj; + let obj; createTestUser() .then(user => { return config.database.loadSchema() // Create a valid class .then(schema => schema.validateObject('Stuff', {foo: 'bar'})) .then(schema => { - var find = {}; - var get = {}; + const find = {}; + const get = {}; get[user.id] = true; return schema.setPermissions('Stuff', { 'create': {'*': true}, @@ -161,13 +161,13 @@ describe('SchemaController', () => { return obj.save(); }).then((o) => { obj = o; - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then(() => { fail('Class permissions should have rejected this query.'); done(); }, () => { - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.get(obj.id).then(() => { done(); }, () => { @@ -179,12 +179,12 @@ describe('SchemaController', () => { }); it('class-level permissions test count', (done) => { - var obj; + let obj; return config.database.loadSchema() // Create a valid class .then(schema => schema.validateObject('Stuff', {foo: 'bar'})) .then(schema => { - var count = {}; + const count = {}; return schema.setPermissions('Stuff', { 'create': {'*': true}, 'find': {'*': true}, @@ -196,11 +196,11 @@ describe('SchemaController', () => { return obj.save(); }).then((o) => { obj = o; - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then((results) => { expect(results.length).toBe(1); - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.count(); }).then(() => { fail('Class permissions should have rejected this query.'); @@ -341,8 +341,8 @@ describe('SchemaController', () => { // race loser should be the same as if they hadn't been racing. config.database.loadSchema() .then(schema => { - var p1 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); - var p2 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); + const p1 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); + const p2 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); Promise.race([p1, p2]) .then(actualSchema => { const expectedSchema = { @@ -758,12 +758,12 @@ describe('SchemaController', () => { }); it('drops related collection when deleting relation field', done => { - var obj1 = hasAllPODobject(); + const obj1 = hasAllPODobject(); obj1.save() .then(savedObj1 => { - var obj2 = new Parse.Object('HasPointersAndRelations'); + const obj2 = new Parse.Object('HasPointersAndRelations'); obj2.set('aPointer', savedObj1); - var relation = obj2.relation('aRelation'); + const relation = obj2.relation('aRelation'); relation.add(obj1); return obj2.save(); }) @@ -842,8 +842,8 @@ describe('SchemaController', () => { it('can delete string fields and resave as number field', done => { Parse.Object.disableSingleInstance(); - var obj1 = hasAllPODobject(); - var obj2 = hasAllPODobject(); + const obj1 = hasAllPODobject(); + const obj2 = hasAllPODobject(); Parse.Object.saveAll([obj1, obj2]) .then(() => config.database.loadSchema()) .then(schema => schema.deleteField('aString', 'HasAllPOD', config.database)) @@ -870,7 +870,7 @@ describe('SchemaController', () => { it('can delete pointer fields and resave as string', done => { Parse.Object.disableSingleInstance(); - var obj1 = new Parse.Object('NewClass'); + const obj1 = new Parse.Object('NewClass'); obj1.save() .then(() => { obj1.set('aPointer', obj1); @@ -1053,7 +1053,7 @@ describe('Class Level Permissions for requiredAuth', () => { } }); }).then(() => { - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then(() => { fail('Class permissions should have rejected this query.'); @@ -1077,7 +1077,7 @@ describe('Class Level Permissions for requiredAuth', () => { }).then(() => { return createUser(); }).then(() => { - var query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then((results) => { expect(results.length).toEqual(0); diff --git a/spec/SchemaCache.spec.js b/spec/SchemaCache.spec.js index a27abd98..ffbe9183 100644 --- a/spec/SchemaCache.spec.js +++ b/spec/SchemaCache.spec.js @@ -1,6 +1,6 @@ -var CacheController = require('../src/Controllers/CacheController.js').default; -var InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; -var SchemaCache = require('../src/Controllers/SchemaCache').default; +const CacheController = require('../src/Controllers/CacheController.js').default; +const InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; +const SchemaCache = require('../src/Controllers/SchemaCache').default; describe('SchemaCache', () => { let cacheController; diff --git a/spec/SessionTokenCache.spec.js b/spec/SessionTokenCache.spec.js index 57709e0c..316e55da 100644 --- a/spec/SessionTokenCache.spec.js +++ b/spec/SessionTokenCache.spec.js @@ -1,9 +1,9 @@ -var SessionTokenCache = require('../src/LiveQuery/SessionTokenCache').SessionTokenCache; +const SessionTokenCache = require('../src/LiveQuery/SessionTokenCache').SessionTokenCache; describe('SessionTokenCache', function() { beforeEach(function(done) { - var Parse = require('parse/node'); + const Parse = require('parse/node'); spyOn(Parse, "Query").and.returnValue({ first: jasmine.createSpy("first").and.returnValue(Parse.Promise.as(new Parse.Object("_Session", { @@ -16,7 +16,7 @@ describe('SessionTokenCache', function() { }); it('can get undefined userId', function(done) { - var sessionTokenCache = new SessionTokenCache(); + const sessionTokenCache = new SessionTokenCache(); sessionTokenCache.getUserId(undefined).then(() => { }, (error) => { @@ -26,9 +26,9 @@ describe('SessionTokenCache', function() { }); it('can get existing userId', function(done) { - var sessionTokenCache = new SessionTokenCache(); - var sessionToken = 'sessionToken'; - var userId = 'userId' + const sessionTokenCache = new SessionTokenCache(); + const sessionToken = 'sessionToken'; + const userId = 'userId' sessionTokenCache.cache.set(sessionToken, userId); sessionTokenCache.getUserId(sessionToken).then((userIdFromCache) => { @@ -38,7 +38,7 @@ describe('SessionTokenCache', function() { }); it('can get new userId', function(done) { - var sessionTokenCache = new SessionTokenCache(); + const sessionTokenCache = new SessionTokenCache(); sessionTokenCache.getUserId('sessionToken').then((userIdFromCache) => { expect(userIdFromCache).toBe('userId'); diff --git a/spec/Subscription.spec.js b/spec/Subscription.spec.js index 20f1aa5b..9fe20179 100644 --- a/spec/Subscription.spec.js +++ b/spec/Subscription.spec.js @@ -1,4 +1,4 @@ -var Subscription = require('../src/LiveQuery/Subscription').Subscription; +const Subscription = require('../src/LiveQuery/Subscription').Subscription; let logger; describe('Subscription', function() { @@ -8,7 +8,7 @@ describe('Subscription', function() { }); it('can be initialized', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); expect(subscription.className).toBe('className'); expect(subscription.query).toEqual({ key : 'value' }); @@ -17,20 +17,20 @@ describe('Subscription', function() { }); it('can check it has subscribing clients', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); expect(subscription.hasSubscribingClient()).toBe(false); }); it('can check it does not have subscribing clients', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); expect(subscription.hasSubscribingClient()).toBe(true); }); it('can add one request for one client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); expect(subscription.clientRequestIds.size).toBe(1); @@ -38,7 +38,7 @@ describe('Subscription', function() { }); it('can add requests for one client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); @@ -47,7 +47,7 @@ describe('Subscription', function() { }); it('can add requests for clients', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.addClientSubscription(2, 2); @@ -59,14 +59,14 @@ describe('Subscription', function() { }); it('can delete requests for nonexistent client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.deleteClientSubscription(1, 1); expect(logger.error).toHaveBeenCalled(); }); it('can delete nonexistent request for one client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.deleteClientSubscription(1, 2); @@ -76,7 +76,7 @@ describe('Subscription', function() { }); it('can delete some requests for one client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.deleteClientSubscription(1, 2); @@ -87,7 +87,7 @@ describe('Subscription', function() { }); it('can delete all requests for one client', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.deleteClientSubscription(1, 1); @@ -98,7 +98,7 @@ describe('Subscription', function() { }); it('can delete requests for multiple clients', function() { - var subscription = new Subscription('className', { key : 'value' }, 'hash'); + const subscription = new Subscription('className', { key : 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.addClientSubscription(2, 1); diff --git a/spec/UserController.spec.js b/spec/UserController.spec.js index 498f70b6..4588091f 100644 --- a/spec/UserController.spec.js +++ b/spec/UserController.spec.js @@ -1,9 +1,9 @@ -var UserController = require('../src/Controllers/UserController').UserController; -var emailAdapter = require('./MockEmailAdapter') -var AppCache = require('../src/cache').AppCache; +const UserController = require('../src/Controllers/UserController').UserController; +const emailAdapter = require('./MockEmailAdapter') +const AppCache = require('../src/cache').AppCache; describe('UserController', () => { - var user = { + const user = { _email_verify_token: 'testToken', username: 'testUser', email: 'test@example.com' @@ -25,7 +25,7 @@ describe('UserController', () => { done() } - var userController = new UserController(emailAdapter, 'test', { + const userController = new UserController(emailAdapter, 'test', { verifyUserEmails: true }) @@ -48,7 +48,7 @@ describe('UserController', () => { done() } - var userController = new UserController(emailAdapter, 'test', { + const userController = new UserController(emailAdapter, 'test', { verifyUserEmails: true }) diff --git a/spec/ValidationAndPasswordsReset.spec.js b/spec/ValidationAndPasswordsReset.spec.js index 1080cf00..99367a0b 100644 --- a/spec/ValidationAndPasswordsReset.spec.js +++ b/spec/ValidationAndPasswordsReset.spec.js @@ -18,7 +18,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { publicServerURL: "https://my.public.server.com/1" }) .then(() => { - var config = Config.get("test"); + const config = Config.get("test"); expect(config.invalidLinkURL).toEqual("myInvalidLink"); expect(config.verifyEmailSuccessURL).toEqual("myVerifyEmailSuccess"); expect(config.choosePasswordURL).toEqual("myChoosePassword"); @@ -31,7 +31,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('sends verification email if email verification is enabled', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -44,7 +44,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }) .then(() => { spyOn(emailAdapter, 'sendVerificationEmail'); - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.setEmail('testIfEnabled@parse.com'); @@ -66,7 +66,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does not send verification email when verification is enabled and email is not set', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -79,7 +79,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }) .then(() => { spyOn(emailAdapter, 'sendVerificationEmail'); - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.signUp(null, { @@ -100,7 +100,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does send a validation email when updating the email', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -113,7 +113,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }) .then(() => { spyOn(emailAdapter, 'sendVerificationEmail'); - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.signUp(null, { @@ -143,7 +143,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does send a validation email with valid verification link when updating the email', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -160,7 +160,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { expect(options.link).not.toMatch(/token=undefined/); Promise.resolve(); }); - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.signUp(null, { @@ -190,8 +190,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does send with a simple adapter', done => { - var calls = 0; - var emailAdapter = { + let calls = 0; + const emailAdapter = { sendMail: function(options){ expect(options.to).toBe('testSendSimpleAdapter@parse.com'); if (calls == 0) { @@ -212,7 +212,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { publicServerURL: "http://localhost:8378/1" }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testSendSimpleAdapter@parse.com"); @@ -277,9 +277,9 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('allows user to login only after user clicks on the link to confirm email address if preventLoginWithUnverifiedEmail is set to true', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -524,7 +524,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does not send verification email if email verification is disabled', done => { - var emailAdapter = { + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() @@ -537,7 +537,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }) .then(() => { spyOn(emailAdapter, 'sendVerificationEmail'); - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.signUp(null, { @@ -558,8 +558,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('receives the app name and user in the adapter', done => { - var emailSent = false; - var emailAdapter = { + let emailSent = false; + const emailAdapter = { sendVerificationEmail: options => { expect(options.appName).toEqual('emailing app'); expect(options.user.get('email')).toEqual('user@parse.com'); @@ -575,7 +575,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { publicServerURL: "http://localhost:8378/1" }) .then(() => { - var user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set('email', 'user@parse.com'); @@ -593,9 +593,9 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }) it('when you click the link in the email it sets emailVerified to true and redirects you', done => { - var user = new Parse.User(); - var sendEmailOptions; - var emailAdapter = { + const user = new Parse.User(); + let sendEmailOptions; + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, @@ -706,8 +706,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('does not update email verified if you use an invalid token', done => { - var user = new Parse.User(); - var emailAdapter = { + const user = new Parse.User(); + const emailAdapter = { sendVerificationEmail: () => { request.get('http://localhost:8378/1/apps/test/verify_email?token=invalid&username=zxcv', { followRedirect: false, @@ -745,8 +745,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('should send a password reset link', done => { - var user = new Parse.User(); - var emailAdapter = { + const user = new Parse.User(); + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: options => { request.get(options.link, { @@ -758,7 +758,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { return; } expect(response.statusCode).toEqual(302); - var re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=[a-zA-Z0-9]+\&id=test\&username=zxcv%2Bzxcv/; + const re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=[a-zA-Z0-9]+\&id=test\&username=zxcv%2Bzxcv/; expect(response.body.match(re)).not.toBe(null); done(); }); @@ -810,8 +810,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('should programatically reset password', done => { - var user = new Parse.User(); - var emailAdapter = { + const user = new Parse.User(); + const emailAdapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: options => { request.get(options.link, { @@ -823,14 +823,14 @@ describe("Custom Pages, Email Verification, Password Reset", () => { return; } expect(response.statusCode).toEqual(302); - var re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=([a-zA-Z0-9]+)\&id=test\&username=zxcv/; - var match = response.body.match(re); + const re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=([a-zA-Z0-9]+)\&id=test\&username=zxcv/; + const match = response.body.match(re); if (!match) { fail("should have a token"); done(); return; } - var token = match[1]; + const token = match[1]; request.post({ url: "http://localhost:8378/1/apps/test/request_password_reset" , diff --git a/spec/WinstonLoggerAdapter.spec.js b/spec/WinstonLoggerAdapter.spec.js index e677d0b8..555a3fee 100644 --- a/spec/WinstonLoggerAdapter.spec.js +++ b/spec/WinstonLoggerAdapter.spec.js @@ -1,12 +1,12 @@ 'use strict'; -var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; -var request = require('request'); +const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; +const request = require('request'); describe('info logs', () => { it("Verify INFO logs", (done) => { - var winstonLoggerAdapter = new WinstonLoggerAdapter(); + const winstonLoggerAdapter = new WinstonLoggerAdapter(); winstonLoggerAdapter.log('info', 'testing info logs', () => { winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), @@ -35,7 +35,7 @@ describe('info logs', () => { describe('error logs', () => { it("Verify ERROR logs", (done) => { - var winstonLoggerAdapter = new WinstonLoggerAdapter(); + const winstonLoggerAdapter = new WinstonLoggerAdapter(); winstonLoggerAdapter.log('error', 'testing error logs', () => { winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), @@ -71,7 +71,7 @@ describe('verbose logs', () => { expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0); expect(logString.match(/moon-y/g)).toBe(null); - var headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; diff --git a/spec/batch.spec.js b/spec/batch.spec.js index 5d30caab..b789b92b 100644 --- a/spec/batch.spec.js +++ b/spec/batch.spec.js @@ -1,4 +1,4 @@ -var batch = require('../src/batch'); +const batch = require('../src/batch'); const originalURL = '/parse/batch'; const serverURL = 'http://localhost:1234/parse'; diff --git a/spec/cryptoUtils.spec.js b/spec/cryptoUtils.spec.js index b38c9297..effa73b9 100644 --- a/spec/cryptoUtils.spec.js +++ b/spec/cryptoUtils.spec.js @@ -1,9 +1,9 @@ -var cryptoUtils = require('../src/cryptoUtils'); +const cryptoUtils = require('../src/cryptoUtils'); function givesUniqueResults(fn, iterations) { - var results = {}; - for (var i = 0; i < iterations; i++) { - var s = fn(); + const results = {}; + for (let i = 0; i < iterations; i++) { + const s = fn(); if (results[s]) { return false; } diff --git a/spec/helper.js b/spec/helper.js index 965d7165..7b9c2153 100644 --- a/spec/helper.js +++ b/spec/helper.js @@ -23,10 +23,10 @@ if (global._babelPolyfill) { process.exit(1); } -var cache = require('../src/cache').default; -var ParseServer = require('../src/index').ParseServer; -var path = require('path'); -var TestUtils = require('../src/TestUtils'); +const cache = require('../src/cache').default; +const ParseServer = require('../src/index').ParseServer; +const path = require('path'); +const TestUtils = require('../src/TestUtils'); const GridStoreAdapter = require('../src/Adapters/Files/GridStoreAdapter').GridStoreAdapter; const FSAdapter = require('@parse/fs-files-adapter'); import PostgresStorageAdapter from '../src/Adapters/Storage/Postgres/PostgresStorageAdapter'; @@ -58,7 +58,7 @@ if (process.env.PARSE_SERVER_TEST_DB === 'postgres') { }); } -var port = 8378; +const port = 8378; let filesAdapter; @@ -79,7 +79,7 @@ if (process.env.PARSE_SERVER_LOG_LEVEL) { logLevel = process.env.PARSE_SERVER_LOG_LEVEL; } // Default server configuration for tests. -var defaultConfiguration = { +const defaultConfiguration = { filesAdapter, serverURL: 'http://localhost:' + port + '/1', databaseAdapter, @@ -116,7 +116,7 @@ if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') { const openConnections = {}; // Set up a default API server for testing with default configuration. -var server; +let server; // Allows testing specific configurations of Parse Server const reconfigureServer = changedConfiguration => { @@ -153,7 +153,7 @@ const reconfigureServer = changedConfiguration => { } // Set up a Parse client to talk to our test API server -var Parse = require('parse/node'); +const Parse = require('parse/node'); Parse.serverURL = 'http://localhost:' + port + '/1'; // This is needed because we ported a bunch of tests from the non-A+ way. @@ -204,7 +204,7 @@ afterEach(function(done) { databaseAdapter.getAllClasses() .then(allSchemas => { allSchemas.forEach((schema) => { - var className = schema.className; + const className = schema.className; expect(className).toEqual({ asymmetricMatch: className => { if (!className.startsWith('_')) { return true; @@ -220,27 +220,27 @@ afterEach(function(done) { .then(afterLogOut, afterLogOut) }); -var TestObject = Parse.Object.extend({ +const TestObject = Parse.Object.extend({ className: "TestObject" }); -var Item = Parse.Object.extend({ +const Item = Parse.Object.extend({ className: "Item" }); -var Container = Parse.Object.extend({ +const Container = Parse.Object.extend({ className: "Container" }); // Convenience method to create a new TestObject with a callback function create(options, callback) { - var t = new TestObject(options); + const t = new TestObject(options); t.save(null, { success: callback }); } function createTestUser(success, error) { - var user = new Parse.User(); + const user = new Parse.User(); user.set('username', 'test'); user.set('password', 'moon-y'); - var promise = user.signUp(); + const promise = user.signUp(); if (success || error) { promise.then(function(user) { if (success) { @@ -312,8 +312,8 @@ function normalize(obj) { if (obj instanceof Array) { return '[' + obj.map(normalize).join(', ') + ']'; } - var answer = '{'; - for (var key of Object.keys(obj).sort()) { + let answer = '{'; + for (const key of Object.keys(obj).sort()) { answer += key + ': '; answer += normalize(obj[key]); answer += ', '; @@ -328,15 +328,15 @@ function jequal(o1, o2) { } function range(n) { - var answer = []; - for (var i = 0; i < n; i++) { + const answer = []; + for (let i = 0; i < n; i++) { answer.push(i); } return answer; } function mockFacebookAuthenticator(id, token) { - var facebook = {}; + const facebook = {}; facebook.validateAuthData = function(authData) { if (authData.id === id && authData.access_token.startsWith(token)) { return Promise.resolve(); @@ -444,9 +444,9 @@ global.describe_only = (validator) =>{ }; -var libraryCache = {}; +const libraryCache = {}; jasmine.mockLibrary = function(library, name, mock) { - var original = require(library)[name]; + const original = require(library)[name]; if (!libraryCache[library]) { libraryCache[library] = {}; } diff --git a/spec/index.spec.js b/spec/index.spec.js index ed9e9a91..335a8ac3 100644 --- a/spec/index.spec.js +++ b/spec/index.spec.js @@ -1,10 +1,10 @@ "use strict" -var request = require('request'); -var parseServerPackage = require('../package.json'); -var MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); -var ParseServer = require("../src/index"); -var Config = require('../src/Config'); -var express = require('express'); +const request = require('request'); +const parseServerPackage = require('../package.json'); +const MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); +const ParseServer = require("../src/index"); +const Config = require('../src/Config'); +const express = require('express'); import MongoStorageAdapter from '../src/Adapters/Storage/Mongo/MongoStorageAdapter'; @@ -270,7 +270,7 @@ describe('server', () => { }); it('can create a parse-server v1', done => { - var parseServer = new ParseServer.default(Object.assign({}, + const parseServer = new ParseServer.default(Object.assign({}, defaultConfiguration, { appId: "aTestApp", masterKey: "aTestMasterKey", @@ -279,15 +279,15 @@ describe('server', () => { promise .then(() => { expect(Parse.applicationId).toEqual("aTestApp"); - var app = express(); + const app = express(); app.use('/parse', parseServer.app); - var server = app.listen(12666); - var obj = new Parse.Object("AnObject"); - var objId; + const server = app.listen(12666); + const obj = new Parse.Object("AnObject"); + let objId; obj.save().then((obj) => { objId = obj.id; - var q = new Parse.Query("AnObject"); + const q = new Parse.Query("AnObject"); return q.first(); }).then((obj) => { expect(obj.id).toEqual(objId); @@ -360,7 +360,7 @@ describe('server', () => { it('properly gives publicServerURL when set', done => { reconfigureServer({ publicServerURL: 'https://myserver.com/1' }) .then(() => { - var config = Config.get('test', 'http://localhost:8378/1'); + const config = Config.get('test', 'http://localhost:8378/1'); expect(config.mount).toEqual('https://myserver.com/1'); done(); }); @@ -369,7 +369,7 @@ describe('server', () => { it('properly removes trailing slash in mount', done => { reconfigureServer({}) .then(() => { - var config = Config.get('test', 'http://localhost:8378/1/'); + const config = Config.get('test', 'http://localhost:8378/1/'); expect(config.mount).toEqual('http://localhost:8378/1'); done(); }); diff --git a/spec/rest.spec.js b/spec/rest.spec.js index 1e897ef3..af6ce8c4 100644 --- a/spec/rest.spec.js +++ b/spec/rest.spec.js @@ -1,12 +1,12 @@ "use strict"; // These tests check the "create" / "update" functionality of the REST API. -var auth = require('../src/Auth'); -var Config = require('../src/Config'); -var Parse = require('parse/node').Parse; -var rest = require('../src/rest'); -var RestWrite = require('../src/RestWrite'); -var request = require('request'); -var rp = require('request-promise'); +const auth = require('../src/Auth'); +const Config = require('../src/Config'); +const Parse = require('parse/node').Parse; +const rest = require('../src/rest'); +const RestWrite = require('../src/RestWrite'); +const request = require('request'); +const rp = require('request-promise'); let config; let database; @@ -23,7 +23,7 @@ describe('rest create', () => { .then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) .then(results => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(typeof obj.objectId).toEqual('string'); expect(obj.objectId.length).toEqual(10); expect(obj._id).toBeUndefined(); @@ -37,7 +37,7 @@ describe('rest create', () => { .then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) .then((results) => { expect(results.length).toEqual(1); - var obj = results[0]; + const obj = results[0]; expect(typeof obj.objectId).toEqual('string'); expect(obj.objectId.length).toEqual(20); done(); @@ -76,7 +76,7 @@ describe('rest create', () => { it('handles array, object, date', (done) => { const now = new Date(); - var obj = { + const obj = { array: [1, 2, 3], object: {foo: 'bar'}, date: Parse._encode(now), @@ -89,7 +89,7 @@ describe('rest create', () => { } }, {}, {})) .then(results => { expect(results.length).toEqual(1); - var mob = results[0]; + const mob = results[0]; expect(mob.array instanceof Array).toBe(true); expect(typeof mob.object).toBe('object'); expect(mob.date.__type).toBe('Date'); @@ -135,7 +135,7 @@ describe('rest create', () => { }); it('handles create on non-existent class when disabled client class creation', (done) => { - var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); + const customConfig = Object.assign({}, config, {allowClientClassCreation: false}); rest.create(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}) .then(() => { fail('Should throw an error'); @@ -149,7 +149,7 @@ describe('rest create', () => { }); it('handles create on existent class when disabled client class creation', (done) => { - var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); + const customConfig = Object.assign({}, config, {allowClientClassCreation: false}); config.database.loadSchema() .then(schema => schema.addClassIfNotExists('ClientClassCreation', {})) .then(actualSchema => { @@ -164,7 +164,7 @@ describe('rest create', () => { }); it('handles user signup', (done) => { - var user = { + const user = { username: 'asdf', password: 'zxcv', foo: 'bar', @@ -180,21 +180,21 @@ describe('rest create', () => { }); it('handles anonymous user signup', (done) => { - var data1 = { + const data1 = { authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' } } }; - var data2 = { + const data2 = { authData: { anonymous: { id: '00000000-0000-0000-0000-000000000002' } } }; - var username1; + let username1; rest.create(config, auth.nobody(config), '_User', data1) .then((r) => { expect(typeof r.response.objectId).toEqual('string'); @@ -225,7 +225,7 @@ describe('rest create', () => { }); it('handles anonymous user signup and upgrade to new user', (done) => { - var data1 = { + const data1 = { authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' @@ -233,12 +233,12 @@ describe('rest create', () => { } }; - var updatedData = { + const updatedData = { authData: { anonymous: null }, username: 'hello', password: 'world' } - var objectId; + let objectId; rest.create(config, auth.nobody(config), '_User', data1) .then((r) => { expect(typeof r.response.objectId).toEqual('string'); @@ -263,9 +263,9 @@ describe('rest create', () => { }); it('handles no anonymous users config', (done) => { - var NoAnnonConfig = Object.assign({}, config); + const NoAnnonConfig = Object.assign({}, config); NoAnnonConfig.authDataManager.setEnableAnonymousUsers(false); - var data1 = { + const data1 = { authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' @@ -284,7 +284,7 @@ describe('rest create', () => { }); it('test facebook signup and login', (done) => { - var data = { + const data = { authData: { facebook: { id: '8675309', @@ -292,7 +292,7 @@ describe('rest create', () => { } } }; - var newUserSignedUpByFacebookObjectId; + let newUserSignedUpByFacebookObjectId; rest.create(config, auth.nobody(config), '_User', data) .then((r) => { expect(typeof r.response.objectId).toEqual('string'); @@ -310,7 +310,7 @@ describe('rest create', () => { '_Session', {sessionToken: r.response.sessionToken}); }).then((response) => { expect(response.results.length).toEqual(1); - var output = response.results[0]; + const output = response.results[0]; expect(output.user.objectId).toEqual(newUserSignedUpByFacebookObjectId); done(); }).catch(err => { @@ -349,7 +349,7 @@ describe('rest create', () => { }); it("cannot set objectId", (done) => { - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -362,7 +362,7 @@ describe('rest create', () => { 'objectId': 'hello' }) }, (error, response, body) => { - var b = JSON.parse(body); + const b = JSON.parse(body); expect(b.code).toEqual(105); expect(b.error).toEqual('objectId is an invalid field name.'); done(); @@ -370,12 +370,12 @@ describe('rest create', () => { }); it("test default session length", (done) => { - var user = { + const user = { username: 'asdf', password: 'zxcv', foo: 'bar', }; - var now = new Date(); + const now = new Date(); rest.create(config, auth.nobody(config), '_User', user) .then((r) => { @@ -389,9 +389,9 @@ describe('rest create', () => { .then((r) => { expect(r.results.length).toEqual(1); - var session = r.results[0]; - var actual = new Date(session.expiresAt.iso); - var expected = new Date(now.getTime() + (1000 * 3600 * 24 * 365)); + const session = r.results[0]; + const actual = new Date(session.expiresAt.iso); + const expected = new Date(now.getTime() + (1000 * 3600 * 24 * 365)); expect(actual.getFullYear()).toEqual(expected.getFullYear()); expect(actual.getMonth()).toEqual(expected.getMonth()); @@ -404,12 +404,12 @@ describe('rest create', () => { }); it("test specified session length", (done) => { - var user = { + const user = { username: 'asdf', password: 'zxcv', foo: 'bar', }; - var sessionLength = 3600, // 1 Hour ahead + const sessionLength = 3600, // 1 Hour ahead now = new Date(); // For reference later config.sessionLength = sessionLength; @@ -425,9 +425,9 @@ describe('rest create', () => { .then((r) => { expect(r.results.length).toEqual(1); - var session = r.results[0]; - var actual = new Date(session.expiresAt.iso); - var expected = new Date(now.getTime() + (sessionLength * 1000)); + const session = r.results[0]; + const actual = new Date(session.expiresAt.iso); + const expected = new Date(now.getTime() + (sessionLength * 1000)); expect(actual.getFullYear()).toEqual(expected.getFullYear()); expect(actual.getMonth()).toEqual(expected.getMonth()); @@ -443,7 +443,7 @@ describe('rest create', () => { }); it("can create a session with no expiration", (done) => { - var user = { + const user = { username: 'asdf', password: 'zxcv', foo: 'bar' @@ -462,7 +462,7 @@ describe('rest create', () => { .then((r) => { expect(r.results.length).toEqual(1); - var session = r.results[0]; + const session = r.results[0]; expect(session.expiresAt).toBeUndefined(); done(); @@ -491,7 +491,7 @@ describe('rest create', () => { it("cannot create object in volatileClasses if not masterKey", (done) =>{ Promise.resolve() .then(() => { - rest.create(config, auth.nobody(config), '_PushStatus', {}) + return rest.create(config, auth.nobody(config), '_PushStatus', {}) }) .then((r) => { console.log(r); @@ -502,12 +502,12 @@ describe('rest create', () => { }) }); - it ('locks down session', (done) => { + it('locks down session', (done) => { let currentUser; Parse.User.signUp('foo', 'bar').then((user) => { currentUser = user; const sessionToken = user.getSessionToken(); - var headers = { + const headers = { 'Content-Type': 'application/octet-stream', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -599,6 +599,7 @@ describe('rest create', () => { describe('rest update', () => { it('ignores createdAt', done => { + const config = Config.get('test'); const nobody = auth.nobody(config); const className = 'Foo'; const newCreatedAt = new Date('1970-01-01T00:00:00.000Z'); @@ -619,10 +620,7 @@ describe('rest update', () => { const updatedObject = res2.results[0]; expect(new Date(updatedObject.createdAt)).not.toEqual(newCreatedAt); done(); - }).then(done).catch(err => { - fail(err); - done(); - }); + }).then(done).catch(done.fail); }); }); diff --git a/spec/schemas.spec.js b/spec/schemas.spec.js index ed85d1cc..b3c8453f 100644 --- a/spec/schemas.spec.js +++ b/spec/schemas.spec.js @@ -1,15 +1,15 @@ 'use strict'; -var Parse = require('parse/node').Parse; -var request = require('request'); +const Parse = require('parse/node').Parse; +const request = require('request'); const rp = require('request-promise'); -var dd = require('deep-diff'); -var Config = require('../src/Config'); +const dd = require('deep-diff'); +const Config = require('../src/Config'); -var config; +let config; -var hasAllPODobject = () => { - var obj = new Parse.Object('HasAllPOD'); +const hasAllPODobject = () => { + const obj = new Parse.Object('HasAllPOD'); obj.set('aNumber', 5); obj.set('aString', 'string'); obj.set('aBool', true); @@ -18,7 +18,7 @@ var hasAllPODobject = () => { obj.set('aArray', ['contents', true, 5]); obj.set('aGeoPoint', new Parse.GeoPoint({latitude: 0, longitude: 0})); obj.set('aFile', new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' })); - var objACL = new Parse.ACL(); + const objACL = new Parse.ACL(); objACL.setPublicWriteAccess(false); obj.setACL(objACL); return obj; @@ -45,7 +45,7 @@ const defaultClassLevelPermissions = { } } -var plainOldDataSchema = { +const plainOldDataSchema = { className: 'HasAllPOD', fields: { //Default fields @@ -66,7 +66,7 @@ var plainOldDataSchema = { classLevelPermissions: defaultClassLevelPermissions }; -var pointersAndRelationsSchema = { +const pointersAndRelationsSchema = { className: 'HasPointersAndRelations', fields: { //Default fields @@ -117,16 +117,16 @@ const roleSchema = { "classLevelPermissions": defaultClassLevelPermissions, } -var noAuthHeaders = { +const noAuthHeaders = { 'X-Parse-Application-Id': 'test', }; -var restKeyHeaders = { +const restKeyHeaders = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', }; -var masterKeyHeaders = { +const masterKeyHeaders = { 'X-Parse-Application-Id': 'test', 'X-Parse-Master-Key': 'test', }; @@ -184,7 +184,7 @@ describe('schemas', () => { json: true, headers: masterKeyHeaders, }, (error, response, body) => { - var expected = { + const expected = { results: [userSchema,roleSchema] }; expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined); @@ -193,11 +193,11 @@ describe('schemas', () => { }); it('responds with a list of schemas after creating objects', done => { - var obj1 = hasAllPODobject(); + const obj1 = hasAllPODobject(); obj1.save().then(savedObj1 => { - var obj2 = new Parse.Object('HasPointersAndRelations'); + const obj2 = new Parse.Object('HasPointersAndRelations'); obj2.set('aPointer', savedObj1); - var relation = obj2.relation('aRelation'); + const relation = obj2.relation('aRelation'); relation.add(obj1); return obj2.save(); }).then(() => { @@ -206,7 +206,7 @@ describe('schemas', () => { json: true, headers: masterKeyHeaders, }, (error, response, body) => { - var expected = { + const expected = { results: [userSchema,roleSchema,plainOldDataSchema,pointersAndRelationsSchema] }; expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined); @@ -216,7 +216,7 @@ describe('schemas', () => { }); it('responds with a single schema', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save().then(() => { request.get({ url: 'http://localhost:8378/1/schemas/HasAllPOD', @@ -230,7 +230,7 @@ describe('schemas', () => { }); it('treats class names case sensitively', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save().then(() => { request.get({ url: 'http://localhost:8378/1/schemas/HASALLPOD', @@ -485,7 +485,7 @@ describe('schemas', () => { }); it('refuses to put to existing fields, even if it would not be a change', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.put({ @@ -507,7 +507,7 @@ describe('schemas', () => { }); it('refuses to delete non-existent fields', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.put({ @@ -529,7 +529,7 @@ describe('schemas', () => { }); it('refuses to add a geopoint to a class that already has one', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.put({ @@ -551,7 +551,7 @@ describe('schemas', () => { }); it('refuses to add two geopoints', done => { - var obj = new Parse.Object('NewClass'); + const obj = new Parse.Object('NewClass'); obj.set('aString', 'aString'); obj.save() .then(() => { @@ -575,7 +575,7 @@ describe('schemas', () => { }); it('allows you to delete and add a geopoint in the same request', done => { - var obj = new Parse.Object('NewClass'); + const obj = new Parse.Object('NewClass'); obj.set('geo1', new Parse.GeoPoint({latitude: 0, longitude: 0})); obj.save() .then(() => { @@ -607,7 +607,7 @@ describe('schemas', () => { }); it('put with no modifications returns all fields', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.put({ @@ -732,8 +732,8 @@ describe('schemas', () => { }); it('lets you delete multiple fields and check schema', done => { - var simpleOneObject = () => { - var obj = new Parse.Object('SimpleOne'); + const simpleOneObject = () => { + const obj = new Parse.Object('SimpleOne'); obj.set('aNumber', 5); obj.set('aString', 'string'); obj.set('aBool', true); @@ -773,7 +773,7 @@ describe('schemas', () => { }); it('lets you delete multiple fields and add fields', done => { - var obj1 = hasAllPODobject(); + const obj1 = hasAllPODobject(); obj1.save() .then(() => { request.put({ @@ -813,9 +813,9 @@ describe('schemas', () => { }, classLevelPermissions: defaultClassLevelPermissions }); - var obj2 = new Parse.Object('HasAllPOD'); + const obj2 = new Parse.Object('HasAllPOD'); obj2.set('aNewPointer', obj1); - var relation = obj2.relation('aNewRelation'); + const relation = obj2.relation('aNewRelation'); relation.add(obj1); obj2.save().then(done); //Just need to make sure saving works on the new object. }); @@ -823,7 +823,7 @@ describe('schemas', () => { }); it('will not delete any fields if the additions are invalid', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.put({ @@ -864,7 +864,7 @@ describe('schemas', () => { }); it('refuses to delete non-empty collection', done => { - var obj = hasAllPODobject(); + const obj = hasAllPODobject(); obj.save() .then(() => { request.del({ @@ -907,12 +907,12 @@ describe('schemas', () => { }); it('deletes collections including join tables', done => { - var obj = new Parse.Object('MyClass'); + const obj = new Parse.Object('MyClass'); obj.set('data', 'data'); obj.save() .then(() => { - var obj2 = new Parse.Object('MyOtherClass'); - var relation = obj2.relation('aRelation'); + const obj2 = new Parse.Object('MyOtherClass'); + const relation = obj2.relation('aRelation'); relation.add(obj); return obj2.save(); }) @@ -1642,7 +1642,7 @@ describe('schemas', () => { setPermissionsOnClass('AClass', { 'addField': {} }).then(() => { - var obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); obj.set('key', 'value'); return obj.save(null, {useMasterKey: true}) }).then((obj) => { diff --git a/spec/support/jasmine.json b/spec/support/jasmine.json index e0347ebf..3f247853 100644 --- a/spec/support/jasmine.json +++ b/spec/support/jasmine.json @@ -6,5 +6,6 @@ "helpers": [ "../node_modules/babel-core/register.js", "helper.js" - ] + ], + "random": false } diff --git a/spec/testing-routes.js b/spec/testing-routes.js index 187fcb8f..ac982ffc 100644 --- a/spec/testing-routes.js +++ b/spec/testing-routes.js @@ -4,14 +4,14 @@ import * as middlewares from '../src/middlewares'; import { ParseServer } from '../src/index'; import { Parse } from 'parse/node'; -var express = require('express'), +const express = require('express'), cryptoUtils = require('../src/cryptoUtils'); -var router = express.Router(); +const router = express.Router(); // creates a unique app in the cache, with a collection prefix function createApp(req, res) { - var appId = cryptoUtils.randomHexString(32); + const appId = cryptoUtils.randomHexString(32); ParseServer({ databaseURI: 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase', @@ -20,7 +20,7 @@ function createApp(req, res) { serverURL: Parse.serverURL, collectionPrefix: appId }); - var keys = { + const keys = { 'application_id': appId, 'client_key' : 'unused', 'windows_key' : 'unused',