简体   繁体   中英

How integrate mocha test file with webpack process?

I have a JS class I would like to write tests for. I got mocha installed. Created a file test.js in project root. I can now run tests within that like this

var assert = require('assert');

describe('Arithmetic', function() {
    describe('Plus', function() {
        it('1 + 1 equals 2', function() {
        assert.equal(1+1, 2);
        });
    });
});

All good! The thing I am unsure of is how to test my file as it includes alot of ES6 things. For example imports like import someDependency from 'resources/assets/js/someDependencyToMyClass';

How do I make it so mocha knows of my package.json/webpack process? Or should I just test the transpiled versions of my code?


I tried to setup a test class myself and run with node but then I am bypassing all the babel stuff so it wont work. I also thought about making a test page in addition to my SPA (react) but I rather not clutter the actual code. How would you do this?

Also, if necessary, here is my projects package.json.

 { "private": true, "scripts": { "dev": "npm run development", "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch-poll": "npm run watch -- --watch-poll", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "prod": "npm run production", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "axios": "^0.17", "babel-preset-react": "^6.23.0", "cross-env": "^5.1", "jquery": "^3.2", "laravel-mix": "^1.0", "lodash": "^4.17.4", "mocha": "^5.0.0", "react": "^15.4.2", "react-dom": "^15.4.2", "testing": "^1.1.1" }, "dependencies": { "bootstrap": "^4.0.0", "popper.js": "^1.12.9", "react-redux": "^5.0.6", "redux": "^3.7.2" } } 

You might want to pull in mocha-webpack ( https://github.com/zinserjan/mocha-webpack ) in order to precompile your code according to your webpack config. Then you can simply create a test script in your package.json pointing to your webpack config like so:

"scripts": { "test": "mocha-webpack --webpack-config=webpack.config.js tests/*.js" } .

Running npm test will then precompile your code properly. Hopefully it points you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM