<commit_before>module.exports = function(config) {
  var detectBrowsers = {
    enabled: false,
    usePhantomJS: false
  };

  }

  // If no browsers are specified, we enable `karma-detect-browsers`
  // this will detect all browsers that are available for testing
  if (!config.browsers.length) {
    detectBrowsers.enabled = true;
  }

  config.set({
    basePath: '..',
    frameworks: ['qunit', 'detectBrowsers'],
    files: [
      'node_modules/video.js/dist/video-js.css',
      'node_modules/sinon/pkg/sinon.js',
      'node_modules/video.js/dist/video.js',
      'test/dist/bundle.js'
    ],
    detectBrowsers: detectBrowsers,
    preprocessors: {
      'test/dist/**/*.js': ['coverage'],
    },
    reporters: ['coverage','dots'],
    // Coverage reporter outputs a nicely formated HTML coverage
    // report, as well as an XML report in Clover format for
    // Bamboo to consume
    coverageReporter: {
      dir : 'test/coverage/',
      includeAllSources: true,
      reporters: [
        {type: 'html', subdir: 'report'},
        {type: 'clover', subdir: '.', file: 'report-clover.xml'},
        {type: 'lcov', subdir: '.'}
      ]
    },
    port: 9876,
    colors: true,
    autoWatch: false,
    singleRun: true,
    concurrency: Infinity
  });
};
<commit_msg>ci: skip Chromium testing on GitHub Actions. Temporarily fixes #596<commit_after>module.exports = function(config) {
  var detectBrowsers = {
    enabled: false,
    usePhantomJS: false
  };

  // On GitHub Actions with Ubuntu 20, both Chromium and Chrome are provided, but
  // only Chrome is launchable. See https://github.com/amclin/videojs-scene7/issues/596
  // TODO: Remove this so Chromium is tested as well
  if (process.env.GITHUB_ACTIONS) {
    config.browsers = ['Firefox', 'Chrome']
  }

  // If no browsers are specified, we enable `karma-detect-browsers`
  // this will detect all browsers that are available for testing
  if (!config.browsers.length) {
    detectBrowsers.enabled = true;
  }

  config.set({
    basePath: '..',
    frameworks: ['qunit', 'detectBrowsers'],
    files: [
      'node_modules/video.js/dist/video-js.css',
      'node_modules/sinon/pkg/sinon.js',
      'node_modules/video.js/dist/video.js',
      'test/dist/bundle.js'
    ],
    detectBrowsers: detectBrowsers,
    preprocessors: {
      'test/dist/**/*.js': ['coverage'],
    },
    reporters: ['coverage','dots'],
    // Coverage reporter outputs a nicely formated HTML coverage
    // report, as well as an XML report in Clover format for
    // Bamboo to consume
    coverageReporter: {
      dir : 'test/coverage/',
      includeAllSources: true,
      reporters: [
        {type: 'html', subdir: 'report'},
        {type: 'clover', subdir: '.', file: 'report-clover.xml'},
        {type: 'lcov', subdir: '.'}
      ]
    },
    port: 9876,
    colors: true,
    autoWatch: false,
    singleRun: true,
    concurrency: Infinity
  });
};
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-03-28 using
// generator-karma 0.9.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      'bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js',
      'bower_components/angular-translate-storage-local/angular-translate-storage-local.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-ui-utils/ui-utils.js',
      'bower_components/angular-ui-select/dist/select.js',
      'bower_components/jquery-ui/ui/jquery-ui.js',
      'bower_components/moment/moment.js',
      'bower_components/fullcalendar/dist/fullcalendar.js',
      'bower_components/angular-ui-calendar/src/calendar.js',
      'bower_components/angular-ui-grid/ui-grid.js',
      'bower_components/angular-xeditable/dist/js/xeditable.js',
      'bower_components/ng-grid/build/ng-grid.js',
      'bower_components/ngstorage/ngStorage.js',
      'bower_components/textAngular/dist/textAngular.min.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/bootstrap-wysiwyg/bootstrap-wysiwyg.js',
      'bower_components/datatables/media/js/jquery.dataTables.js',
      'bower_components/footable/js/footable.js',
      'bower_components/screenfull/dist/screenfull.js',
      'bower_components/bootstrap-daterangepicker/daterangepicker.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>adapt test<commit_after>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-03-28 using
// generator-karma 0.9.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      'bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js',
      'bower_components/angular-translate-storage-local/angular-translate-storage-local.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-ui-utils/ui-utils.js',
      'bower_components/angular-ui-select/dist/select.js',
      'bower_components/moment/moment.js',
      'bower_components/fullcalendar/dist/fullcalendar.js',
      'bower_components/angular-ui-calendar/src/calendar.js',
      'bower_components/angular-ui-grid/ui-grid.js',
      'bower_components/angular-xeditable/dist/js/xeditable.js',
      'bower_components/ng-grid/build/ng-grid.js',
      'bower_components/ngstorage/ngStorage.js',
      'bower_components/textAngular/dist/textAngular.min.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/bootstrap-wysiwyg/bootstrap-wysiwyg.js',
      'bower_components/datatables/media/js/jquery.dataTables.js',
      'bower_components/footable/js/footable.js',
      'bower_components/screenfull/dist/screenfull.js',
      'bower_components/bootstrap-daterangepicker/daterangepicker.js',
      'bower_components/lodash/lodash.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<|endoftext|>


