Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesnt seem to work with karma and webpack #16

Closed
bulkan opened this issue Jul 17, 2015 · 15 comments
Closed

Doesnt seem to work with karma and webpack #16

bulkan opened this issue Jul 17, 2015 · 15 comments

Comments

@bulkan
Copy link

bulkan commented Jul 17, 2015

When I enable babel-plugin-rewire I get errors in JSX compilation.

I've tried the fixes mentioned in this issue, enabling babel-runtime but this creates more errors.

Any ideas ?

node v2.3.1 (iojs)
babel-core 5.7.3
babel 5.6.23
babel-loader 5.3.2
@speedskater
Copy link
Owner

Could you please provide more information and a small example replicating your issue?
What kind of errors do you get?

@speedskater
Copy link
Owner

Could you please check version 0.1.7 as this should fix some regressions which happened at the transition to 0.1.6.

@bulkan
Copy link
Author

bulkan commented Jul 18, 2015

Thanks for that I'm getting the following error now;

ERROR in ./src/js/components/common/form/input.jsx
Module build failed: TypeError: /Users/bulkan/src/work/work_official/frontend/src/js/components/common/form/input.jsx: Cannot set property 'kind' of undefined
    at /Users/bulkan/src/work/work_official/frontend/node_modules/babel-plugin-rewire/src/babel-plugin-rewire.js:100:39
    at Array.forEach (native)
    at NodePath.module.exports.Transformer.VariableDeclaration (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-plugin-rewire/src/babel-plugin-rewire.js:96:21)
    at NodePath.call (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/path/context.js:56:28)
    at NodePath.visit (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/path/context.js:89:8)
    at TraversalContext.visitMultiple (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/context.js:107:16)
    at TraversalContext.visit (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/context.js:145:19)
    at Function.traverse.node (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/index.js:76:17)
    at NodePath.visit (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/path/context.js:106:26)
    at TraversalContext.visitSingle (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/context.js:131:12)
    at TraversalContext.visit (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/context.js:147:19)
    at Function.traverse.node (/Users/bulkan/src/work/work_official/frontend/node_modules/babel-core/lib/traversal/index.js:76:17)
 @ ./src/js/components/common/search.jsx 127:16-59

@speedskater
Copy link
Owner

Thanks I will have a look into this issue. Could you please attach a sample file causing this problem.

@bulkan
Copy link
Author

bulkan commented Jul 18, 2015

That component is part of a bigger application not sure I can distill it into a smaller chunk but here is the component code

@speedskater
Copy link
Owner

Thanks I will have look at it. Will take till tomorrow.

@speedskater
Copy link
Owner

@bulkan Version 0.1.8 should fix your problem. The issue was cause by the destructuring assignment in line 10 of your code. For now i changed babel-plugin-rewire to ignore destructuring assignments. If you want to rewire this variables you have to create separate variables. Let me know if this fix solved your issue or if there are still issues.

@seanepping
Copy link

EDIT: webpack 1.10.1, karma 0.12.37, karma-webpack 1.6.0, babel-core 5.7.4, babel-loader 5.3.2, babel-plugin-rewire 0.1.8

I am having an issue with the newest version (0.1.8, I have also tried 0.1.7). When I call Rewire on a module, it doesn't actually set the value. I followed through in a debugger and verified that on calls to $Setters_ and $Getters it was calling $Resetters, although they appear to be defined correctly in the file. These worked fine before the update to Babel and in 0.1.6, is there a new gotcha with configuration I am missing?

@speedskater
Copy link
Owner

Thanks for the report. Can you send me the module you tried to rewire and the code you use to rewire this module? I will try to reproduce your issue and distill a unit test from it so we can solve this annoyance for you.

@seanepping
Copy link

Here is the module I was mocking

import { Database } from 'database';

export default class RewireExample {
    constructor(){
        this.database = new Database();
    }

    outputDatabaseInfo() {
        return this.database.info;
    }
}

Here is the dependency

export class Database {
    get info() {
        return 'real database info';
    }
}

And here is the test

import RewireExample from './RewireExample';

let fakeDatabaseInfo = 'fake database info';

class FakeDatabase {
    get info(){
        return fakeDatabaseInfo;
    }
}

