解决travis ci 中chrome找不到的办法

写一些react插件,大家会引入CI集成测试。这样有助于开源项目的质量。尤其引入了karma 进行浏览器的自动测试。

自己写react.js的开源组件的时候用的是 Airbnb Enzyme + Karma的测试环境。这个时候我们需要调用chrome测试,通常我们在 karma.conf.js 指定 browsers 参数为['chrome']。但是在CI的测试环境中。会提示

 Cannot load browser "[Chrome]": it is not registered! Perhaps you are missing some plugin?

这个时候需要我们对测试环境做个判断重新指定浏览器,参考如下:

const path = require('path');

let browsers = ['Chrome'];
// trvis env

if (process.env.TRAVIS) {
  browsers = ['Chrome_travis_ci'];
}


module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      './tests/**/*.js'
    ],
    preprocessors: {
      // add webpack as preprocessor
      'src/**/*.js': ['webpack', 'sourcemap'],
      'tests/**/*.test.js': ['webpack', 'sourcemap']
    },
    // webpack file
    webpack: { 
      devtool: 'inline-source-map', //just do inline source maps instead of the default
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel',
            exclude: path.resolve(__dirname, 'node_modules'),
            query: {
              presets: ['airbnb']
            }
          },
          {
            test: /\.json$/,
            loader: 'json',
          },
        ]
      },
      externals: {
        'react/addons': true,
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
      }
    },

    webpackServer: {
      noInfo: true //please don't spam the console when running in karma!
    },

    plugins: [
      'karma-webpack',
      'karma-jasmine',
      'karma-sourcemap-loader',
      'karma-chrome-launcher',
    ],

    babelPreprocessor: {
      options: {
        presets: ['airbnb']
      }
    },
    // custom launchers 
    customLaunchers: {
        Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    },
    reporters: ['progress'],
    // port: 9002,
    logLevel: config.LOG_INFO,
    browsers: browsers,
    singleRun: false,
  })
};

你在你的 .travis.yml 中需要提前安装chrome浏览器:

language: node_js
node_js:
  - 5.0
  - 6.0
  - 7.0
script: node_modules/karma/bin/karma start ./karma.conf.js --singleRun
before_install:
  - export CHROME_BIN=chromium-browser
  - export DISPLAY=:99.0
  - sh -e /etc/init.d/xvfb start

最后大家就可以提交测试一下了。

大家配置可以参考这个项目reactjs-percentage-circle