<commit_before>module.exports = function (config) {
  config.set({
    basePath: '..',
    frameworks: ['jasmine'],
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/tinymce/tinymce.min.js',
      'src/tinymce.js',
      {pattern: 'bower_components/tinymce/themes/modern/theme.min.js', served: true},
      'test/*.spec.js'
    ],
    singleRun: false,
    autoWatch: true,
    browsers: [ 'Chrome' ],
  });
};<commit_msg>Add two css files to karma.conf.js to remove warnings<commit_after>module.exports = function (config) {
  config.set({
    basePath: '..',
    frameworks: ['jasmine'],
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/tinymce/tinymce.min.js',
      'src/tinymce.js',
      'test/*.spec.js',
      {pattern: 'bower_components/tinymce/themes/modern/theme.min.js', served: true},
      {pattern: 'bower_components/tinymce/skins/lightgray/content.min.css', served: true},
      {pattern: 'bower_components/tinymce/skins/lightgray/skin.min.css', served: true}
    ],
    singleRun: false,
    autoWatch: true,
    browsers: [ 'Chrome' ],
  });
};<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        client: {
            jasmine: {
                random: false
            }
        },

        browserify: {
            debug: true,
            transform: [
                [
                    require('babelify'),
                    {
                        global: true,
                        presets: ['@babel/preset-env'],
                        ignore: [
                            '../src/classic/libs/**',
                            '../test/libs/**',
                            '../node_modules/mapbox-gl/**',
                            '../node_modules/three/**',
                            '../node_modules/xlsx/**',
                            '../node_modules/@turf/**',
                            '../node_modules/lodash/**'
                        ],
                        plugins: ['istanbul']
                    }
                ],
                [require('browserify-css'), { global: true }],
                require('browserify-imgify')
            ]
        },
        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            './resources/img/**.png',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            { pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-17729.js', include: false },
            { pattern: '../src/classic/libs/Lang/*.js', include: false },
            { pattern: '../src/classic/theme/default/*.css', include: false },
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/
            './test-main-common.js',

            /***leaflet的源码***/
            { pattern: './libs/workers/TurfWorkerForTest.js', include: false },
            { pattern: '../node_modules/leaflet/dist/leaflet.css', include: false },
            { pattern: '../src/leaflet/**/**/*.css', include: false },
            '../src/leaflet/**/!(index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            { pattern: '../node_modules/ol/ol.css', include: false },
            { pattern: '../src/openlayers/**/**/*.css', include: false },
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            { pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false },
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            './tool/utils.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-17729.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            // './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            // './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(index).js': ['browserify'],
            // './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/ol/*.js': ['browserify'],
            '../node_modules/ol/**/*.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            // './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            // './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [{ type: 'lcov', subdir: '.' }]
        },
        sonarQubeUnitReporter: {
            sonarQubeVersion: 'LATEST',
            outputFile: 'testcoverage/ut_report.xml',
            useBrowserName: false
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
};
<commit_msg>Update karma.conf.js<commit_after>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        client: {
            jasmine: {
                random: false
            }
        },

        browserify: {
            debug: true,
            transform: [
                [
                    require('babelify'),
                    {
                        global: true,
                        presets: ['@babel/preset-env'],
                        ignore: [
                            '../src/classic/libs/**',
                            '../test/libs/**',
                            '../node_modules/mapbox-gl/**',
                            '../node_modules/three/**',
                            '../node_modules/xlsx/**',
                            '../node_modules/@turf/**',
                            '../node_modules/lodash/**'
                        ],
                        plugins: ['istanbul']
                    }
                ],
                [require('browserify-css'), { global: true }],
                require('browserify-imgify')
            ]
        },
        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            './resources/img/**.png',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            { pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-17729.js', include: false },
            { pattern: '../src/classic/libs/Lang/*.js', include: false },
            { pattern: '../src/classic/theme/default/*.css', include: false },
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/
            './test-main-common.js',

            /***leaflet的源码***/
            { pattern: './libs/workers/TurfWorkerForTest.js', include: false },
            { pattern: '../node_modules/leaflet/dist/leaflet.css', include: false },
            { pattern: '../src/leaflet/**/**/*.css', include: false },
            '../src/leaflet/**/!(index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            { pattern: '../node_modules/ol/ol.css', include: false },
            { pattern: '../src/openlayers/**/**/*.css', include: false },
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            { pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false },
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            './tool/utils.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-17729.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            // './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            // './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(index).js': ['browserify'],
            // './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/ol/*.js': ['browserify'],
            '../node_modules/ol/**/*.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            // './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            // './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [{ type: 'lcov', subdir: '.' }]
        },
//         sonarQubeUnitReporter: {
//             sonarQubeVersion: 'LATEST',
//             outputFile: 'testcoverage/ut_report.xml',
//             useBrowserName: false
//         },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
};
<|endoftext|>


<commit_before>var plugin = angular.module("CDPipeline", ['ui.bootstrap', 'ngAnimate']);<commit_msg>fix for IE 9+ cache preventing reloads<commit_after>var plugin = angular.module("CDPipeline", ['ui.bootstrap', 'ngAnimate']);

//used to prevent IE caching which blocks live updates
plugin.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
}]);<|endoftext|>


<commit_before>module.exports = function (config) {
	config.set({
		basePath : '',
		frameworks: ['jasmine', 'requirejs'],
//	        files: [
//			'../lib/**/*.js',
//			'../test/spec/*.js'
//	        ],
        exclude: [
			'lib/requireconfig.js',
			'test/karma.conf.js'
        ],
		browsers : ['PhantomJS'],
		reporters : ['progress', 'spec', 'coverage', 'html'],
		preprocessors: {
			'../lib/**/*.js': 'coverage'
		},
		coverageReporter: {
			type : 'text'//,
			//dir : 'coverage/'
		},
		htmlReporter: {
			outputFile: 'results/unit-tests.html'
		},
		singleRun: true,
		plugins : [
			'karma-spec-reporter',
			'karma-phantomjs-launcher',
			'karma-jasmine',
			'karma-coverage',
			'karma-htmlfile-reporter'
		]
	});
};
<commit_msg>include requirejs as plugin<commit_after>module.exports = function (config) {
	config.set({
		basePath : '',
		frameworks: ['jasmine', 'requirejs'],
//	        files: [
//			'../lib/**/*.js',
//			'../test/spec/*.js'
//	        ],
        exclude: [
			'lib/requireconfig.js',
			'test/karma.conf.js'
        ],
		browsers : ['PhantomJS'],
		reporters : ['progress', 'spec', 'coverage', 'html'],
		preprocessors: {
			'../lib/**/*.js': 'coverage'
		},
		coverageReporter: {
			type : 'text'//,
			//dir : 'coverage/'
		},
		htmlReporter: {
			outputFile: 'results/unit-tests.html'
		},
		singleRun: true,
		plugins : [
			'karma-spec-reporter',
			'karma-phantomjs-launcher',
			'karma-jasmine',
			'karma-coverage',
            'karma-htmlfile-reporter',
            'karma-requirejs'
		]
	});
};
<|endoftext|>


<commit_before>const playwright = require('playwright');
const webpack = require('webpack');

let build = `material-ui local ${new Date().toISOString()}`;

if (process.env.CIRCLE_BUILD_URL) {
  build = process.env.CIRCLE_BUILD_URL;
}

const browserStack = {
  username: process.env.BROWSERSTACK_USERNAME,
  accessKey: process.env.BROWSERSTACK_ACCESS_KEY,
  build,
};

process.env.CHROME_BIN = playwright.chromium.executablePath();

