Code Monkey home page Code Monkey logo

karma-redirect-preprocessor's Introduction

karma-redirect-preprocessor

Preprocessor for serving files at custom URLs

In your code, you might have a line like:

$.ajax('templates/landing.html').done(function(html) {
  loadView(html);
});

However, when running this code in Karma, landing.html will probably be served to a URL like /base/static/templates/landing.html, in which case the above AJAX won't work.

The karma-redirect-preprocessor can solve this problem by making karma serve files at the correct URL.

Based off of karma-ng-html2js-preprocessor.

Installation

The easiest way is to keep karma-redirect-preprocessor as a devDependency in your package.json.

{
  "devDependencies": {
    "karma": "~0.10",
    "karma-redirect-preprocessor": "~0.1"
  }
}

You can simple do it by:

npm install karma-redirect-preprocessor --save-dev

Compatible with karma 0.13 and above

Configuration

// karma.conf.js
module.exports = function(config) {
  config.set({
    preprocessors: {
      '**/*.html': ['redirect']
    },

    files: [
      '*.js',
      '*.html',
      '*.html.ext',
      // if you wanna load template files in nested directories, you must use this
      '**/*.html'
    ],

    // if you have defined plugins explicitly, add karma-redirect-preprocessor
    // plugins: [
    //     <your plugins>
    //     'karma-redirect-preprocessor',
    // ]

    redirectPreprocessor: {
      // strip this from the file path
      stripPrefix: 'public/',
      stripSuffix: '.ext',
      // prepend this to the
      prependPrefix: 'served/',

      // or define a custom transform function
      cacheIdFromPath: function(filepath) {
        return cacheId;
      },

      // By default, any redirected files have their `included` property set to
      // false (see "How does it work?").  If you set dontInclude to false
      // however, the preprocessor will not mess with the `included` property.
      // dontInclude = false
    }
  });
};

How does it work ?

This preprocessor rewrites your config file so that files are proxied to the desired address. See the config documentation for information on proxies in karma. By default, the preprocessor also sets the included property of all redirected files to false. This stops karma from including the files in <script> tags, since the tests will probably be retrieving these files over AJAX (and the files might not even be js files).

See the test file for an example.


For more information on Karma see the homepage.

karma-redirect-preprocessor's People

Contributors

sjelin avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

phillip-hopper

karma-redirect-preprocessor's Issues

Trying to use this for Angular2 templateUrl

Hi there,

I've been trying to get this karma pre-processor working with templateUrl in angular2 beta.0 but it doesn't seem to change the URL according to the stack trace that angular produces.

Failed: Failed to load app/components/chealthcheck/healthCheckStatus.view.html

Thanks
Mat

var appConfig = require('./ui-config.js');

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', 'chai', 'sinon'],

        // list of files / patterns to load in the browser
        files: [
            {pattern: 'spec-bundle.js', watched: false},

            // if you wanna load template files in nested directories, you must use this
            '**/*.html'
        ],
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'spec-bundle.js': ['webpack', 'sourcemap'],
            '**/*.html': 'redirect'

            //'src/main/app/**/*.html': 'ng-html2js',
            //'src/main/app/**/*.js': ['coverage']
        },

        webpack: {
            resolve: {
                cache: false,
                root: __dirname,
                extensions: ['', '.ts', '.js', '.json', '.css', '.html'],
                alias: {
                    'app': 'src/app',
                    'common': 'src/common'
                }
            },
            devtool: 'inline-source-map',
            module: {
                loaders: [
                    {
                        test: /\.ts$/,
                        loader: 'ts-loader',
                        query: {
                            'ignoreDiagnostics': [
                                2403, // 2403 -> Subsequent variable declarations
                                2300, // 2300 Duplicate identifier
                                2375  // 2375 -> Duplicate string index signature
                            ]
                        },
                        exclude: [/\.e2e\.ts$/, /node_modules/]
                    },
                    {test: /\.json$/, loader: 'json-loader'},
                    {test: /\.html$/, loader: 'raw-loader'},
                    {test: /\.css$/, loader: 'raw-loader'}
                ]
            },
            stats: {colors: true, reasons: true},
            debug: false,
            noParse: [
                /zone\.js\/dist\/zone-microtask\.js/,
                /zone\.js\/dist\/long-stack-trace-zone\.js/,
                /zone\.js\/dist\/jasmine-patch\.js/
            ]
        },

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

        // Append to HTML files so tests can find them
        redirectPreprocessor: {
            // prepend this to HTML files
            prependPrefix: 'src/main/'
        },

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

        junitReporter: {
            outputDir: 'target/karma-reports',
            suite: ''
        },
        coverageReporter: {
            type: 'lcov',
            dir: 'target/karma-coverage/',
            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: ['PhantomJS'],

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

Not working with karma-systemjs

I'm serving the files through karma but I'm using the karma-systemjs plugin that has a serveFiles option.
I see the file server on the propoer location, but not from the redirect location.

I'm trying to serve HTML files for Angular 2.0 correctly.

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.