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.js
to 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 )');
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With