Giter Club home page Giter Club logo

webpack-karma-jasmine's Introduction

Installation

This boilerplate package will let you use karma in your projects.
Use npm install webpack-karma-jasmine instead of installing all dependencies and loaders separately.

If you want to test your .html files with DOM see karma-html package.

This package is the suggestion of karma configuration. It uses:

  • karma-webpack and babel-loader to compile ES2015 javascript features and bundle specs and tests .js files together
  • karma-jasmine (to use another framework, install it manually)
  • karma-mocha-reporter bash reporter
  • karma-jasmine-html-reporter browser reporter

Sample

git clone https://github.com/devrafalko/webpack-karma-jasmine.git
cd webpack-karma-jasmine/sample
npm install
npm test

Configuration

This is the full description of the sample above.

1. Install all dependencies

npm install webpack webpack-cli webpack-karma-jasmine

2. create karma.conf.js file

The suggestion of karma.conf.js configuration

module.exports = function (config) {
  config.set({
    //root path location to resolve paths defined in files and exclude
    basePath: '',
    //files/patterns to exclude from loaded files
    exclude: [],
    //files/patterns to load in the browser
    files: [
      { pattern: 'tests/*.js', watched: true, served: true, included: true }
      /*parameters:
          watched: if autoWatch is true all files that have set watched to true will be watched for changes
          served: should the files be served by Karma's webserver?
          included: should the files be included in the browser using <script> tag?
          nocache: should the files be served from disk on each request by Karma's webserver? */
      /*assets:
          {pattern: '*.html', watched:true, served:true, included:false}
          {pattern: 'images/*', watched:false, served:true, included:false} */
    ],

    //executes the tests whenever one of watched files changes
    autoWatch: true,
    //if true, Karma will run tests and then exit browser
    singleRun: false,
    //if true, Karma fails on running empty test-suites
    failOnEmptyTestSuite: false,
    //reduce the kind of information passed to the bash
    logLevel: config.LOG_WARN, //config.LOG_DISABLE, config.LOG_ERROR, config.LOG_INFO, config.LOG_DEBUG

    //list of frameworks you want to use, only jasmine is installed with this boilerplate
    frameworks: ['jasmine'],
    //list of browsers to launch and capture
    browsers: ['Chrome'/*,'PhantomJS','Firefox','Edge','ChromeCanary','Opera','IE','Safari'*/],
    //list of reporters to use
    reporters: ['mocha', 'kjhtml'/*,'dots','progress','spec'*/],

    //address that the server will listen on, '0.0.0.0' is default
    listenAddress: '0.0.0.0',
    //hostname to be used when capturing browsers, 'localhost' is default
    hostname: 'localhost',
    //the port where the web server will be listening, 9876 is default
    port: 9876,
    //when a browser crashes, karma will try to relaunch, 2 is default
    retryLimit: 0,
    //how long does Karma wait for a browser to reconnect, 2000 is default
    browserDisconnectTimeout: 5000,
    //how long will Karma wait for a message from a browser before disconnecting from it, 10000 is default
    browserNoActivityTimeout: 10000,
    //timeout for capturing a browser, 60000 is default
    captureTimeout: 60000,

    client: {
      //capture all console output and pipe it to the terminal, true is default
      captureConsole: false,
      //if true, Karma clears the context window upon the completion of running the tests, true is default
      clearContext: false,
      //run the tests on the same window as the client, without using iframe or a new window, false is default
      runInParent: false,
      //true: runs the tests inside an iFrame; false: runs the tests in a new window, true is default
      useIframe: true,
      jasmine: {
        //tells jasmine to run specs in semi random order, false is default
        random: false
      }
    },

    /* karma-webpack config
       pass your webpack configuration for karma
       add `babel-loader` to the webpack configuration to make 
       the ES6+ code in the test files readable to the browser  
       eg. import, export keywords */
    webpack: {
      module: {
        rules: [
          {
            test: /\.js$/i,
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        ]
      }
    },
    preprocessors: {
      //add webpack as preprocessor to support require() in test-suits .js files
      './tests/*.js': ['webpack']
    },
    webpackMiddleware: {
      //turn off webpack bash output when run the tests
      noInfo: true,
      stats: 'errors-only'
    },

    /*karma-mocha-reporter config*/
    mochaReporter: {
      output: 'noFailures'  //full, autowatch, minimal
    }
  });
};

3. adjust the folders structure to your needs

  • Adjust basePath and excludes property, files pattern properties, and preprocessors properties to your need.
  • The configuration assumes that the following folder structure is arranged in the following way:
┌ karma.conf.js
├ package.json
├ webpack.config.js
├ src
│  ├ index.js
│  └ another_module.js
└ tests
   ├ spec_a.js
   └ spec_b.js

4. Add some specs to your test files

tests/spec_a.js
import myModule from './../src/index.js';

describe("Module should return", function () {
  it("some number", function () {
    expect(myModule()).toEqual(10);
  });
});
src/index.js
export default ()=> 10;

5. Run tests:

  • add "scripts": { "test": "karma start" } to your package.json and run tests with npm test
  • or run karma start in the terminal (but first install karma-cli globally)
> npm install karma-cli -g

Links

Launchers
Reporters

See also

webpack-karma-jasmine's People

Contributors

devrafalko avatar fulv avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

webpack-karma-jasmine's Issues

Dependencies Security Vulnerabilities

This package requires an old version of 'karma' (3.1.4) that requires 'set-value' with old version (2.0.0) which has vulnerability issue.
Updating the package to require the latest version of karma (4.2.0) will resolve the issue.

Thanks,
Michal.

Out of sync with latest released version

There are a slew of problems that would punish an unwitting user simply for trying to follow the instructions in the readme.

To start, /sample/package.json has an outdated version pin:

    "webpack-karma-jasmine": "^2.0.1"

Whereas the latest version on npm is 3.0.0.

Next, when you run npm install in webpack-karma-jasmine/sample, you get;

npm WARN [email protected] requires a peer of webpack@^2.0.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself.

and

found 6 vulnerabilities (1 low, 5 moderate)
run `npm audit fix` to fix them, or `npm audit` for details

Finally, npm test doesn't work at all:

> npm test

> [email protected] test /home/me/javascript/webpack-karma-jasmine/sample
> karma start

(node:9315) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
ℹ 「wdm」: wait until bundle finished: noop
14 09 2018 21:26:28.072:ERROR [karma]: TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.join (path.js:1236:7)
    at Plugin.<anonymous> (/home/me/javascript/webpack-karma-jasmine/sample/node_modules/karma-webpack/lib/karma-webpack.js:274:66)
    at Plugin.readFile (/home/me/javascript/webpack-karma-jasmine/sample/node_modules/karma-webpack/lib/karma-webpack.js:294:5)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
✖ 「wdm」: 
ERROR in chunk tests/spec_a [entry]
bundled.js
Conflict: Multiple chunks emit assets to the same filename bundled.js (chunks 0 and 1)
ℹ 「wdm」: Failed to compile.
npm ERR! Test failed.  See above for more details.

Sadly, updating the version pin in /sample/package.json to 3.0.0 does not really improve things, except that at least then the vulnerabilities are gone.

Dependency Security Violation

Hi,

webpack-karma-jasmine depends on karma 4.2.0, which causes minimist 0.0.10 to be loaded. The chain is:
karma 4.2.0 -> optimist 0.6.1 -> minimist 0.0.10
This reports a security violation https://npmjs.com/advisories/1179 .
This is fixed in karma >= 5.0.0, which no longer depends on optimist. Is it possible to upgrade to karma 5.0.0?

Thanks

Postinstall script requires installation of karma-cli with global tag.

Currently in a package.json is post-install script:

"postinstall": "npm install karma-cli -g"

I presume that the local package should not try to install some other package globally. This is currently cause me some issues when I try to have this package in my build as it fails the npm install. I do not have permission to install something globally for all the users nor it is the best option. Is it possible to remove a global -g modifier?

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.