describe('rewire example', () => {
    var rewireExample;

    beforeEach(() => {
        RewireExample.__Rewire__('Database', FakeDatabase);
        expect(RewireExample.__GetDependency__('Database')).toEqual(FakeDatabase);

                rewireExample = new RewireExample();
    });

    afterEach(()=> {
        RewireExample.__ResetDependency__('Database');
    });

    describe('outputDatabaseInfo function', () => {
        it('should output fakeDatabase when fake database is used', () =>{
            expect(rewireExample.outputDatabaseInfo()).toBe(fakeDatabaseInfo);
        });
    });
});

I added the expectations on GetDependency to show that they are getting the undefined return of $Resetters, and they fail as expected for me. I am loading tests through karma as follows:

import 'babel-core/register';

var testsContext = require.context(".", true, /.test$/);
testsContext.keys().forEach(testsContext);

Webpack and karma configs are as follows:

module: {
        loaders:[
            { test: /\.css$/, loader: 'style!css'},
            { test: /\.less$/, loader: 'style!css!less'},
            { test: /\.scss$/, loader: 'style!css!sass'},
            { test: /\.json$/, loader: 'json'},
            {test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
            {test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
            {
                test: /\.(js|jsx)?$/,
                exclude: /node_modules/,
                loader: ['babel'],
                include: path.join(__dirname, '../..'),
                stage: 1,
                modules: 'common',
                query: {
                    plugins: ['babel-plugin-rewire'],
                    optional:[
                        'runtime',
                        'es6.spec.blockScoping',
                        'es6.spec.symbols',
                        'es6.spec.templateLiterals'
                    ]
                }
            }
        ]
    },
    resolve: {
        modulesDirectories: ['src', 'web_modules', 'node_modules', 'test/client/lib'],
        extensions:['','.js','.jsx']
    },
    plugins:[
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(true)
        //new webpack.optimize.UglifyJsPlugin({
        //  compressor: {},
        //  warnings: false
        //})
    ],
    devtool: 'eval'
// 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'],


    // list of files / patterns to load in the browser
    files: [
        'test/client/unit_test_index.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: {
        'test/client/unit_test_index.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,

    webpackMiddleware: {
        stats: {
            // With console colors
            colors: true,
            // add the hash of the compilation
            hash: false,
            // add webpack version information
            version: false,
            // add timing information
            timings: true,
            // add assets information
            assets: false,
            // add chunk information
            chunks: false,
            // add built modules information to chunk information
            chunkModules: false,
            // add built modules information
            modules: false,
            // add also information about cached (not built) modules
            cached: false,
            // add information about the reasons why modules are included
            reasons: false,
            // add the source code of modules
            source: true,
            // add details to errors (like resolving log)
            errorDetails: true,
            // add the origins of chunks and chunk merging info
            chunkOrigins: true,
            // Add messages from child loaders
            children: false
        }
    },

    plugins: [
        require('karma-jasmine'),
        require('karma-chrome-launcher'),
        require('karma-phantomjs-launcher'),
        require('karma-spec-reporter'),
        require('karma-sourcemap-loader'),
        require('karma-webpack')
    ],

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

    // web server port
    port: 9876,

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

    // 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

@speedskater
Copy link
Owner

Thanks for the detailed error description. I will try to fix your issue on thursday.

@speedskater
Copy link
Owner

The issue that your test is not working is caused by correct usage of TDZ due to the setting of es6.spec.blockScoping.
If you remove es6.spec.blockScoping from the optional section in your webpack config it should work.
I investigate whether i can change the plugin in such a way that it also works if es6.spec.blockScoping is enabled.

@seanepping
Copy link

Oh that makes sense, thanks for looking into it. I will keep watching to see if you enable that feature, as block scoping is one of the things I really like having. I wonder if there isn't a way that if you are enabling rewire capability for testing that imports could be declared in such a way that block scoping can be avoided, since they are mandated to be declared first anyhow. Again, thanks for your time.

@speedskater
Copy link
Owner

The error was caused by an error in the transformation. It should be fixed now. Can you please test with version 0.1.10. and let me know whether this solves the issue for you.

@seanepping
Copy link

It works brilliantly, thanks for the quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants