Przeglądaj źródła

apply to src/test dir

Yuki Takei 7 lat temu
rodzic
commit
3544d9f94a

+ 36 - 14
.eslintrc.js

@@ -18,15 +18,33 @@ module.exports = {
     hljs: true,
     hljs: true,
     window: true,
     window: true,
   },
   },
-  plugins: ['react'],
+  plugins: [
+    'react',
+    'chai-friendly',
+  ],
   rules: {
   rules: {
     "arrow-body-style": ["error", "always"],
     "arrow-body-style": ["error", "always"],
     "brace-style": [
     "brace-style": [
       "error",
       "error",
-      "stroustrup", { "allowSingleLine": true }
+      "stroustrup",
+      { "allowSingleLine": true },
     ],
     ],
     "global-require": 'off',
     "global-require": 'off',
-    "key-spacing": ['error', { 'mode': 'minimum' }],
+    "key-spacing": [
+      'error',
+      { 'mode': 'minimum' }
+    ],
+    "max-len": ['error',
+      {
+        code: 160,
+        ignoreTrailingComments: true
+      }
+    ],
+    "no-plusplus": [
+      "error",
+      { "allowForLoopAfterthoughts": true }
+    ],
+    "prefer-destructuring": 'off',
     // "comma-spacing": [
     // "comma-spacing": [
     //   "error",
     //   "error",
     //   { "before": false, "after": true }
     //   { "before": false, "after": true }
@@ -35,17 +53,18 @@ module.exports = {
     //   "error",
     //   "error",
     //   "never"
     //   "never"
     // ],
     // ],
-    // "indent": [
-    //   "error",
-    //   2,
-    //   {
-    //     "SwitchCase": 1,
-    //     "ignoredNodes": ['JSXElement *', 'JSXElement', "JSXAttribute", "JSXSpreadAttribute"],
-    //     "FunctionDeclaration": {"body": 1, "parameters": 2},
-    //     "FunctionExpression": {"body": 1, "parameters": 2},
-    //     "MemberExpression": "off"
-    //   }
-    // ],
+    "indent": [
+      "error",
+      2,
+      {
+        "SwitchCase": 1,
+        "ignoredNodes": ['JSXElement *', 'JSXElement', "JSXAttribute", "JSXSpreadAttribute"],
+        "ArrayExpression": "first",
+        "FunctionDeclaration": {"body": 1, "parameters": 2},
+        "FunctionExpression": {"body": 1, "parameters": 2},
+        "MemberExpression": "off"
+      }
+    ],
     // "key-spacing": [
     // "key-spacing": [
     //   "error", {
     //   "error", {
     //     "beforeColon": false,
     //     "beforeColon": false,
@@ -87,5 +106,8 @@ module.exports = {
     "import/no-extraneous-dependencies": 'off',
     "import/no-extraneous-dependencies": 'off',
     "import/no-dynamic-require": 'off',
     "import/no-dynamic-require": 'off',
     "import/no-unresolved": [2, { ignore: ['^@'] }],  // ignore @alias/..., @commons/..., ...
     "import/no-unresolved": [2, { ignore: ['^@'] }],  // ignore @alias/..., @commons/..., ...
+    // eslint-plugin-chai-friendly rules
+    "no-unused-expressions": 0,
+    "chai-friendly/no-unused-expressions": 2,
   },
   },
 };
 };

+ 2 - 1
package.json

@@ -32,7 +32,7 @@
     "clean:report": "rimraf -- report",
     "clean:report": "rimraf -- report",
     "clean": "npm-run-all -p clean:*",
     "clean": "npm-run-all -p clean:*",
     "heroku-postbuild": "sh bin/heroku/install-plugins.sh && npm run build:prod",
     "heroku-postbuild": "sh bin/heroku/install-plugins.sh && npm run build:prod",
-    "lint:js:fix": "eslint . --fix",
+    "lint:js:fix": "eslint src/test --fix",
     "lint:js": "eslint .",
     "lint:js": "eslint .",
     "lint:styles:fix": "prettier-stylelint --quiet --write src/client/styles/scss/**/*.scss",
     "lint:styles:fix": "prettier-stylelint --quiet --write src/client/styles/scss/**/*.scss",
     "lint:styles": "stylelint src/client/styles/scss/**/*.scss",
     "lint:styles": "stylelint src/client/styles/scss/**/*.scss",
@@ -155,6 +155,7 @@
     "eazy-logger": "^3.0.2",
     "eazy-logger": "^3.0.2",
     "eslint": "^5.0.0",
     "eslint": "^5.0.0",
     "eslint-config-airbnb": "^17.1.0",
     "eslint-config-airbnb": "^17.1.0",
+    "eslint-plugin-chai-friendly": "^0.4.1",
     "eslint-plugin-import": "^2.16.0",
     "eslint-plugin-import": "^2.16.0",
     "eslint-plugin-jsx-a11y": "^6.2.1",
     "eslint-plugin-jsx-a11y": "^6.2.1",
     "eslint-plugin-react": "^7.12.4",
     "eslint-plugin-react": "^7.12.4",

+ 14 - 19
src/test/bootstrap.js

@@ -1,5 +1,3 @@
-'use strict';
-
 process.env.NODE_ENV = 'test';
 process.env.NODE_ENV = 'test';
 
 
 require('module-alias/register');
 require('module-alias/register');
@@ -8,37 +6,34 @@ const helpers = require('@commons/util/helpers');
 
 
 const express = require('express');
 const express = require('express');
 
 
