I have a module which is generated by webpack at build time called config.
// webpack.config.js
let devConfig = {url: 'https://localhost'}
...
externals: {
'config': JSON.stringify(devConfig),
},
I import and ise it like;
import config from 'config'
console.log(config.url)
How can I mock this module, and give the url during the test?
I've tried following. It's making config object avaliable but not url.
// __mocks__/config.js
jest.mock('config', ()=>({url: 'https://localhost'}), {virtual: true})
How can I add url propery to mocked module?
Thank you.
Note: I need url since I will need it when using nock.
Here it is;
Looks like something elese was preventing me.
jest.mock("Config", ()=> ({url: 'https://localhost'}), {virtual: true});
Related
I am currently trying to overwrite a javascript file from an existing plugin.
I've been following the documentation but I am struggling with the path for the JS class to overwrite.
In the docs is an example code:
import CookiePermissionPlugin from 'src/plugin/cookie/cookie-permission.plugin';
export default class MyCookiePermission extends CookiePermissionPlugin {
}
So I implemented the following code:
import QuantityField from 'src/plugin/FilterRangeSlider/filter-range-slider.plugin';
export default class ExampleQuantityField extends QuantityField {
This code does not work for me, since the original file is in the vendor directory and my plugin is in the custom directory. When trying to compile (eg bin/build-storefront.sh) I receive the following error message:
Module not found: Error: Can't resolve 'src/plugin/FilterRangeSlider/filter-range-slider.plugin' in '<project root>/custom/plugins/ExampleProductFilter/src/Resources/app/storefront/src/filter-range-slider'
Any idea how I can import that class as stated in the docs?
Node.js provides a bunch of in-built file-system functionalities. The __dirname points to the root directory.
So, this should work.
import QuantityField from `${__dirname}/vendor/store.shopware.com/mmeesrangesliderpro/src/Resources/app/storefront/src/script/filter-range-slider.plugin`
My current solution is not really clean...
import QuantityField from '../../../../../../../../../vendor/store.shopware.com/mmeesrangesliderpro/src/Resources/app/storefront/src/script/filter-range-slider.plugin';
Isnt there any plugin root variable or something similar?
There is - I believe - no easier way to accomplish this.
If each plugin would extend the webpack config as described in
https://developer.shopware.com/docs/guides/plugins/plugins/administration/extending-webpack
const path = require('path');
module.exports = () => {
return {
resolve: {
alias: {
MmeesRangeSliderPro: path.join(__dirname, '..', 'src')
}
}
};
};
The alias could be used instead of the Plugin Root.
But this is not the case, so the following is not working:
import QuantityField from 'MmeesRangeSliderPro/plugin/FilterRangeSlider/filter-range-slider.plugin';
You can add a console.log(webpackConfig) to the bottom of Resources/app/storefront/webpack.config.js to validate this.
alias: {
src: '/home/user/example/projects/example.de/vendor/shopware/storefront/Resources/app/storefront/src',
assets: '/home/user/example/projects/example.de/vendor/shopware/storefront/Resources/app/storefront/assets',
jquery: 'jquery/dist/jquery.slim',
scss: '/home/user/example/projects/example.de/vendor/shopware/storefront/Resources/app/storefront/src/scss',
vendor: '/home/user/example/projects/example.de/vendor/shopware/storefront/Resources/app/storefront/vendor'
}
And those again to not really allow locating the module.
If it is a third-party plugin, replace the path with an absolute path like the following
import ThirdPartyPlugin from '/app/custom/plugins/ThirdPartyPlugin/src/Resources/app/storefront/src/third-party-plugin/third-party-plugin.plugin';
First off, I'm a beginner with NuxtJS and front-end development in general, so it might be that I'm missing something - though I do believe I went through all the options before posting here. Apologies in advance if that is not the case.
I've been having trouble using installed modules that I've registered as plugins. For example, take mapbox-sdk.
After installing it with npm install #mapbox/mapbox-sdk, which correctly creates #mapbox/mapbox-sdk in node_modules, I register it in nuxt.config.js:
plugins: [
...
"~/plugins/mapbox-sdk.js",
],
Of course, I also create the mapbox-sdk.js file in plugins/, containing:
import "#mapbox/mapbox-sdk";
Then, in a page (say, myMap.vue), when I try:
var mapboxClient = mapboxSdk({ accessToken: MY_ACCESS_TOKEN });
which is the basic usage example in the documentation, I get:
mapboxSdk is not defined
in the console. This behavior extends to every single module I installed today, but is not the case for modules I had previously installed.
The reason why you're getting the error mapboxSdk is not defined is because there are a few issues with the way you've set up this plugin.
Docs here https://nuxtjs.org/docs/2.x/directory-structure/plugins/, they have some useful diagrams.
There are a couple of ways you can use this package.
Plugin
// ~/plugins/mapbox-sdk.js
import mapboxSdk from '#mapbox/mapbox-sdk'
export default (_ctx, inject) => {
// Exposing the mapboxSdk to your Nuxt app as $mapBox.
inject('mapBox', mapboxSdk)
}
Then in nuxt.config.js, same as you've already done.
plugins: [
...
"~/plugins/mapbox-sdk.js",
],
Then in your component myMap.vue
var mapboxClient = this.$mapBox({ accessToken: MY_ACCESS_TOKEN });
Directly in the component:
If you don't wish to use a plugin, the way that #kissu mentioned above https://stackoverflow.com/a/67421094/12205549 will also work.
Try adding this after the import to let Vue know that this method exists (in the same .vue file) at first
<script>
import mapboxSdk from '#mapbox/mapbox-sdk'
export default {
methods: {
mapboxSdk,
},
mounted() {
console.log('mapbox function >>', mapboxSdk)
},
}
</script>
Do you have it working in a .vue component at first ?
Trying to set up some tests for a component in a CRA-generated application.
Having an issue where the test is failing to run due to an imported file relying on a window object which isn't initialised.
Quick overview:
In public/index.html there is an object defined on the window called window.config.
<script src="%PUBLIC_URL%/config.js"></script>
<script>
// THESE PROPERTIES ARE DEFINED IN config.js
window.config = {
ENV,
IDENTITY_URL,
OIDC_CLIENT_ID,
};
</script>
There is a file called identity.constants.js which exports an object that uses these window variables.
export const IdentityConfig = {
authority: window.config.IDENTITY_URL,
client_id: window.config.OIDC_CLIENT_ID,
... etc
};
The component I am trying to test imports another component that relies on identity.constants.js shown above.
The problem is that the test fails to start and throws an error stating window.config is undefined from the identity.constants.js file.
After reading the CRA docs, I have tried adding the following code into src/setupTests.js to set the config object before the test starts but it seems to fail before this code runs.
global.config = {
ENV: "development",
IDENTITY_URL: "identityurl.com",
OIDC_CLIENT_ID: "i-am-a-clientId",
... etc
};
I'm looking for a way to set this window variable before the tests run (or a better way to structure the way I'm using window variables) so I can successfully run my tests.
globa.config defines a global variable named config, you'll need to define global.window firstly, then add config as a property of global.window.
It seems your test environment is node, if you have jsdom as the devDependencies of your project, try to add below piece of code to your setupTests.js:
import { JSDOM } from 'jsdom';
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
global.window = jsdom.window;
global.document = jsdom.window.document;
global.window.config = {
ENV: "development",
IDENTITY_URL: "identityurl.com",
OIDC_CLIENT_ID: "i-am-a-clientId",
... etc
};
Without jsdom, a simple fix is like below:
global.window = {
config: {
ENV: "development",
IDENTITY_URL: "identityurl.com",
OIDC_CLIENT_ID: "i-am-a-clientId",
... etc
}
}
I need to import a .js file with config values to be used on my react app:
import config from './config'
These values are already added at webpack configuration:
new webpack.DefinePlugin({...config})
What I need is to import these values into jest.config.js:
globals: {
config: // Here config...
}
"I know that we can add these values manually, but I want to add them from this file to prevent the maintenance of all values instead".
Thanks!
https://jestjs.io/docs/en/configuration#globals-object
Note that, if you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will not be persisted across test runs for other test files. In addition the globals object must be json-serializable, so it can't be used to specify global functions.
here is a guide on adding globals to your jest config with basic usage below
import * as config from "path/to/config";
//...package.json || jest.config
"jest": {
"globals": {
...config
}
}
const config = {
this: 'is now global'
}
console.log({
jest: {
globals: {
...config
}
}
})
You can add it to the globals object and import the config as normal
Let's say I have 5 jsx files and each file uses some config parameter.
My index.js file imports all of these 5 jsx files.
Instead of having my config data spread accross 5 files, is there a way for my jsx files to get the data from a global JS object which has loaded the data from a config file?
I've seen some examples, but I've not been able to get them to work.
JS6 import function | Example using webpack
Assuming ES6:
config.js
export const myConfig = { importantData: '', apiUrl: '', ... };
Then:
jsxFileOne.js, jsxFileTwo.js, ...
import { myConfig } from 'config.js';
There are other ways to import & export things globally leveraging webpack, but this should get you started.
If your project is built using Webpack, consider using node-env-file.
Example config file snippets:
development.env
API_SERVER_URL=https://www.your-server.com
webpack.config.js
const envFile = require('node-env-file');
...
const appSettingsFile = isDevBuild ? '/settings/development.env' : '/settings/production.env';
try {
envFile(path.join(__dirname + appSettingsFile));
} catch (error) {
console.log("Failed to read env file!: " + __dirname + appSettingsFile);
}
...
plugins: [
new webpack.DefinePlugin({
"process.env": {
API_SERVER_URL: JSON.stringify(process.env.API_SERVER_URL)
}
})
...
]
Inside your js/jsx code, you can now access process.env.API_SERVER_URL variable which will contain the required value.
It seems dotenv package is more popular, you can try this out as well.
Very old problem, that nobody took the time to solve, until now. I leave this for future readers because this is a top search result for configuration in React.
I created wj-config to deal exactly with this. Be sure to pay close attention to the React notes as you will need to enable top-level awaits in webpack, either by ejecting or using the #craco/craco NPM package.
You may also read this blog post that explains its use.