// Karma configuration
module.exports = function setKarmaConfig(config) {
  const baseConfig = {
    basePath: '../',
    browsers: ['chromeHeadless'],
    browserDisconnectTimeout: 120000, // default 2000
    browserDisconnectTolerance: 1, // default 0
    browserNoActivityTimeout: 6 * 60 * 1000, // default 10000
    colors: true,
    client: {
      mocha: {
        // Some BrowserStack browsers can be slow.
        timeout: (process.env.CIRCLECI === 'true' ? 4 : 2) * 1000,
      },
    },
    frameworks: ['mocha'],
    files: [
      {
        pattern: 'test/karma.tests.js',
        watched: true,
        served: true,
        included: true,
      },
      {
        pattern: 'test/assets/*.png',
        watched: false,
        included: false,
        served: true,
      },
    ],
    plugins: ['karma-mocha', 'karma-chrome-launcher', 'karma-sourcemap-loader', 'karma-webpack'],
    /**
     * possible values:
     * - config.LOG_DISABLE
     * - config.LOG_ERROR
     * - config.LOG_WARN
     * - config.LOG_INFO
     * - config.LOG_DEBUG
     */
    logLevel: config.LOG_INFO,
    port: 9876,
    preprocessors: {
      'test/karma.tests.js': ['webpack', 'sourcemap'],
    },
    proxies: {
      '/fake.png': '/base/test/assets/fake.png',
      '/fake2.png': '/base/test/assets/fake2.png',
    },
    reporters: ['dots'],
    webpack: {
      mode: 'development',
      devtool: 'inline-source-map',
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test'),
          'process.env.CI': JSON.stringify(process.env.CI),
          'process.env.KARMA': JSON.stringify(true),
          'process.env.TEST_GATE': JSON.stringify(process.env.TEST_GATE),
        }),
      ],
      module: {
        rules: [
          {
            test: /\.(js|ts|tsx)$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            options: {
              envName: 'stable',
            },
          },
        ],
      },
      node: {
        // Some tests import fs
        fs: 'empty',
      },
      resolve: {
        extensions: ['.js', '.ts', '.tsx'],
      },
    },
    webpackMiddleware: {
      noInfo: true,
      writeToDisk: Boolean(process.env.CI),
    },
    customLaunchers: {
      chromeHeadless: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox'],
      },
    },
    singleRun: Boolean(process.env.CI),
  };

  let newConfig = baseConfig;

  if (browserStack.accessKey) {
    newConfig = {
      ...baseConfig,
      browserStack,
      browsers: baseConfig.browsers.concat(['chrome', 'firefox', 'safari', 'edge']),
      plugins: baseConfig.plugins.concat(['karma-browserstack-launcher']),
      customLaunchers: {
        ...baseConfig.customLaunchers,
        chrome: {
          base: 'BrowserStack',
          os: 'OS X',
          os_version: 'Catalina',
          browser: 'chrome',
          browser_version: '84.0',
        },
        firefox: {
          base: 'BrowserStack',
          os: 'Windows',
          os_version: '10',
          browser: 'firefox',
          browser_version: '78.0',
        },
        safari: {
          base: 'BrowserStack',
          os: 'OS X',
          os_version: 'Catalina',
          browser: 'safari',
          // We support 12.2 on iOS.
          // However, 12.1 is very flaky on desktop (mobile is always flaky).
          browser_version: '13.0',
        },
        edge: {
          base: 'BrowserStack',
          os: 'Windows',
          os_version: '10',
          browser: 'edge',
          browser_version: '85.0',
        },
      },
    };
  }

  config.set(newConfig);
};
<commit_msg>[test] Reduce compile time of test:karma in watchmode drastically (#24967)<commit_after>const playwright = require('playwright');
const webpack = require('webpack');

const CI = Boolean(process.env.CI);

let build = `material-ui local ${new Date().toISOString()}`;

if (process.env.CIRCLE_BUILD_URL) {
  build = process.env.CIRCLE_BUILD_URL;
}

const browserStack = {
  username: process.env.BROWSERSTACK_USERNAME,
  accessKey: process.env.BROWSERSTACK_ACCESS_KEY,
  build,
};

process.env.CHROME_BIN = playwright.chromium.executablePath();

// Karma configuration
module.exports = function setKarmaConfig(config) {
  const baseConfig = {
    basePath: '../',
    browsers: ['chromeHeadless'],
    browserDisconnectTimeout: 120000, // default 2000
    browserDisconnectTolerance: 1, // default 0
    browserNoActivityTimeout: 6 * 60 * 1000, // default 10000
    colors: true,
    client: {
      mocha: {
        // Some BrowserStack browsers can be slow.
        timeout: (process.env.CIRCLECI === 'true' ? 4 : 2) * 1000,
      },
    },
    frameworks: ['mocha'],
    files: [
      {
        pattern: 'test/karma.tests.js',
        watched: true,
        served: true,
        included: true,
      },
      {
        pattern: 'test/assets/*.png',
        watched: false,
        included: false,
        served: true,
      },
    ],
    plugins: ['karma-mocha', 'karma-chrome-launcher', 'karma-sourcemap-loader', 'karma-webpack'],
    /**
     * possible values:
     * - config.LOG_DISABLE
     * - config.LOG_ERROR
     * - config.LOG_WARN
     * - config.LOG_INFO
     * - config.LOG_DEBUG
     */
    logLevel: config.LOG_INFO,
    port: 9876,
    preprocessors: {
      'test/karma.tests.js': ['webpack', 'sourcemap'],
    },
    proxies: {
      '/fake.png': '/base/test/assets/fake.png',
      '/fake2.png': '/base/test/assets/fake2.png',
    },
    reporters: ['dots'],
    webpack: {
      mode: 'development',
      devtool: CI ? 'inline-source-map' : 'eval-source-map',
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test'),
          'process.env.CI': JSON.stringify(process.env.CI),
          'process.env.KARMA': JSON.stringify(true),
          'process.env.TEST_GATE': JSON.stringify(process.env.TEST_GATE),
        }),
      ],
      module: {
        rules: [
          {
            test: /\.(js|ts|tsx)$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            options: {
              envName: 'stable',
            },
          },
        ],
      },
      node: {
        // Some tests import fs
        fs: 'empty',
      },
      resolve: {
        extensions: ['.js', '.ts', '.tsx'],
      },
    },
    webpackMiddleware: {
      noInfo: true,
      writeToDisk: CI,
    },
    customLaunchers: {
      chromeHeadless: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox'],
      },
    },
    singleRun: CI,
  };

  let newConfig = baseConfig;

  if (browserStack.accessKey) {
    newConfig = {
      ...baseConfig,
      browserStack,
      browsers: baseConfig.browsers.concat(['chrome', 'firefox', 'safari', 'edge']),
      plugins: baseConfig.plugins.concat(['karma-browserstack-launcher']),
      customLaunchers: {
        ...baseConfig.customLaunchers,
        chrome: {
          base: 'BrowserStack',
          os: 'OS X',
          os_version: 'Catalina',
          browser: 'chrome',
          browser_version: '84.0',
        },
        firefox: {
          base: 'BrowserStack',
          os: 'Windows',
          os_version: '10',
          browser: 'firefox',
          browser_version: '78.0',
        },
        safari: {
          base: 'BrowserStack',
          os: 'OS X',
          os_version: 'Catalina',
          browser: 'safari',
          // We support 12.2 on iOS.
          // However, 12.1 is very flaky on desktop (mobile is always flaky).
          browser_version: '13.0',
        },
        edge: {
          base: 'BrowserStack',
          os: 'Windows',
          os_version: '10',
          browser: 'edge',
          browser_version: '85.0',
        },
      },
    };
  }

  config.set(newConfig);
};
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-07-06 using
// generator-karma 0.8.3

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'src/**/**/*.js',
      'test/spec/**/*.js',
      'test/spec/**/**/*.js'
    ],

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    reporters: ['coverage'],
    //files to coverage
    preprocessors: {
      "src/**/*js": "coverage"
    },

    coverageReporter: {
      type: "lcov",
      dir: "test/coverage/"
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // cli runner port
    runnerPort: 9100,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-coverage'
    ],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>travis<commit_after>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-07-06 using