-let testDBUtil;
-
-testDBUtil = {
-  generateFixture: function(conn, model, fixture) {
-    if (conn.readyState == 0) {
+const testDBUtil = {
+  generateFixture(conn, model, fixture) {
+    if (conn.readyState === 0) {
       return Promise.reject();
       return Promise.reject();
     }
     }
     const m = conn.model(model);
     const m = conn.model(model);
 
 
-    return new Promise(function(resolve, reject) {
+    return new Promise(((resolve) => {
       const createdModels = [];
       const createdModels = [];
-      fixture.reduce(function(promise, entity) {
-        return promise.then(function() {
-          const newDoc = new m;
+      fixture.reduce((promise, entity) => {
+        return promise.then(() => {
+          const newDoc = new m(); // eslint-disable-line new-cap
 
 
-          Object.keys(entity).forEach(function(k) {
+          Object.keys(entity).forEach((k) => {
             newDoc[k] = entity[k];
             newDoc[k] = entity[k];
           });
           });
-          return new Promise(function(r, rj) {
-            newDoc.save(function(err, data) {
-
+          return new Promise(((r) => {
+            newDoc.save((err, data) => {
               createdModels.push(data);
               createdModels.push(data);
               return r();
               return r();
             });
             });
-          });
+          }));
         });
         });
-      }, Promise.resolve()).then(function() {
+      }, Promise.resolve()).then(() => {
         resolve(createdModels);
         resolve(createdModels);
       });
       });
-    });
-  }
+    }));
+  },
 };
 };
 
 
 global.express = express;
 global.express = express;

+ 33 - 30
src/test/crowi/crowi.test.js

