Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require.context not a function when trying to run Mocha tests

I'm trying to run tests using the Mocha.js + JSDOM frameworks, but I'm having trouble getting Mocha to start up. This is in the process of testing a React app using the Vue.js library. I keep getting the following error:

var req = require.context('./', false, /\.vue$/);
TypeError: require.context is not a function

The code in question is:

let req = require.context('./', false, /\.vue$/);
components.forEach(function (component) {
    try {
        let filePath = './' + component + '.vue';
        let injected = inject(req(filePath));
        Vue.component(getComponentName(component), injected);

        let appComponent = {
            name: injected.name,
            props: {
                autocompletion: {
                    metadata: getComponentName('template'),
                    score: xTemplatesScore,
                    attributes: injected.props || []
                }
            }
        };

        appComponents.push(appComponent);

    } catch (err) {
        console.log(err);
        console.error('Vue file was not found for component:' + component + '. Please rename your files accordingly ( component-name.vue )');
    }

Is there a way to get around this and actually get Mocha to start up? Or is there a suitable replacement for require.context? I've tried to redo it with just plain string concatenations and a vanilla require, but that keeps telling me that none of the Vue modules can be found.

like image 343
rafafan2010 Avatar asked Jan 24 '17 15:01

rafafan2010


1 Answers

require.context is a method of webpack. Your tests must be bundled before they can be run.

Normally, you'd create a separate webpack config file for your tests. You'll then create a test bundle using webpack and then run Mocha on this bundle. Alternatively, you can use mocha-loader inside the webpack test config file and let the tests run as part of the bundling process.

Further information can be found in the webpack documentation on testing.

like image 174
Stefan Dragnev Avatar answered Nov 07 '22 17:11

Stefan Dragnev