Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for `require.context` when running Jest

I'm trying to run tests for my React application using Jest, but my tests keep on failing due to an error saying that require.context is not a function. I am looking for a replacement for that functionality that Jest will not choke on. I am trying to dynamically require and modify some *.vue file from Vue.jsto be used later on in my application. In addition to this, I occasionally get errors that don't recognize the format of the .vue files and say that they can't be parsed. This is the code in question:

function inject(comp) {
    comp.methods = Object.assign({}, comp.methods, stub.methods);
    return comp;
} 

let req = require.context('./', false, /\.vue$/);
components.forEach(function (component) {
    try {
        let filePath = __dirname + "\\" + 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 )');
    }
});
like image 510
rafafan2010 Avatar asked Feb 17 '17 16:02

rafafan2010


1 Answers

If someone still run into this issue, you need to know that require.context is a webpack-specific feature, so it doesn't work in jest.

You can try to mock it, like someone already provided as an answer in this How can I mock Webpack's require.context in Jest? SO question. But you can't use it without any workaround.

like image 53
StevenSiebert Avatar answered Nov 15 '22 22:11

StevenSiebert