// generator-karma 0.8.3

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'src/**/**/*.js',
      'test/spec/**/*.js'
    ],

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    reporters: ['coverage'],
    //files to coverage
    preprocessors: {
      "src/**/*js": "coverage"
    },

    coverageReporter: {
      type: "lcov",
      dir: "test/coverage/"
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // cli runner port
    runnerPort: 9100,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-coverage'
    ],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Nov 09 2015 18:53:12 GMT+0530 (IST)

module.exports = function (config) {
    var configuration = {

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'browserify'],

        // list of files / patterns to load in the browser
        files: [
            '../index.js',
            '../test/unit/**/*.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../index.js': ['browserify'], // Mention path as per your test js folder
            '../test/unit/**/*.js': ['browserify'] // Mention path as per your library js folder
        },
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['mocha'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // one of: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_WARN,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Concurrency level
        // how many browser should be started simultanous
        concurrency: Infinity,

        // Uncomment "karma-browserify" if you see an error like this:
        // Error: No provider for "framework:browserify"! (Resolving: framework:browserify)
        plugins: [
            'karma-mocha',
            'karma-chrome-launcher',
            'karma-browserify',
            'karma-mocha-reporter'
        ],

        // Pass options to the client frameworks.
        client: {
            mocha: {
                timeout: 10000 // 10 seconds
            }
        }
    };

    if (process.env.TRAVIS) { // eslint-disable-line no-process-env
        configuration.customLaunchers = {
            chromeTravis: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        };
        configuration.browsers = ['chromeTravis'];
    }

    config.set(configuration);
};
<commit_msg>Fixed build issues on Node v8<commit_after>// Karma configuration
// Generated on Mon Nov 09 2015 18:53:12 GMT+0530 (IST)

