Mocha tests don't run with Webpack and mocha-loader

前端 未结 2 1371
春和景丽
春和景丽 2020-12-07 17:27

Background

I am porting some npm scripts to Webpack loaders to better learn how Webpack works and I’ve got everything working except for my Mocha tests: I have one

2条回答
  •  庸人自扰
    2020-12-07 17:58

    Mocha loader won't run tests while building, it's used to create a bundle specifically containing your tests which you can then run from your browser.

    I would recommend creating a separate webpack config file for your tests, which you can then host on a webpack-dev-server that uses a different port from your application. Here's an example that's more-or-less the pattern that I use for my own projects (as of writing this answer):

    webpack.tests.config.js

    module.exports = {
        entry: 'mocha!./tests/index.js',
        output: {
            filename: 'test.build.js',
            path: 'tests/',
            publicPath: 'http://' + hostname + ':' + port + '/tests'
        },
        module: {
            loaders: [
                {
                    test: /\.js$/,
                    loaders: ['babel-loader']
                },
                {
                    test: /(\.css|\.less)$/,
                    loader: 'null-loader',
                    exclude: [
                        /build/
                    ]
                },
                {
                    test: /(\.jpg|\.jpeg|\.png|\.gif)$/,
                    loader: 'null-loader'
                }
            ]
        },
        devServer: {
            host: hostname,
            port: port
        }
    };
    

    tests/index.js

    // This will search for files ending in .test.js and require them
    // so that they are added to the webpack bundle
    var context = require.context('.', true, /.+\.test\.js?$/);
    context.keys().forEach(context);
    module.exports = context;
    

    package.json

    "scripts": {
        "test": "find ./ -name '*.test.js' | xargs mocha -R min -r babel/register",
        "devtest": "webpack-dev-server --config webpack.tests.config.js",
        "dev": "webpack-dev-server --config webpack.config.js"
    }
    

    test.html

    
    
        
            Mocha
            
            
            
            
        
        
        
    
    

    Then run npm run devtest, open http://localhost:/webpack-dev-server/test.html, and mocha should run your tests.

    If you don't require CSS/LESS or images through your modules, you can remove those loaders from webpack.tests.config.js.

    With hot loading enabled this is a really great setup because I can have both my application and my tests running in different browser tabs, then update my code and see my changes and my tests re-running immediately.

    You can also run npm run test to execute the same tests through the command line.

    Hope this helps.

提交回复
热议问题