jest global variable example - jestjs

Can someone give an example on how to use jest globals?
{
...
"jest": {
"globals": {
"__DEV__": true,
}
}
...
}
Do I specify the globals in the package.json file or do I create a folder with a js file where the globals should be defined?
Thanks

Yep. You put the globals in the package.json. For example, here's an excerpt from the default react-native jest configuration:
"jest": {
"globals": {
"__DEV__": true,
"__RCTProfileIsProfiling": false
},
...
},
This will make the variables available globally when the tests are run.

A cleaner way to add globals would be to set "setupFiles": "<rootDir>/private/jest/setup.js" in package.json, and then create a setup.js file that sets global.__DEV__ = true.
This pattern is helpful for making 3rd party libraries available as globals to Jest tests as well (like Backbone, jQuery, lodash, etc.) - eg. global.Backbone = require('backbone'); and so on.
(Re-submitting this as an answer as it was previously just a comment under Michael Helvey's answer.)

For me using the Jest config file worked much better because it is a Javascript file itself so it gives full freedom:
After running jest --init in your folder, in the jest.config.js file Jest makes, scroll down to find:
// A set of global variables that need to be available in all test environments
// globals: {},
Uncomment the second line and put all your globals in there.

If you are using create-react-app, you must use the src/setupTests.js file instead of pointing to a file via setupFiles in the package.json file.
https://create-react-app.dev/docs/running-tests/#srcsetuptestsjs
In the src/setupTests.js file, you can define globals like so:
global.TIMEOUT = 3000;

To share object variables (not only primitives as with configuration's globals property), you can use the testEnvironment property.
More explanations here in Jest's Git

Related

How can I make webpack skip a require

How can I make webpack skip occurences of
require('shelljs/global');
in my source files? I want to make a bundle of my source files but keep the require('shelljs/global') in the files and not bundle shelljs/global.
If you store the path in a variable then IgnorePlugin will not work. Though you still could do:
const myCustomModule = eval('require')(myCustomPath)
for new comers, on webpack 2+ the way to do this is like so:
module.exports = {
entry: __dirname + '/src/app',
output: {
path: __dirname + '/dist',
libraryTarget: 'umd'
},
externals: {
'shelljs/globals': 'commonjs shelljs/global'
}
};
the bundle will contain a verbatim require:
require('shelljs/global');
read on more supported formats on webpack's config guide and some good examples here
You can use Ignore Plugin (webpack 1) / Ignore plugin (webpack 2).
Add plugin in webpack.config.js:
plugins: [
new webpack.IgnorePlugin(/shelljs\/global/),
],
If require is in the global namespace and this is why you want Webpack to ignore it, just do window.require()
This should be a last resort option, but if you are certain that your JS file is always parsed by Webpack, and nothing else:
You could replace your require() calls with __non_webpack_require__()
Webpack will parse and convert any occurrence of this and output a normal require() call. This will only work if you are executing in NodeJS OR in a browser if you have a global require library available to trigger.
If webpack does not parse the file, and the script is run by something else, then your code will try to call the non-converted __non_webpack_require__ which will fail. You could potentially write some code that checks earlier in your script if __non_webpack_require__ exists as a function and if not, have it pass the call on to require.
However, this should be temporary, and only to just avoid the build errors, until you can replace it with something like Webpack's own dynamic imports.
Here a trick
const require = module[`require`].bind(module);
Note the use of a template string
If some files contains nested requires and You want to ignore them, You can tell webpack to not do parsing for these specific files.
For example if swiper.js and vue-quill-editor.js had inner requires this would be how to ignore them.
module.exports = {
module: {
noParse: [
/swiper.js/,/quill/
],

ESLint - "window" is not defined. How to allow global variables in package.json

I am assigning a property to the global window object, but when I run eslint, I get this:
"window" is not defined
I see this here in the eslint docs:
the following defines window as a global variable for code that should not trigger the rule being tested:
valid: [
{
code: "window.alert()",
globals: [ "window" ]
}
]
I've tried adding something like this to the package.json file to have eslint allow "window" as a global variable, but I must be doing something wrong. From the docs it seems like I might need to do something like this in a separate file, but is there a way to define some allowed global variables right in the package.json file?
There is a builtin environment: browser that includes window.
Example .eslintrc.json:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: https://eslint.org/docs/user-guide/configuring/language-options#specifying-environments
Also see the package.json answer by chevin99 below.
I found it on this page: http://eslint.org/docs/user-guide/configuring
In package.json, this works:
"eslintConfig": {
"globals": {
"window": true
}
}
Add .eslintrc in the project root.
{
"globals": {
"document": true,
"foo": true,
"window": true
}
}
Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.
{
"env": {
"browser": true,
"node": true
}
}
I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:
Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):
/* eslint-env browser */
This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.
There are plenty of environments, and you can declare more than one at the same time, for example, in-line:
/* eslint-env browser, node */
If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.
From their docs:
An environment defines global variables that are predefined. The
available environments are:
browser - browser global variables.
node - Node.js global variables and Node.js scoping.
commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
shared-node-browser - Globals common to both Node and Browser.
[...]
Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:
/* eslint-disable no-console */
You can see the list of all rules, including recommended rules to have for best coding practices.
If you are using Angular you can get it off with:
"env": {
"browser": true,
"node": true
},
"rules" : {
"angular/window-service": 0
}

how to require a specific file using duojs

I need to include a library that is present on github, but is not well-packaged; using Duo.js
At the moment of writing I am using the following to achieve what I desire:
bower
gulp
main-bower-files
Bower just downloades the library.
Gulp, with main-bower-files are useful to override the single package options and setup a so-called "main file" that I can build.
Example:
gulp.task('copy-libs', function () {
return gulp.src(bowerFiles({ env: 'development' }))
.pipe(gulp.dest('build/libs/'));
});
bower.json file:
"dependencies": {
"cash": "sudo-js/cash",
"bootstrap": "~3.3.2",
"delorean": "~0.8.7",
"react": "~0.12.2"
},
"overrides": {
"cash": {
"main": {
"development": "build/debug/cash.js"
}
}
}
}
How can i achieve this with duojs?
The documentation is quite thin regarding libraries that does not ship with a valid component.json
You can specify the path to an entry file for your lib. It won't be as clean as just specifying user/repo, but it'll get the job done.
For example, when including Twitter Bootstrap from twbs/bootstrap
require('twbs/bootstrap#v3.3.2:dist/js/bootstrap.js');
// repo: twbs/bootstrap
// version/tag: v3.3.2
// path: dist/js/bootstrap.js
Unfortunately, this doesn't work out-of-the-box since it assumes you have the jQuery global... so you need to add this above the previous line.
jQuery = require('components/jquery'); // leave out `var` so it becomes a global
This includes jQuery from the wonderful components project. (they package up popular libs so they can be consumed by various package managers.
Also, it turns out there is a components/bootstrap that is properly packaged with a component.json.
So, you can actually make bootstrap work with the following:
jQuery = require('components/jquery');
require('components/bootstrap');
For the other libraries that aren't as common, you can use the process mentioned first to specify the path to the right JS/CSS file. (ie: user/repo#version:path)

Environment specific variables with requirejs

I would like to set a requirejs configuration variable which would be available via module.config.
The optimizer does not seem to pass this through.
Is this possible, or should I handle this step via my build process.
You have to set it in your config file for a specific module like this and as long as your told r.js to use this config file it should work:
requirejs.config({
config: {
'path/to/myModule': {
someSetting: 'someSetting'
}
}
});
A simple solution seems to be to be:
Create a config file for each environment (eg., config, config-production)
When you want your config, require('/path/to/config')
When you call r.js, just put in a paths argument (eg., r.js -o build.js paths.config=config-production)
You now have your production configuration settings

Disabling warning about "require" function in JSHint

I'm writing some code for Node.js and I'm currently using JSHint to check over my code. However, when I use the require function to import modules, it says:
'require' is not defined.
How can I suppress the warning?
"use strict";
var express = require('express');
var register = require('./routes/register');
jshint is not aware of node.js globals by default you need to inform it.
add this comment to the top:
/* jshint node: true */
We can set node as the global environment variable in JSHint's .jshintrc file
This option defines globals available when your code is running inside of the Node runtime environment. Node.js is a server-side JavaScript environment that uses an asynchronous event-driven model. This option also skips some warnings that make sense in the browser environments but don't make sense in Node such as file-level use strict pragmas and console.log statements.
For more info http://jshint.com/docs/options/#node
{
"node": true
}
Errors like 'require' is not defined, 'console' is not defined, 'module' is not defined won't show up any more
You can configure JSHint by adding "require" to the .jshintrc file. For instance:
{
"globals" : {
"require": false
}
}
Or you can define globals per specific file only by:
/* global require */
For more information about how to configure JSHint please read JSHint Documentation
I stumbled upon this answer and couldn't get anything to work in VSCode. I got this to work:
Open JSON Settings file using the Preferences: Open Settings (JSON) via the Command Palette Window (Ctrl-Shift-P).
Add this section into the settings.json file:
{
"jshint.options": {
"esversion": 8, // This gets rid of some other warnings
"node": true
}
}

Resources