@@ -1,32 +1,32 @@
-const chai = require('chai')
-  , expect = chai.expect
-  , sinonChai = require('sinon-chai')
+const chai = require('chai');
+
+const { expect } = chai;
+const sinonChai = require('sinon-chai');
+const helpers = require('@commons/util/helpers');
 
 
-  , helpers = require('@commons/util/helpers')
-  ;
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
-describe('Test for Crowi application context', function() {
-  const Crowi = require('@server/crowi')
-    , mongoose = require('mongoose')
-    ;
+describe('Test for Crowi application context', () => {
+  const Crowi = require('@server/crowi');
+
 
 
-  describe('construction', function() {
-    it('initialize crowi context', function() {
+  const mongoose = require('mongoose');
+  describe('construction', () => {
+    it('initialize crowi context', () => {
       const crowi = new Crowi(helpers.root());
       const crowi = new Crowi(helpers.root());
       expect(crowi).to.be.instanceof(Crowi);
       expect(crowi).to.be.instanceof(Crowi);
       expect(crowi.version).to.equal(require('../../../package.json').version);
       expect(crowi.version).to.equal(require('../../../package.json').version);
       expect(crowi.env).to.be.an('Object');
       expect(crowi.env).to.be.an('Object');
     });
     });
 
 
-    it('config getter, setter', function() {
+    it('config getter, setter', () => {
       const crowi = new Crowi(helpers.root());
       const crowi = new Crowi(helpers.root());
       expect(crowi.getConfig()).to.deep.equals({});
       expect(crowi.getConfig()).to.deep.equals({});
-      crowi.setConfig({test: 1});
-      expect(crowi.getConfig()).to.deep.equals({test: 1});
+      crowi.setConfig({ test: 1 });
+      expect(crowi.getConfig()).to.deep.equals({ test: 1 });
     });
     });
 
 
-    it('model getter, setter', function() {
+    it('model getter, setter', () => {
       const crowi = new Crowi(helpers.root());
       const crowi = new Crowi(helpers.root());
       // set
       // set
       crowi.model('hoge', { fuga: 1 });
       crowi.model('hoge', { fuga: 1 });
@@ -34,27 +34,30 @@ describe('Test for Crowi application context', function() {
     });
     });
   });
   });
 
 
-  describe('.setupDatabase', function() {
-    before(function() {
+  describe('.setupDatabase', () => {
+    before(() => {
       mongoose.disconnect(); // avoid error of Trying to open unclosed connection
       mongoose.disconnect(); // avoid error of Trying to open unclosed connection
     });
     });
-    it('setup completed', function(done) {
+    it('setup completed', (done) => {
       const crowi = new Crowi(helpers.root());
       const crowi = new Crowi(helpers.root());
       // set
       // set
       const p = crowi.setupDatabase();
       const p = crowi.setupDatabase();
       expect(p).to.instanceof(Promise);
       expect(p).to.instanceof(Promise);
-      p.then(function() {
-        expect(mongoose.connection.readyState).to.equals(1);
-        done();
-      }).catch(function(err) {
-        //console.log('readyState', mongoose.connection.readyState);
-        if (mongoose.connection.readyState === 2 || mongoose.connection.readyState === 1) { // alreaady connected
-          // throught
-        } else {
-          expect(mongoose.connection.readyState).to.equals(0);
-        }
-        done();
-      });
+      p
+        .then(() => {
+          expect(mongoose.connection.readyState).to.equals(1);
+          done();
+        })
+        .catch((err) => { // eslint-disable-line no-unused-vars
+          // console.log('readyState', mongoose.connection.readyState);
+          if (mongoose.connection.readyState === 2 || mongoose.connection.readyState === 1) { // alreaady connected
+            // throught
+          }
+          else {
+            expect(mongoose.connection.readyState).to.equals(0);
+          }
+          done();
+        });
     });
     });
   });
   });
 });
 });

+ 30 - 30
src/test/models/config.test.js

@@ -1,45 +1,46 @@
-var chai = require('chai')
-  , expect = chai.expect
-  , sinon = require('sinon')
-  , sinonChai = require('sinon-chai')
-  , utils = require('../utils.js')
-  ;
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+const utils = require('../utils.js');
+
+const { expect } = chai;
+
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
-describe('Config model test', function () {
-  var Page = utils.models.Page,
-    Config = utils.models.Config,
-    User   = utils.models.User,
-    conn = utils.mongoose.connection;
-
-  before(function (done) {
-    var fixture = [
-      {ns: 'crowi', key: 'test:test', value: JSON.stringify('crowi test value')},
-      {ns: 'crowi', key: 'test:test2', value: JSON.stringify(11111)},
-      {ns: 'crowi', key: 'test:test3', value: JSON.stringify([1, 2, 3, 4, 5])},
-      {ns: 'plugin', key: 'other:config', value: JSON.stringify('this is data')},
+/* global testDBUtil */
+
+
+describe('Config model test', () => {
+  const Config = utils.models.Config;
+
+  const conn = utils.mongoose.connection;
+
+  before((done) => {
+    const fixture = [
+      { ns: 'crowi', key: 'test:test', value: JSON.stringify('crowi test value') },
+      { ns: 'crowi', key: 'test:test2', value: JSON.stringify(11111) },
+      { ns: 'crowi', key: 'test:test3', value: JSON.stringify([1, 2, 3, 4, 5]) },
+      { ns: 'plugin', key: 'other:config', value: JSON.stringify('this is data') },
     ];
     ];
 
 
     testDBUtil.generateFixture(conn, 'Config', fixture)
     testDBUtil.generateFixture(conn, 'Config', fixture)
-    .then(function(configs) {
-      done();
-    }).catch(function() {
-      done(new Error('Skip this test.'));
-    });
+      .then((configs) => {  // eslint-disable-line
+        done();
+      }).catch(() => {
+        done(new Error('Skip this test.'));
+      });
   });
   });
 
 
-  describe('.CONSTANTS', function () {
-    it('Config has constants', function() {
+  describe('.CONSTANTS', () => {
+    it('Config has constants', () => {
       expect(Config.SECURITY_REGISTRATION_MODE_OPEN).to.have.string('Open');
       expect(Config.SECURITY_REGISTRATION_MODE_OPEN).to.have.string('Open');
       expect(Config.SECURITY_REGISTRATION_MODE_RESTRICTED).to.have.string('Resricted');
       expect(Config.SECURITY_REGISTRATION_MODE_RESTRICTED).to.have.string('Resricted');
       expect(Config.SECURITY_REGISTRATION_MODE_CLOSED).to.have.string('Closed');
       expect(Config.SECURITY_REGISTRATION_MODE_CLOSED).to.have.string('Closed');
     });
     });
   });
   });
 
 
-  describe('.loadAllConfig', function () {
-    it('Get config array', function(done) {
-      Config.loadAllConfig(function(err, config) {
-
+  describe('.loadAllConfig', () => {
+    it('Get config array', (done) => {
+      Config.loadAllConfig((err, config) => {
         expect(config.crowi).to.be.an('Object');
         expect(config.crowi).to.be.an('Object');
         expect(config.crowi).to.have.property('test:test')
         expect(config.crowi).to.have.property('test:test')
           .and.equal('crowi test value');
           .and.equal('crowi test value');
@@ -58,4 +59,3 @@ describe('Config model test', function () {
     });
     });
   });
   });
 });
 });
-

+ 56 - 62
src/test/models/page.test.js

@@ -1,18 +1,20 @@
-const chai = require('chai')
-  , expect = chai.expect
-  , sinonChai = require('sinon-chai')
-  , utils = require('../utils.js')
-  ;
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+const utils = require('../utils.js');
+
+const { expect } = chai;
+const testDBUtil = global.testDBUtil;
+
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
 describe('Page', () => {
 describe('Page', () => {
-  const Page = utils.models.Page,
-    User   = utils.models.User,
-    conn   = utils.mongoose.connection;
+  const Page = utils.models.Page;
+  const User = utils.models.User;
+  const conn = utils.mongoose.connection;
 
 
-  let createdPages,
-    createdUsers,
-    createdUserGroups;
+  let createdPages;
+  let createdUsers;
+  let createdUserGroups;
 
 
   before(async() => {
   before(async() => {
     await conn.collection('pages').remove();
     await conn.collection('pages').remove();
@@ -49,7 +51,7 @@ describe('Page', () => {
       {
       {
         relatedGroup: testGroup0,
         relatedGroup: testGroup0,
         relatedUser: testUser1,
         relatedUser: testUser1,
-      }
+      },
     ];
     ];
     await testDBUtil.generateFixture(conn, 'UserGroupRelation', userGroupRelationFixture);
     await testDBUtil.generateFixture(conn, 'UserGroupRelation', userGroupRelationFixture);
 
 
@@ -58,19 +60,19 @@ describe('Page', () => {
         path: '/user/anonymous0/memo',
         path: '/user/anonymous0/memo',
         grant: Page.GRANT_RESTRICTED,
         grant: Page.GRANT_RESTRICTED,
         grantedUsers: [testUser0],
         grantedUsers: [testUser0],
-        creator: testUser0
+        creator: testUser0,
       },
       },
       {
       {
         path: '/grant/public',
         path: '/grant/public',
         grant: Page.GRANT_PUBLIC,
         grant: Page.GRANT_PUBLIC,
         grantedUsers: [testUser0],
         grantedUsers: [testUser0],
-        creator: testUser0
+        creator: testUser0,
       },
       },
       {
       {
         path: '/grant/restricted',
         path: '/grant/restricted',
         grant: Page.GRANT_RESTRICTED,
         grant: Page.GRANT_RESTRICTED,
         grantedUsers: [testUser0],
         grantedUsers: [testUser0],
-        creator: testUser0
+        creator: testUser0,
       },
       },
       {
       {
         path: '/grant/specified',
         path: '/grant/specified',
@@ -88,7 +90,7 @@ describe('Page', () => {
         path: '/page/for/extended',
         path: '/page/for/extended',
         grant: Page.GRANT_PUBLIC,
         grant: Page.GRANT_PUBLIC,
         creator: testUser0,
         creator: testUser0,
-        extended: {hoge: 1}
+        extended: { hoge: 1 },
       },
       },
       {
       {
         path: '/grant/groupacl',
         path: '/grant/groupacl',
@@ -114,13 +116,12 @@ describe('Page', () => {
       },
       },
     ];
     ];
     createdPages = await testDBUtil.generateFixture(conn, 'Page', fixture);
     createdPages = await testDBUtil.generateFixture(conn, 'Page', fixture);
-
   });
   });
 
 
   describe('.isPublic', () => {
   describe('.isPublic', () => {
     context('with a public page', () => {
     context('with a public page', () => {
-      it('should return true', done => {
-        Page.findOne({path: '/grant/public'}, (err, page) => {
+      it('should return true', (done) => {
+        Page.findOne({ path: '/grant/public' }, (err, page) => {
           expect(err).to.be.null;
           expect(err).to.be.null;
           expect(page.isPublic()).to.be.equal(true);
           expect(page.isPublic()).to.be.equal(true);
           done();
           done();
@@ -128,10 +129,10 @@ describe('Page', () => {
       });
       });
     });
     });
 
 
-    ['restricted', 'specified', 'owner'].forEach(grant => {
-      context('with a ' + grant + ' page', () => {
-        it('should return false', done => {
-          Page.findOne({path: '/grant/' + grant}, (err, page) => {
+    ['restricted', 'specified', 'owner'].forEach((grant) => {
+      context(`with a ${grant} page`, () => {
+        it('should return false', (done) => {
+          Page.findOne({ path: `/grant/${grant}` }, (err, page) => {
             expect(err).to.be.null;
             expect(err).to.be.null;
             expect(page.isPublic()).to.be.equal(false);
             expect(page.isPublic()).to.be.equal(false);
             done();
             done();
@@ -198,22 +199,22 @@ describe('Page', () => {
 
 
       expect(Page.isCreatableName('/ the / path / with / space')).to.be.false;
       expect(Page.isCreatableName('/ the / path / with / space')).to.be.false;
 
 
-      var forbidden = ['installer', 'register', 'login', 'logout', 'admin', 'files', 'trash', 'paste', 'comments'];
-      for (var i = 0; i < forbidden.length ; i++) {
-        var pn = forbidden[i];
-        expect(Page.isCreatableName('/' + pn + '')).to.be.false;
-        expect(Page.isCreatableName('/' + pn + '/')).to.be.false;
-        expect(Page.isCreatableName('/' + pn + '/abc')).to.be.false;
+      const forbidden = ['installer', 'register', 'login', 'logout',
+                         'admin', 'files', 'trash', 'paste', 'comments'];
+      for (let i = 0; i < forbidden.length; i++) {
+        const pn = forbidden[i];
+        expect(Page.isCreatableName(`/${pn}`)).to.be.false;
+        expect(Page.isCreatableName(`/${pn}/`)).to.be.false;
+        expect(Page.isCreatableName(`/${pn}/abc`)).to.be.false;
       }
       }
-
     });
     });
   });
   });
 
 
   describe('.isAccessiblePageByViewer', () => {
   describe('.isAccessiblePageByViewer', () => {
     context('with a granted user', () => {
     context('with a granted user', () => {
       it('should return true', async() => {
       it('should return true', async() => {
-        const user = await User.findOne({email: 'anonymous0@example.com'});
-        const page = await Page.findOne({path: '/user/anonymous0/memo'});
+        const user = await User.findOne({ email: 'anonymous0@example.com' });
+        const page = await Page.findOne({ path: '/user/anonymous0/memo' });
 
 
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         expect(bool).to.be.equal(true);
         expect(bool).to.be.equal(true);
@@ -222,8 +223,8 @@ describe('Page', () => {
 
 
     context('with a public page', () => {
     context('with a public page', () => {
       it('should return true', async() => {
       it('should return true', async() => {
-        const user = await User.findOne({email: 'anonymous1@example.com'});
-        const page = await Page.findOne({path: '/grant/public'});
+        const user = await User.findOne({ email: 'anonymous1@example.com' });
+        const page = await Page.findOne({ path: '/grant/public' });
 
 
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         expect(bool).to.be.equal(true);
         expect(bool).to.be.equal(true);
@@ -232,8 +233,8 @@ describe('Page', () => {
 
 
     context('with a restricted page and an user who has no grant', () => {
     context('with a restricted page and an user who has no grant', () => {
       it('should return false', async() => {
       it('should return false', async() => {
-        const user = await User.findOne({email: 'anonymous1@example.com'});
-        const page = await Page.findOne({path: '/grant/owner'});
+        const user = await User.findOne({ email: 'anonymous1@example.com' });
+        const page = await Page.findOne({ path: '/grant/owner' });
 
 
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         const bool = await Page.isAccessiblePageByViewer(page.id, user);
         expect(bool).to.be.equal(false);
         expect(bool).to.be.equal(false);
@@ -243,27 +244,21 @@ describe('Page', () => {
 
 
   describe('Extended field', () => {
   describe('Extended field', () => {
     context('Slack Channel.', () => {
     context('Slack Channel.', () => {
-      it('should be empty', done => {
-        Page.findOne({path: '/page/for/extended'}, (err, page) => {
+      it('should be empty', (done) => {
+        Page.findOne({ path: '/page/for/extended' }, (err, page) => {
           expect(page.extended.hoge).to.be.equal(1);
           expect(page.extended.hoge).to.be.equal(1);
           expect(page.getSlackChannel()).to.be.equal('');
           expect(page.getSlackChannel()).to.be.equal('');
           done();
           done();
-        })
-      });
-
-      it('set slack channel and should get it and should keep hoge ', done => {
-        Page.findOne({path: '/page/for/extended'}, (err, page) => {
-          page.updateSlackChannel('slack-channel1')
-          .then(data => {
-            Page.findOne({path: '/page/for/extended'}, (err, page) => {
-              expect(page.extended.hoge).to.be.equal(1);
-              expect(page.getSlackChannel()).to.be.equal('slack-channel1');
-              done();
-            });
-          })
         });
         });
       });
       });
 
 
+      it('set slack channel and should get it and should keep hoge ', async() => {
+        let page = await Page.findOne({ path: '/page/for/extended' });
+        await page.updateSlackChannel('slack-channel1');
+        page = await Page.findOne({ path: '/page/for/extended' });
+        expect(page.extended.hoge).to.be.equal(1);
+        expect(page.getSlackChannel()).to.be.equal('slack-channel1');
+      });
     });
     });
   });
   });
 
 
@@ -273,7 +268,7 @@ describe('Page', () => {
         const pageToFind = createdPages[1];
         const pageToFind = createdPages[1];
         const grantedUser = createdUsers[0];
         const grantedUser = createdUsers[0];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.not.null;
         expect(page).to.be.not.null;
         expect(page.path).to.equal(pageToFind.path);
         expect(page.path).to.equal(pageToFind.path);
       });
       });
@@ -282,7 +277,7 @@ describe('Page', () => {
         const pageToFind = createdPages[2];
         const pageToFind = createdPages[2];
         const grantedUser = createdUsers[1];
         const grantedUser = createdUsers[1];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.not.null;
         expect(page).to.be.not.null;
         expect(page.path).to.equal(pageToFind.path);
         expect(page.path).to.equal(pageToFind.path);
       });
       });
@@ -291,7 +286,7 @@ describe('Page', () => {
         const pageToFind = createdPages[4];
         const pageToFind = createdPages[4];
         const grantedUser = createdUsers[0];
         const grantedUser = createdUsers[0];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.not.null;
         expect(page).to.be.not.null;
         expect(page.path).to.equal(pageToFind.path);
         expect(page.path).to.equal(pageToFind.path);
       });
       });
@@ -300,7 +295,7 @@ describe('Page', () => {
         const pageToFind = createdPages[4];
         const pageToFind = createdPages[4];
         const grantedUser = createdUsers[1];
         const grantedUser = createdUsers[1];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.null;
         expect(page).to.be.null;
       });
       });
     });
     });
@@ -310,7 +305,7 @@ describe('Page', () => {
         const pageToFind = createdPages[6];
         const pageToFind = createdPages[6];
         const grantedUser = createdUsers[0];
         const grantedUser = createdUsers[0];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.not.null;
         expect(page).to.be.not.null;
         expect(page.path).to.equal(pageToFind.path);
         expect(page.path).to.equal(pageToFind.path);
       });
       });
@@ -319,7 +314,7 @@ describe('Page', () => {
         const pageToFind = createdPages[6];
         const pageToFind = createdPages[6];
         const grantedUser = createdUsers[2];
         const grantedUser = createdUsers[2];
 
 
-        const page = await Page.findByIdAndViewer(pageToFind._id, grantedUser);
+        const page = await Page.findByIdAndViewer(pageToFind.id, grantedUser);
         expect(page).to.be.null;
         expect(page).to.be.null;
       });
       });
     });
     });
@@ -334,7 +329,7 @@ describe('Page', () => {
       // assert totalCount
       // assert totalCount
       expect(result.totalCount).to.equal(1);
       expect(result.totalCount).to.equal(1);
       // assert paths
       // assert paths
-      const pagePaths = result.pages.map(page => page.path);
+      const pagePaths = result.pages.map((page) => { return page.path });
       expect(pagePaths).to.include.members(['/page/for/extended']);
       expect(pagePaths).to.include.members(['/page/for/extended']);
     });
     });
     it('should return only /page1/', async() => {
     it('should return only /page1/', async() => {
@@ -345,7 +340,7 @@ describe('Page', () => {
       // assert totalCount
       // assert totalCount
       expect(result.totalCount).to.equal(2);
       expect(result.totalCount).to.equal(2);
       // assert paths
       // assert paths
-      const pagePaths = result.pages.map(page => page.path);
+      const pagePaths = result.pages.map((page) => { return page.path });
       expect(pagePaths).to.include.members(['/page1', '/page1/child1']);
       expect(pagePaths).to.include.members(['/page1', '/page1/child1']);
     });
     });
   });
   });
@@ -359,7 +354,7 @@ describe('Page', () => {
       // assert totalCount
       // assert totalCount
       expect(result.totalCount).to.equal(4);
       expect(result.totalCount).to.equal(4);
       // assert paths
       // assert paths
-      const pagePaths = result.pages.map(page => page.path);
+      const pagePaths = result.pages.map((page) => { return page.path });
       expect(pagePaths).to.include.members(['/page/for/extended', '/page1', '/page1/child1', '/page2']);
       expect(pagePaths).to.include.members(['/page/for/extended', '/page1', '/page1/child1', '/page2']);
     });
     });
     it('should process with regexp', async() => {
     it('should process with regexp', async() => {
@@ -370,9 +365,8 @@ describe('Page', () => {
       // assert totalCount
       // assert totalCount
       expect(result.totalCount).to.equal(3);
       expect(result.totalCount).to.equal(3);
       // assert paths
       // assert paths
-      const pagePaths = result.pages.map(page => page.path);
+      const pagePaths = result.pages.map((page) => { return page.path });
       expect(pagePaths).to.include.members(['/page1', '/page1/child1', '/page2']);
       expect(pagePaths).to.include.members(['/page1', '/page1/child1', '/page2']);
     });
     });
   });
   });
-
 });
 });

+ 18 - 20
src/test/models/updatePost.test.js

@@ -1,18 +1,17 @@
-var chai = require('chai')
-  , expect = chai.expect
-  , sinon = require('sinon')
-  , sinonChai = require('sinon-chai')
-  , utils = require('../utils.js')
-  ;
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+
+const expect = chai.expect;
+const utils = require('../utils.js');
+
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
-describe('UpdatePost', function () {
-  var UpdatePost = utils.models.UpdatePost,
-    conn   = utils.mongoose.connection;
+describe('UpdatePost', () => {
+  const UpdatePost = utils.models.UpdatePost;
 
 
-  describe('.createPrefixesByPathPattern', function () {
-    context('with a path', function() {
-      it('should return right patternPrfixes', function(done) {
+  describe('.createPrefixesByPathPattern', () => {
+    context('with a path', () => {
+      it('should return right patternPrfixes', (done) => {
         expect(UpdatePost.createPrefixesByPathPattern('/*')).to.deep.equal(['*', '*']);
         expect(UpdatePost.createPrefixesByPathPattern('/*')).to.deep.equal(['*', '*']);
         expect(UpdatePost.createPrefixesByPathPattern('/user/*/日報*')).to.deep.equal(['user', '*']);
         expect(UpdatePost.createPrefixesByPathPattern('/user/*/日報*')).to.deep.equal(['user', '*']);
         expect(UpdatePost.createPrefixesByPathPattern('/project/hoge/*')).to.deep.equal(['project', 'hoge']);
         expect(UpdatePost.createPrefixesByPathPattern('/project/hoge/*')).to.deep.equal(['project', 'hoge']);
@@ -25,23 +24,23 @@ describe('UpdatePost', function () {
     });
     });
   });
   });
 
 
-  describe('.getRegExpByPattern', function () {
-    context('with a pattern', function() {
-      it('should return right regexp', function(done) {
+  describe('.getRegExpByPattern', () => {
+    context('with a pattern', () => {
+      it('should return right regexp', (done) => {
         expect(UpdatePost.getRegExpByPattern('/*')).to.deep.equal(/^\/.*/);
         expect(UpdatePost.getRegExpByPattern('/*')).to.deep.equal(/^\/.*/);
         expect(UpdatePost.getRegExpByPattern('/user/*/日報*')).to.deep.equal(/^\/user\/.*\/日報.*/);
         expect(UpdatePost.getRegExpByPattern('/user/*/日報*')).to.deep.equal(/^\/user\/.*\/日報.*/);
         expect(UpdatePost.getRegExpByPattern('/project/hoge/*')).to.deep.equal(/^\/project\/hoge\/.*/);
         expect(UpdatePost.getRegExpByPattern('/project/hoge/*')).to.deep.equal(/^\/project\/hoge\/.*/);
         expect(UpdatePost.getRegExpByPattern('/*/MTG/*')).to.deep.equal(/^\/.*\/MTG\/.*/);
         expect(UpdatePost.getRegExpByPattern('/*/MTG/*')).to.deep.equal(/^\/.*\/MTG\/.*/);
         expect(UpdatePost.getRegExpByPattern('自己紹介')).to.deep.equal(/^\/.*自己紹介.*/);
         expect(UpdatePost.getRegExpByPattern('自己紹介')).to.deep.equal(/^\/.*自己紹介.*/);
-        expect(UpdatePost.getRegExpByPattern('\/user\/aoi\/メモ\/2016\/02\/10\/xxx')).to.deep.equal(/^\/user\/aoi\/メモ\/2016\/02\/10\/xxx/);
+        expect(UpdatePost.getRegExpByPattern('/user/aoi/メモ/2016/02/10/xxx')).to.deep.equal(/^\/user\/aoi\/メモ\/2016\/02\/10\/xxx/);
         done();
         done();
       });
       });
     });
     });
   });
   });
 
 
-  describe('.normalizeChannelName', function () {
-    context('with a channel name', function() {
-      it('should return true', function(done) {
+  describe('.normalizeChannelName', () => {
+    context('with a channel name', () => {
+      it('should return true', (done) => {
         expect(UpdatePost.normalizeChannelName('#pj-hoge')).to.be.equal('pj-hoge');
         expect(UpdatePost.normalizeChannelName('#pj-hoge')).to.be.equal('pj-hoge');
         expect(UpdatePost.normalizeChannelName('pj-hoge')).to.be.equal('pj-hoge');
         expect(UpdatePost.normalizeChannelName('pj-hoge')).to.be.equal('pj-hoge');
 
 
@@ -50,4 +49,3 @@ describe('UpdatePost', function () {
     });
     });
   });
   });
 });
 });
-

+ 72 - 76
src/test/models/user.test.js

@@ -1,76 +1,72 @@
-var chai = require('chai')
-  , expect = chai.expect
-  , sinon = require('sinon')
-  , sinonChai = require('sinon-chai')
-  , utils = require('../utils.js')
-  ;
-chai.use(sinonChai);
-
-describe('User', function () {
-  var Page = utils.models.Page,
-    User   = utils.models.User,
-    conn   = utils.mongoose.connection;
-
-  // clear collection
-  before(done => {
-    conn.collection('users').remove()
-      .then(() => {
-        done();
-      });
-  });
-
-  describe('Create and Find.', function () {
-    context('The user', function() {
-      it('should created', function(done) {
-        User.createUserByEmailAndPassword('Aoi Miyazaki', 'aoi', 'aoi@example.com', 'hogefuga11', 'en', function (err, userData) {
-          expect(err).to.be.null;
-          expect(userData).to.instanceof(User);
-          done();
-        });
-      });
-
-      it('should be found by findUserByUsername', function(done) {
-        User.findUserByUsername('aoi')
-        .then(function(userData) {
-          expect(userData).to.instanceof(User);
-          done();
-        });
-      });
-
-      it('should be found by findUsersByPartOfEmail', function(done) {
-
-        User.findUsersByPartOfEmail('ao', {})
-        .then(function(userData) {
-          expect(userData).to.instanceof(Array);
-          expect(userData[0]).to.instanceof(User);
-          expect(userData[0].email).to.equal('aoi@example.com');
-          done();
-        });
-
-      });
-    });
-  });
-
-  describe('User Utilities', function () {
-    context('Get username from path', function() {
-      it('found', function(done) {
-        var username = null;
-        username = User.getUsernameByPath('/user/sotarok');
-        expect(username).to.equal('sotarok');
-
-        username = User.getUsernameByPath('/user/some.user.name12/'); // with slash
-        expect(username).to.equal('some.user.name12');
-
-        done();
-      });
-
-      it('not found', function(done) {
-        var username = null;
-        username = User.getUsernameByPath('/the/page/is/not/related/to/user/page');
-        expect(username).to.be.null;
-
-        done();
-      });
-    });
-  });
-});
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+const utils = require('../utils.js');
+
+const expect = chai.expect;
+chai.use(sinonChai);
+
+describe('User', () => {
+  const User = utils.models.User;
+  const conn = utils.mongoose.connection;
+
+  // clear collection
+  before((done) => {
+    conn.collection('users').remove()
+      .then(() => {
+        done();
+      });
+  });
+
+  describe('Create and Find.', () => {
+    context('The user', () => {
+      it('should created', (done) => {
+        User.createUserByEmailAndPassword('Aoi Miyazaki', 'aoi', 'aoi@example.com', 'hogefuga11', 'en', (err, userData) => {
+          expect(err).to.be.null;
+          expect(userData).to.instanceof(User);
+          done();
+        });
+      });
+
+      it('should be found by findUserByUsername', (done) => {
+        User.findUserByUsername('aoi')
+          .then((userData) => {
+            expect(userData).to.instanceof(User);
+            done();
+          });
+      });
+
+      it('should be found by findUsersByPartOfEmail', (done) => {
+        User.findUsersByPartOfEmail('ao', {})
+          .then((userData) => {
+            expect(userData).to.instanceof(Array);
+            expect(userData[0]).to.instanceof(User);
+            expect(userData[0].email).to.equal('aoi@example.com');
+            done();
+          });
+      });
+    });
+  });
+
+  describe('User Utilities', () => {
+    context('Get username from path', () => {
+      it('found', (done) => {
+        let username = null;
+        username = User.getUsernameByPath('/user/sotarok');
+        expect(username).to.equal('sotarok');
+
+        username = User.getUsernameByPath('/user/some.user.name12/'); // with slash
+        expect(username).to.equal('some.user.name12');
+
+        done();
+      });
+
+      it('not found', (done) => {
+        let username = null;
+        username = User.getUsernameByPath('/the/page/is/not/related/to/user/page');
+        expect(username).to.be.null;
+
+        done();
+      });
+    });
+  });
+});

+ 9 - 9
src/test/util/path-utils.test.js

@@ -1,30 +1,30 @@
-const chai = require('chai')
-  , expect = chai.expect
-  , sinonChai = require('sinon-chai')
-  ;
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+
+const expect = chai.expect;
+
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
 const pathUtils = require('@commons/util/path-utils');
 const pathUtils = require('@commons/util/path-utils');
 
 
 describe('page-utils', () => {
 describe('page-utils', () => {
-
   describe('.normalizePath', () => {
   describe('.normalizePath', () => {
-    it('should rurn root path with empty string', done => {
+    it('should rurn root path with empty string', (done) => {
       expect(pathUtils.normalizePath('')).to.equal('/');
       expect(pathUtils.normalizePath('')).to.equal('/');
       done();
       done();
     });
     });
 
 
-    it('should add heading slash', done => {
+    it('should add heading slash', (done) => {
       expect(pathUtils.normalizePath('hoge/fuga')).to.equal('/hoge/fuga');
       expect(pathUtils.normalizePath('hoge/fuga')).to.equal('/hoge/fuga');
       done();
       done();
     });
     });
 
 
-    it('should remove trailing slash', done => {
+    it('should remove trailing slash', (done) => {
       expect(pathUtils.normalizePath('/hoge/fuga/')).to.equal('/hoge/fuga');
       expect(pathUtils.normalizePath('/hoge/fuga/')).to.equal('/hoge/fuga');
       done();
       done();
     });
     });
 
 
-    it('should remove unnecessary slashes', done => {
+    it('should remove unnecessary slashes', (done) => {
       expect(pathUtils.normalizePath('//hoge/fuga//')).to.equal('/hoge/fuga');
       expect(pathUtils.normalizePath('//hoge/fuga//')).to.equal('/hoge/fuga');
       done();
       done();
     });
     });

+ 9 - 10
src/test/util/slack.test.js

@@ -1,22 +1,21 @@
-const chai = require('chai')
-  , expect = chai.expect
-  , sinon = require('sinon')
-  , sinonChai = require('sinon-chai')
-  , utils = require('../utils.js')
-  ;
+const chai = require('chai');
+const sinonChai = require('sinon-chai');
+
+const expect = chai.expect;
+
 chai.use(sinonChai);
 chai.use(sinonChai);
 
 
-describe('Slack Util', function () {
+describe('Slack Util', () => {
   const helpers = require('@commons/util/helpers');
   const helpers = require('@commons/util/helpers');
   const Crowi = require('@server/crowi');
   const Crowi = require('@server/crowi');
   const crowi = new Crowi(helpers.root(), process.env);
   const crowi = new Crowi(helpers.root(), process.env);
-  const slack = require(crowi.libDir + '/util/slack')(crowi);
+  const slack = require(`${crowi.libDir}/util/slack`)(crowi);
 
 
-  it('post comment method exists', function() {
+  it('post comment method exists', () => {
     expect(slack).to.respondTo('postComment');
     expect(slack).to.respondTo('postComment');
   });
   });
 
 
-  it('post page method exists', function() {
+  it('post page method exists', () => {
     expect(slack).to.respondTo('postPage');
     expect(slack).to.respondTo('postPage');
   });
   });
 });
 });

+ 22 - 22
src/test/utils.js

@@ -1,17 +1,17 @@
-'use strict';
 
 
-const mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.MONGO_URI || 'mongodb://localhost/growi_test'
-  , mongoose= require('mongoose')
-  , fs = require('fs')
-  , helpers = require('@commons/util/helpers')
-  , Crowi = require('@server/crowi')
-  , crowi = new Crowi(helpers.root(), process.env)
-  , models = {}
-  ;
+const mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.MONGO_URI || 'mongodb://localhost/growi_test';
+const mongoose = require('mongoose');
+const fs = require('fs');
+const helpers = require('@commons/util/helpers');
+const Crowi = require('@server/crowi');
+
+const crowi = new Crowi(helpers.root(), process.env);
+
+const models = {};
 
 
 mongoose.Promise = global.Promise;
 mongoose.Promise = global.Promise;
 
 
-before('Create database connection and clean up', function (done) {
+before('Create database connection and clean up', (done) => {
   if (!mongoUri) {
   if (!mongoUri) {
     return done();
     return done();
   }
   }
@@ -19,25 +19,25 @@ before('Create database connection and clean up', function (done) {
   mongoose.connect(mongoUri, { useNewUrlParser: true });
   mongoose.connect(mongoUri, { useNewUrlParser: true });
 
 
   function clearDB() {
   function clearDB() {
-    for (var i in mongoose.connection.collections) {
-      mongoose.connection.collections[i].remove(function() {});
-    }
+    Object.values(mongoose.connection.collections).forEach((collection) => {
+      collection.remove(() => {});
+    });
     return done();
     return done();
   }
   }
 
 
   if (mongoose.connection.readyState === 0) {
   if (mongoose.connection.readyState === 0) {
-    mongoose.connect(mongoUri, { useNewUrlParser: true }, function (err) {
+    mongoose.connect(mongoUri, { useNewUrlParser: true }, (err) => {
       if (err) {
       if (err) {
         throw err;
         throw err;
       }
       }
       return clearDB();
       return clearDB();
     });
     });
-  } else {
-    return clearDB();
   }
   }
+
+  return clearDB();
 });
 });
 
 
-after('Close database connection', function (done) {
+after('Close database connection', (done) => {
   if (!mongoUri) {
   if (!mongoUri) {
     return done();
     return done();
   }
   }
@@ -47,14 +47,14 @@ after('Close database connection', function (done) {
 });
 });
 
 
 // Setup Models
 // Setup Models
-fs.readdirSync(helpers.root('src/server/models')).forEach(function(file) {
+fs.readdirSync(helpers.root('src/server/models')).forEach((file) => {
   if (file.match(/^([\w-]+)\.js$/)) {
   if (file.match(/^([\w-]+)\.js$/)) {
-    let name = RegExp.$1;
+    const name = RegExp.$1;
     if (name === 'index') {
     if (name === 'index') {
       return;
       return;
     }
     }
     let modelName = '';
     let modelName = '';
-    name.split('-').map(splitted => {
+    name.split('-').forEach((splitted) => {
       modelName += (splitted.charAt(0).toUpperCase() + splitted.slice(1));
       modelName += (splitted.charAt(0).toUpperCase() + splitted.slice(1));
     });
     });
     models[modelName] = require(`@server/models/${file}`)(crowi);
     models[modelName] = require(`@server/models/${file}`)(crowi);
@@ -64,6 +64,6 @@ fs.readdirSync(helpers.root('src/server/models')).forEach(function(file) {
 crowi.models = models;
 crowi.models = models;
 
 
 module.exports = {
 module.exports = {
-  models: models,
-  mongoose: mongoose,
+  models,
+  mongoose,
 };
 };

+ 5 - 0
yarn.lock

@@ -3645,6 +3645,11 @@ eslint-module-utils@^2.3.0:
     debug "^2.6.8"
     debug "^2.6.8"
     pkg-dir "^2.0.0"
     pkg-dir "^2.0.0"
 
 
+eslint-plugin-chai-friendly@^0.4.1:
+  version "0.4.1"
+  resolved "https://registry.yarnpkg.com/eslint-plugin-chai-friendly/-/eslint-plugin-chai-friendly-0.4.1.tgz#9eeb17f92277ba80bb64f0e946c6936a3ae707b4"
+  integrity sha512-hkpLN7VVoGGsofZjUhcQ+sufC3FgqMJwD0DvAcRfxY1tVRyQyVsqpaKnToPHJQOrRo0FQ0fSEDwW2gr4rsNdGA==
+
 eslint-plugin-import@^2.16.0:
 eslint-plugin-import@^2.16.0:
   version "2.16.0"
   version "2.16.0"
   resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.16.0.tgz#97ac3e75d0791c4fac0e15ef388510217be7f66f"
   resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.16.0.tgz#97ac3e75d0791c4fac0e15ef388510217be7f66f"