module.exports = function (config) {
    var configuration = {

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'browserify'],

        // list of files / patterns to load in the browser
        files: [
            '../index.js',
            '../test/unit/**/*.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../index.js': ['browserify'], // Mention path as per your test js folder
            '../test/unit/**/*.js': ['browserify'] // Mention path as per your library js folder
        },
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['mocha'],

        // web server port
        port: 9876,

        // the number of milliseconds to wait for an idle browser to come back up before bailing
        browserNoActivityTimeout: 20000,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // one of: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_WARN,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['ChromeHeadless'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Concurrency level
        // how many browser should be started simultanous
        concurrency: Infinity,

        // Uncomment "karma-browserify" if you see an error like this:
        // Error: No provider for "framework:browserify"! (Resolving: framework:browserify)
        plugins: [
            'karma-mocha',
            'karma-chrome-launcher',
            'karma-browserify',
            'karma-mocha-reporter'
        ],

        // Pass options to the client frameworks.
        client: {
            mocha: {
                timeout: 10000 // 10 seconds
            }
        }
    };

    if (process.env.TRAVIS) { // eslint-disable-line no-process-env
        configuration.customLaunchers = {
            chromeTravis: {
                base: 'ChromeHeadless',
                flags: ['--no-sandbox']
            }
        };
        configuration.browsers = ['chromeTravis'];
    }

    config.set(configuration);
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                require('browserify-css'),
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-15626.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/!(index).js',
            /**测试文件**/
            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(GraphicLayer|WebGLRenderer|index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(Graphic|WebGLRenderer|index|MapboxStyles).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(GraphicLayer|index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'

        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-15626.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/!(index).js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(GraphicLayer|WebGLRenderer|index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(Graphic|WebGLRenderer|index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(GraphicLayer|index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<commit_msg>fix UT<commit_after>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                require('browserify-css'),
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-15626.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/
            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(GraphicLayer|WebGLRenderer|index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(Graphic|WebGLRenderer|index|MapboxStyles).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(GraphicLayer|index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'

        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-15626.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(GraphicLayer|WebGLRenderer|index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(Graphic|WebGLRenderer|index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(GraphicLayer|index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<|endoftext|>


<commit_before>import Kasen from "../src/kasen";
import KasenArray from "../src/collection/array";
import KasenObject from "../src/collection/object";

describe("Kasen", () => {
  test("ok", () => {
    expect(Kasen([])).toBeInstanceOf(KasenArray);
    expect(Kasen({})).toBeInstanceOf(KasenObject);
  });

  test("error", () => {
    expect(() => Kasen()).toThrow(TypeError);
    expect(() => Kasen(null)).toThrow(TypeError);
  });

  describe("copy()", () => {
    test("error", () => {
      expect(() => Kasen.copy()).toThrow(TypeError);
      expect(() => Kasen.copy(null)).toThrow(TypeError);
    });
  });
});
<commit_msg>Add tests for validation of collection<commit_after>import Kasen from "../src/kasen";
import KasenArray from "../src/collection/array";
import KasenObject from "../src/collection/object";

describe("Kasen", () => {
  test("ok", () => {
    expect(Kasen([])).toBeInstanceOf(KasenArray);
    expect(Kasen({})).toBeInstanceOf(KasenObject);
  });

  test("error", () => {
    expect(() => Kasen()).toThrow(TypeError);
    expect(() => Kasen(null)).toThrow(TypeError);
  });

  describe("copy()", () => {
    test("error", () => {
      expect(() => Kasen.copy()).toThrow(TypeError);
      expect(() => Kasen.copy(null)).toThrow(TypeError);
    });
  });

  describe("isEmpty()", () => {
    test("error", () => {
      expect(() => Kasen.isEmpty()).toThrow(TypeError);
      expect(() => Kasen.isEmpty(null)).toThrow(TypeError);
    });
  });

  describe("toArray()", () => {
    test("error", () => {
      expect(() => Kasen.toArray()).toThrow(TypeError);
      expect(() => Kasen.toArray(null)).toThrow(TypeError);
    });
  });

  describe("toObject()", () => {
    test("error", () => {
      expect(() => Kasen.toObject()).toThrow(TypeError);
      expect(() => Kasen.toObject(null)).toThrow(TypeError);
    });
  });

  describe("keys()", () => {
    test("error", () => {
      expect(() => Kasen.keys()).toThrow(TypeError);
      expect(() => Kasen.keys(null)).toThrow(TypeError);
    });
  });

  describe("values()", () => {
    test("error", () => {
      expect(() => Kasen.values()).toThrow(TypeError);
      expect(() => Kasen.values(null)).toThrow(TypeError);
    });
  });

  describe("entries()", () => {
    test("error", () => {
      expect(() => Kasen.entries()).toThrow(TypeError);
      expect(() => Kasen.entries(null)).toThrow(TypeError);
    });
  });
});
<|endoftext|>


<commit_before>import {
    findModel,
} from 'mobx-decorated-models';
import invariant from 'invariant';
import {
    isEmpty, isNil, find, extend, assign, pick,
} from 'lodash';

import { action, observable, computed } from 'mobx';

import pluralize from 'pluralize';

import Sync from './sync';
import Config from '../config';
import ModelCollection from './collection';

export {
    identifiedBy, belongsTo, hasMany,
} from 'mobx-decorated-models';
export {
    action, autorun,
} from 'mobx';
export {
    field, session, identifier,
} from './decorators';

export {
    observable, computed,
};

export class BaseModel {

    static findDerived(name) {
        return findModel(name);
    }

    static get assignableKeys() {
        return this.$schema.keys();
    }

    static get propertyOptions() {
        const options = {};
        this.$schema.forEach((val, name) => (options[name] = val.options));
        return options;
    }

    static get syncUrl() {
        invariant(this.identifiedBy, 'must have an identifiedBy property in order to calulate syncUrl');
        return `${Config.api_path}/${pluralize(this.identifiedBy)}`;
    }

    static get identifierName() {
        const field = find(this.$schema.values(), { type: 'identifier' });
        invariant(field, 'identifierName called on a model that has not designated one with `@identifier`');
        return field.name;
    }

    static get Collection() {
        return this.$collection || (this.$collection = new ModelCollection(this));
    }

    constructor(attrs) {
        if (!isEmpty(attrs)) { this.set(attrs); }
    }

    @observable syncInProgress = false;
    @observable lastServerMessage = '';
    @observable errors = {};

    @computed get isValid() {
        return isNil(this.errors) || isEmpty(this.errors);
    }

    @computed get isNew() {
        return isNil(this.identifier);
    }

    @computed get identifier() {
        return this[this.constructor.identifierName];
    }

    @computed get syncUrl() {
        const path = this.constructor.syncUrl;
        return this.isNew ? path : `${path}/${this.identifier}`;
    }

    set(attrs) {
        assign(this, pick(attrs, this.constructor.assignableKeys));
    }

    @action reset() {
        this.constructor.assignableKeys.forEach(k => (this[k] = null));
        this.constructor.replaceableKeys.forEach((key) => {
            this[key].reset();
        });
    }

    set syncData(data) {
        return this.update(data);
    }

    @computed
    get syncData() {
        return this.serialize();
    }

    fetch(options = {}) {
        invariant((!this.isNew || options.query),
                  'Unable to fetch record without it’s identifier being set or a query');
        const fetchOptions = extend(options, { limit: 1, method: 'GET' });
        if (!fetchOptions.query) {
            fetchOptions.query = { [`${this.constructor.identifierName}`]: this.identifier };
        }
        return Sync.forModel(this, fetchOptions);
    }

    save(options = {}) {
        return Sync.forModel(this, options);
    }

    destroy(options = {}) {
        return Sync.forModel(this, extend(options, { action: 'destroy' }));
    }
}

export default BaseModel;
<commit_msg>replaceable keys has been removed<commit_after>import {
    findModel,
} from 'mobx-decorated-models';
import invariant from 'invariant';
import {
    isEmpty, isNil, find, extend, assign, pick,
} from 'lodash';

import { action, observable, computed } from 'mobx';

import pluralize from 'pluralize';

import Sync from './sync';
import Config from '../config';
import ModelCollection from './collection';

export {
    identifiedBy, belongsTo, hasMany,
} from 'mobx-decorated-models';
export {
    action, autorun,
} from 'mobx';
export {
    field, session, identifier,
} from './decorators';

export {
    observable, computed,
};

export class BaseModel {

    static findDerived(name) {
        return findModel(name);
    }

    static get assignableKeys() {
        return this.$schema.keys();
    }

    static get propertyOptions() {
        const options = {};
        this.$schema.forEach((val, name) => (options[name] = val.options));
        return options;
    }

    static get syncUrl() {
        invariant(this.identifiedBy, 'must have an identifiedBy property in order to calulate syncUrl');
        return `${Config.api_path}/${pluralize(this.identifiedBy)}`;
    }

    static get identifierName() {
        const field = find(this.$schema.values(), { type: 'identifier' });
        invariant(field, 'identifierName called on a model that has not designated one with `@identifier`');
        return field.name;
    }

    static get Collection() {
        return this.$collection || (this.$collection = new ModelCollection(this));
    }

    constructor(attrs) {
        if (!isEmpty(attrs)) { this.set(attrs); }
    }

    @observable syncInProgress = false;
    @observable lastServerMessage = '';
    @observable errors = {};

    @computed get isValid() {
        return isNil(this.errors) || isEmpty(this.errors);
    }

    @computed get isNew() {
        return isNil(this.identifier);
    }

    @computed get identifier() {
        return this[this.constructor.identifierName];
    }

    @computed get syncUrl() {
        const path = this.constructor.syncUrl;
        return this.isNew ? path : `${path}/${this.identifier}`;
    }

    set(attrs) {
        assign(this, pick(attrs, this.constructor.assignableKeys));
    }

    @action reset() {
        this.constructor.assignableKeys.forEach(k => (this[k] = null));
    }

    set syncData(data) {
        return this.update(data);
    }

    @computed
    get syncData() {
        return this.serialize();
    }

    fetch(options = {}) {
        invariant((!this.isNew || options.query),
                  'Unable to fetch record without it’s identifier being set or a query');
        const fetchOptions = extend(options, { limit: 1, method: 'GET' });
        if (!fetchOptions.query) {
            fetchOptions.query = { [`${this.constructor.identifierName}`]: this.identifier };
        }
        return Sync.forModel(this, fetchOptions);
    }

    save(options = {}) {
        return Sync.forModel(this, options);
    }

    destroy(options = {}) {
        return Sync.forModel(this, extend(options, { action: 'destroy' }));
    }
}

export default BaseModel;
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Bar, Doughnut, Line, Pie, Polar, Radar } from "react-chartjs-2";
import { Nav, NavItem, NavLink } from "reactstrap";
import { JSON_AUTHORIZATION_HEADERS } from "../constants/util_constants";
import moment from "moment";
import {
  CHARTS_BACKGROUND_COLOR,
  DataAnalyticsRow,
  DefaultLineChartDataset
} from "../constants/charts";

const SleepHistoryChart = {
  labels: [],
  datasets: [Object.assign({}, DefaultLineChartDataset)]
};

const SupplementsCorrelationsChart = {
  labels: [],
  datasets: [
    {
      label: "Sleep Correlation",
      backgroundColor: CHARTS_BACKGROUND_COLOR,
      borderColor: CHARTS_BACKGROUND_COLOR,
      borderWidth: 1,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: []
    }
  ]
};

const ActivitiesCorrelationsChart = {
  labels: [],
  datasets: [
    {
      label: "Sleep Correlation",
      backgroundColor: CHARTS_BACKGROUND_COLOR,
      borderColor: CHARTS_BACKGROUND_COLOR,
      borderWidth: 1,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: []
    }
  ]
};

class SleepAnalyticsView extends Component {
  constructor() {
    super();
    this.state = {
      sleepHistory: SleepHistoryChart,
      //
      supplementsCorrelationsChart: SupplementsCorrelationsChart,
      selectedSupplementsCorrelations: [],
      selectedSupplementsCorrelationsTab: "Positively Correlated",
      positiveSupplementsCorrelations: [],
      negativeSupplementsCorrelations: [],
      //
      selectedUserActivityCorrelationsChart: ActivitiesCorrelationsChart,
      selectedUserActivitiesCorrelations: [],
      selectedUserActivitiesCorrelationsTab: "Positively Correlated",
      positiveUserActivitiesCorrelations: [],
      negativeUserActivitiesCorrelations: []
    };
    this.selectSupplementsCorrelationsTab = this.selectSupplementsCorrelationsTab.bind(
      this
    );
    this.selectUserActivitiesCorrelationsTab = this.selectUserActivitiesCorrelationsTab.bind(
      this
    );
  }

  componentDidMount() {
    this.getHistory();
    this.getSupplementsCorrelations();
    this.getUserActivitiesCorrelations();
  }

  selectSupplementsCorrelationsTab(event) {
    event.preventDefault();

    const target = event.target;
    const name = target.name;

    if (name === "Positively Correlated") {
      this.setState({
        selectedSupplementsCorrelations: this.state
          .positiveSupplementsCorrelations
      });
    } else if (name === "Negatively Correlated") {
      this.setState({
        selectedSupplementsCorrelations: this.state
          .negativeSupplementsCorrelations
      });
    }

    this.setState({
      selectedSupplementsCorrelationsTab: name
    });
  }

  selectUserActivitiesCorrelationsTab(event) {
    event.preventDefault();

    const target = event.target;
    const name = target.name;

    if (name === "Positively Correlated") {
      this.setState({
        selectedUserActivitiesCorrelations: this.state
          .positiveUserActivitiesCorrelations
      });
    } else if (name === "Negatively Correlated") {
      this.setState({
        selectedUserActivitiesCorrelations: this.state
          .negativeUserActivitiesCorrelations
      });
    }

    this.setState({
      selectedUserActivitiesCorrelationsTab: name
    });
  }

  //
  // API Calls
  //
  getSupplementsCorrelations() {
    fetch(`api/v1/sleep_activities/supplements/correlations`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        const labels = responseData.map(data => {
          return data[0];
        });
        const dataValues = responseData.map(data => {
          return data[1];
        });

        this.state.supplementsCorrelationsChart.labels = labels;
        this.state.supplementsCorrelationsChart.datasets[0].data = dataValues;

        const positivelyCorrelatedSupplements = responseData.filter(data => {
          return data[1] > 0;
        });
        const negativelyCorrelatedSupplements = responseData.filter(data => {
          return data[1] < 0;
        });

        // Finally update state after we've done so much magic
        this.setState({
          supplementsCorrelationsChart: this.state.supplementsCorrelationsChart,
          selectedSupplementsCorrelations: positivelyCorrelatedSupplements,
          positiveSupplementsCorrelations: positivelyCorrelatedSupplements,
          negativeSupplementsCorrelations: negativelyCorrelatedSupplements
        });
      });
  }

  getUserActivitiesCorrelations() {
    fetch(`api/v1/sleep_activities/user_activities/correlations`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        const labels = responseData.map(data => {
          return data[0];
        });
        const dataValues = responseData.map(data => {
          return data[1];
        });

        this.state.selectedUserActivityCorrelationsChart.labels = labels;
        this.state.selectedUserActivityCorrelationsChart.datasets[
          0
        ].data = dataValues;

        const positivelyCorrelatedActivities = responseData.filter(data => {
          return data[1] > 0;
        });
        const negativelyCorrelatedActivities = responseData.filter(data => {
          return data[1] < 0;
        });

        // Finally update state after we've done so much magic
        this.setState({
          selectedUserActivityCorrelationsChart: this.state
            .supplementsCorrelationsChart,
          selectedUserActivitiesCorrelations: positivelyCorrelatedActivities,
          positiveUserActivitiesCorrelations: positivelyCorrelatedActivities,
          negativeUserActivitiesCorrelations: negativelyCorrelatedActivities
        });
      });
  }

  getHistory() {
    fetch(`api/v1/sleep_activities/aggregates`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        // Sort by datetime
        const sleepDates = Object.keys(responseData);
        sleepDates.sort();

        const sleepDatesFormatted = sleepDates.map(key =>
          moment(key).format("MMMM D YYYY")
        );

        const dataParsed = sleepDates.map(key => responseData[key] / 60);

        this.state.sleepHistory.labels = sleepDatesFormatted;
        this.state.sleepHistory.datasets[0].data = dataParsed;

        // Reset the historicalState of the graph after the data has been grabbed.
        this.setState({ sleepHistory: this.state.sleepHistory });
      });
  }

  renderSupplementsCorrelationSelectionTab(tabName) {
    if (this.state.selectedSupplementsCorrelationsTab === tabName) {
      return (
        <NavItem className="selected-modal">
          <NavLink>
            {tabName}
          </NavLink>
        </NavItem>
      );
    }
    return (
      <NavItem className="default-background">
        <NavLink onClick={this.selectSupplementsCorrelationsTab} name={tabName}>
          {tabName}
        </NavLink>
      </NavItem>
    );
  }

  renderActivitiesCorrelationSelectionTab(tabName) {
    if (this.state.selectedUserActivitiesCorrelationsTab === tabName) {
      return (
        <NavItem className="selected-modal">
          <NavLink>
            {tabName}
          </NavLink>
        </NavItem>
      );
    }
    return (
      <NavItem className="default-background">
        <NavLink
          onClick={this.selectUserActivitiesCorrelationsTab}
          name={tabName}
        >
          {tabName}
        </NavLink>
      </NavItem>
    );
  }

  renderHistoryChart() {
    return (

          Sleep History

            <Line
              data={this.state.sleepHistory}
              options={{
                maintainAspectRatio: false
              }}
            />

    );
  }

  renderUserActivitiesCorrelations() {
    return (

            Activities and Sleep Correlation

              <Bar
                data={ActivitiesCorrelationsChart}
                options={{
                  maintainAspectRatio: true
                }}
              />

              {this.renderActivitiesCorrelationSelectionTab(
                "Positively Correlated"
              )}
              {this.renderActivitiesCorrelationSelectionTab(
                "Negatively Correlated"
              )}

                    Activity
                    Correlation

                  {this.state.selectedUserActivitiesCorrelations.map(key => (
                    <DataAnalyticsRow key={key} object={key} />
                  ))}

    );
  }

  renderSupplementsCorrelations() {
    return (

            Supplements and Sleep Correlation

              <Bar
                data={SupplementsCorrelationsChart}
                options={{
                  maintainAspectRatio: true
                }}
              />

              {this.renderSupplementsCorrelationSelectionTab(
                "Positively Correlated"
              )}
              {this.renderSupplementsCorrelationSelectionTab(
                "Negatively Correlated"
              )}

                    Supplement
                    Correlation

                  {this.state.selectedSupplementsCorrelations.map(key => (
                    <DataAnalyticsRow key={key} object={key} />
                  ))}

    );
  }

  render() {
    return (

        {this.renderHistoryChart()}
        {this.renderSupplementsCorrelations()}
        {this.renderUserActivitiesCorrelations()}
        {/*Hold off on Historical Sleep Analytics, No one has 90 Days of History Yet*/}
        {/*{this.renderHistoricalSleepAnalytics()}*/}

    );
  }
}

export default SleepAnalyticsView;

// const AverageSleepHistoryChart = {
//   labels: [],
//   datasets: [
//     {
//       label: "Average Sleep (Hours)",
//       backgroundColor: CHARTS_BACKGROUND_COLOR,
//       borderColor: "rgb(74, 86, 104)",
//       borderWidth: 1,
//       hoverBackgroundColor: "rgba(255,99,132,0.4)",
//       hoverBorderColor: "rgba(255,99,132,1)",
//       data: []
//     }
//   ]
// };

// renderHistoricalSleepAnalytics() {
//   return (
//

//

//

//           Daily Sleep Analytics
//

//

//

//

//             <Bar
//               data={AverageSleepHistoryChart}
//               options={{
//                 maintainAspectRatio: false
//               }}
//             />
//

//

//

//

//

//
//             {this.renderAnalyticsHistorySelectionTab(
//               "Full Historical Lookback"
//             )}
//             {this.renderAnalyticsHistorySelectionTab("7 Day")}
//             {this.renderAnalyticsHistorySelectionTab("14 Day")}
//             {this.renderAnalyticsHistorySelectionTab("30 Day")}
//             {this.renderAnalyticsHistorySelectionTab("90 Day")}
//
//

//

//

//

//                   Weekday
//                   Average Sleep
//

//

//

//

//                   Monday
//                   6 hours 53 minutes
//

//

//

//

//

//

//

//   );
// }

// renderAnalyticsHistorySelectionTab(tabName) {
//   if (this.state.selectedAnalyticsTab === tabName) {
//     return (
//       <NavItem className="selected-modal">
//         <NavLink>
//           {tabName}
//         </NavLink>
//       </NavItem>
//     );
//   }
//   return (
//     <NavItem className="default-background">
//       <NavLink
//         onClick={this.selectAnalyticsHistoryLookbackTab}
//         name={tabName}
//       >
//         {tabName}
//       </NavLink>
//     </NavItem>
//   );
// }

// selectAnalyticsHistoryLookbackTab(event) {
//   event.preventDefault();
//
//   const target = event.target;
//   const name = target.name;
//
//   this.setState({
//     selectedAnalyticsTab: name
//   });
// }
<commit_msg>Standardize Chart Labels<commit_after>import React, { Component } from "react";
import { Bar, Doughnut, Line, Pie, Polar, Radar } from "react-chartjs-2";
import { Nav, NavItem, NavLink } from "reactstrap";
import { JSON_AUTHORIZATION_HEADERS } from "../constants/util_constants";
import moment from "moment";
import {
  CHARTS_BACKGROUND_COLOR,
  DataAnalyticsRow,
  DefaultLineChartDataset
} from "../constants/charts";

const SleepHistoryChart = {
  labels: [],
  datasets: [Object.assign({}, DefaultLineChartDataset)]
};

const SupplementsCorrelationsChart = {
  labels: [],
  datasets: [
    {
      label: "Sleep Correlation",
      backgroundColor: CHARTS_BACKGROUND_COLOR,
      borderColor: CHARTS_BACKGROUND_COLOR,
      borderWidth: 1,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: []
    }
  ]
};

const ActivitiesCorrelationsChart = {
  labels: [],
  datasets: [
    {
      label: "Sleep Correlation",
      backgroundColor: CHARTS_BACKGROUND_COLOR,
      borderColor: CHARTS_BACKGROUND_COLOR,
      borderWidth: 1,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: []
    }
  ]
};

class SleepAnalyticsView extends Component {
  constructor() {
    super();
    this.state = {
      sleepHistory: SleepHistoryChart,
      //
      supplementsCorrelationsChart: SupplementsCorrelationsChart,
      selectedSupplementsCorrelations: [],
      selectedSupplementsCorrelationsTab: "Positively Correlated",
      positiveSupplementsCorrelations: [],
      negativeSupplementsCorrelations: [],
      //
      selectedUserActivityCorrelationsChart: ActivitiesCorrelationsChart,
      selectedUserActivitiesCorrelations: [],
      selectedUserActivitiesCorrelationsTab: "Positively Correlated",
      positiveUserActivitiesCorrelations: [],
      negativeUserActivitiesCorrelations: []
    };
    this.selectSupplementsCorrelationsTab = this.selectSupplementsCorrelationsTab.bind(
      this
    );
    this.selectUserActivitiesCorrelationsTab = this.selectUserActivitiesCorrelationsTab.bind(
      this
    );
  }

  componentDidMount() {
    this.getHistory();
    this.getSupplementsCorrelations();
    this.getUserActivitiesCorrelations();
  }

  selectSupplementsCorrelationsTab(event) {
    event.preventDefault();

    const target = event.target;
    const name = target.name;

    if (name === "Positively Correlated") {
      this.setState({
        selectedSupplementsCorrelations: this.state
          .positiveSupplementsCorrelations
      });
    } else if (name === "Negatively Correlated") {
      this.setState({
        selectedSupplementsCorrelations: this.state
          .negativeSupplementsCorrelations
      });
    }

    this.setState({
      selectedSupplementsCorrelationsTab: name
    });
  }

  selectUserActivitiesCorrelationsTab(event) {
    event.preventDefault();

    const target = event.target;
    const name = target.name;

    if (name === "Positively Correlated") {
      this.setState({
        selectedUserActivitiesCorrelations: this.state
          .positiveUserActivitiesCorrelations
      });
    } else if (name === "Negatively Correlated") {
      this.setState({
        selectedUserActivitiesCorrelations: this.state
          .negativeUserActivitiesCorrelations
      });
    }

    this.setState({
      selectedUserActivitiesCorrelationsTab: name
    });
  }

  //
  // API Calls
  //
  getSupplementsCorrelations() {
    fetch(`api/v1/sleep_activities/supplements/correlations`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        const labels = responseData.map(data => {
          return data[0];
        });
        const dataValues = responseData.map(data => {
          return data[1];
        });

        this.state.supplementsCorrelationsChart.labels = labels;
        this.state.supplementsCorrelationsChart.datasets[0].data = dataValues;

        const positivelyCorrelatedSupplements = responseData.filter(data => {
          return data[1] > 0;
        });
        const negativelyCorrelatedSupplements = responseData.filter(data => {
          return data[1] < 0;
        });

        // Finally update state after we've done so much magic
        this.setState({
          supplementsCorrelationsChart: this.state.supplementsCorrelationsChart,
          selectedSupplementsCorrelations: positivelyCorrelatedSupplements,
          positiveSupplementsCorrelations: positivelyCorrelatedSupplements,
          negativeSupplementsCorrelations: negativelyCorrelatedSupplements
        });
      });
  }

  getUserActivitiesCorrelations() {
    fetch(`api/v1/sleep_activities/user_activities/correlations`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        const labels = responseData.map(data => {
          return data[0];
        });
        const dataValues = responseData.map(data => {
          return data[1];
        });

        this.state.selectedUserActivityCorrelationsChart.labels = labels;
        this.state.selectedUserActivityCorrelationsChart.datasets[
          0
        ].data = dataValues;

        const positivelyCorrelatedActivities = responseData.filter(data => {
          return data[1] > 0;
        });
        const negativelyCorrelatedActivities = responseData.filter(data => {
          return data[1] < 0;
        });

        // Finally update state after we've done so much magic
        this.setState({
          selectedUserActivityCorrelationsChart: this.state
            .supplementsCorrelationsChart,
          selectedUserActivitiesCorrelations: positivelyCorrelatedActivities,
          positiveUserActivitiesCorrelations: positivelyCorrelatedActivities,
          negativeUserActivitiesCorrelations: negativelyCorrelatedActivities
        });
      });
  }

  getHistory() {
    fetch(`api/v1/sleep_activities/aggregates`, {
      method: "GET",
      headers: JSON_AUTHORIZATION_HEADERS
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        // Sort by datetime
        const sleepDates = Object.keys(responseData);
        sleepDates.sort();

        const sleepDatesFormatted = sleepDates.map(key =>
          moment(key).format("MMMM D YYYY")
        );

        const dataParsed = sleepDates.map(key => responseData[key] / 60);

        this.state.sleepHistory.labels = sleepDatesFormatted;
        this.state.sleepHistory.datasets[0].data = dataParsed;

        // Reset the historicalState of the graph after the data has been grabbed.
        this.setState({ sleepHistory: this.state.sleepHistory });
      });
  }

  renderSupplementsCorrelationSelectionTab(tabName) {
    if (this.state.selectedSupplementsCorrelationsTab === tabName) {
      return (
        <NavItem className="selected-modal">
          <NavLink>
            {tabName}
          </NavLink>
        </NavItem>
      );
    }
    return (
      <NavItem className="default-background">
        <NavLink onClick={this.selectSupplementsCorrelationsTab} name={tabName}>
          {tabName}
        </NavLink>
      </NavItem>
    );
  }

  renderActivitiesCorrelationSelectionTab(tabName) {
    if (this.state.selectedUserActivitiesCorrelationsTab === tabName) {
      return (
        <NavItem className="selected-modal">
          <NavLink>
            {tabName}
          </NavLink>
        </NavItem>
      );
    }
    return (
      <NavItem className="default-background">
        <NavLink
          onClick={this.selectUserActivitiesCorrelationsTab}
          name={tabName}
        >
          {tabName}
        </NavLink>
      </NavItem>
    );
  }

  renderHistoryChart() {
    return (

          Sleep History

            <Line
              data={this.state.sleepHistory}
              options={{
                maintainAspectRatio: false
              }}
            />

    );
  }

  renderUserActivitiesCorrelations() {
    return (

            Activities and Sleep Correlation

              <Bar
                data={ActivitiesCorrelationsChart}
                options={{
                  maintainAspectRatio: true
                }}
              />

              {this.renderActivitiesCorrelationSelectionTab(
                "Positively Correlated"
              )}
              {this.renderActivitiesCorrelationSelectionTab(
                "Negatively Correlated"
              )}

                    Activity
                    Correlation

                  {this.state.selectedUserActivitiesCorrelations.map(key => (
                    <DataAnalyticsRow key={key} object={key} />
                  ))}

    );
  }

  renderSupplementsCorrelations() {
    return (

            Supplements and Sleep Correlation

              <Bar
                data={SupplementsCorrelationsChart}
                options={{
                  maintainAspectRatio: true
                }}
              />

              {this.renderSupplementsCorrelationSelectionTab(
                "Positively Correlated"
              )}
              {this.renderSupplementsCorrelationSelectionTab(
                "Negatively Correlated"
              )}

                    Supplement
                    Correlation

                  {this.state.selectedSupplementsCorrelations.map(key => (
                    <DataAnalyticsRow key={key} object={key} />
                  ))}

    );
  }

  render() {
    return (

        {this.renderHistoryChart()}
        {this.renderSupplementsCorrelations()}
        {this.renderUserActivitiesCorrelations()}
        {/*Hold off on Historical Sleep Analytics, No one has 90 Days of History Yet*/}
        {/*{this.renderHistoricalSleepAnalytics()}*/}

    );
  }
}

export default SleepAnalyticsView;

// const AverageSleepHistoryChart = {
//   labels: [],
//   datasets: [
//     {
//       label: "Average Sleep (Hours)",
//       backgroundColor: CHARTS_BACKGROUND_COLOR,
//       borderColor: "rgb(74, 86, 104)",
//       borderWidth: 1,
//       hoverBackgroundColor: "rgba(255,99,132,0.4)",
//       hoverBorderColor: "rgba(255,99,132,1)",
//       data: []
//     }
//   ]
// };

// renderHistoricalSleepAnalytics() {
//   return (
//

//

//

//           Daily Sleep Analytics
//

//

//

//

//             <Bar
//               data={AverageSleepHistoryChart}
//               options={{
//                 maintainAspectRatio: false
//               }}
//             />
//

//

//

//

//

//
//             {this.renderAnalyticsHistorySelectionTab(
//               "Full Historical Lookback"
//             )}
//             {this.renderAnalyticsHistorySelectionTab("7 Day")}
//             {this.renderAnalyticsHistorySelectionTab("14 Day")}
//             {this.renderAnalyticsHistorySelectionTab("30 Day")}
//             {this.renderAnalyticsHistorySelectionTab("90 Day")}
//
//

//

//

//

//                   Weekday
//                   Average Sleep
//

//

//

//

//                   Monday
//                   6 hours 53 minutes
//

//

//

//

//

//

//

//   );
// }

// renderAnalyticsHistorySelectionTab(tabName) {
//   if (this.state.selectedAnalyticsTab === tabName) {
//     return (
//       <NavItem className="selected-modal">
//         <NavLink>
//           {tabName}
//         </NavLink>
//       </NavItem>
//     );
//   }
//   return (
//     <NavItem className="default-background">
//       <NavLink
//         onClick={this.selectAnalyticsHistoryLookbackTab}
//         name={tabName}
//       >
//         {tabName}
//       </NavLink>
//     </NavItem>
//   );
// }

// selectAnalyticsHistoryLookbackTab(event) {
//   event.preventDefault();
//
//   const target = event.target;
//   const name = target.name;
//
//   this.setState({
//     selectedAnalyticsTab: name
//   });
// }
<|endoftext|>