Prevent "test/expect/etc is not defined" errors when using Jest - javascript

Facebook's Jest testing framework is easy to get started with, but the documentation overlooks an annoying aspect: test statements will be highlighted as errors by any editor that tries to warn of undefined symbols, because test, expect, and all matcher methods are not defined.
Similary, attempting to run a test file with node directly will fail with ReferenceError: test is not defined.
What require/import statement(s) need to be added for those errors to go away?

Node
If you want to run them directly through node, try to require jest and/or jest-runtime. Also give #types/jest a try as well.
Check Edit 2 for new info about this
Edit
#types/jest (jest-DefinitelyTyped) is definitely needed (or just one solution). If you install it (e.g., dev dependency), the IDE errors should go away.
I just tried it on Webstorm, and it works.
Edit 2
The new Jest#20 Matchers (e.g., .resolves and .rejects) are still not defined in #types/jest. You can keep track of its status on the links below:
https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16645
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16803
It should be available soon, though!
Also, it doesn't seem possible to run it directly through node. Last night I tried a bunch of different things, but using jest is the way to go - it really uses node under the hood, so I thought it would be possible as well. #thymikee over your opened issue at GitHub made clear that it's not.
Edit 3
The new release (20.0.1) includes the newest Jest definitions.
Lint
this isn't in the scope of this specific problem, but it also helps
Are you using something like ESLint? If so, you'll need eslint-plugin-jest
Following the steps described in this page: https://www.npmjs.com/package/eslint-plugin-jest, you will basically need to add it as an ESLint plugin and set jest globals in the ESLint configuration:
{
"env": {
"jest/globals": true
}
}
If you plan on supporting ES6 tests, you'll also need Babel and babel-jest plugin with the following jest configuration:
"transform": {
"^.+\\.js$": "babel-jest"
}
Finally, for Typescript tests you'd need the #types/jest and ts-jest packages as well

Adding following .eslintrc configuration is enough
{"env":
{
"jest": true
}
}

I'm using VSCode and ESLint, you need to install eslint-plugin-jest
Add jest info to your .eslintrc.js
{
"plugins": ["jest"]
},
"env": {
"jest/globals": true
}

Related

Force nested npm dependency to use same one

I am facing an error that caused by lower version of TypeScript, root cause is I update prettier version, related post: https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/60310
So dependency issue was:
React -> TypeScript#4.7.4
Other-library -> Webpack-dev-server -> TypeScript#3.8.2
Prettier -> TypeScriptv4+
Since Prettier require TS version 4+ and the Webpack-dev-server has a version of 3.8.2, that will cause the program to throw error.
I can not change the version of Other-library, but I still need the version of TypeScript to be v4+
I am looking at this post:How do I override nested NPM dependency versions?
This seems does exactly what I needed to do.
But after I use the overrides property in package.json, I do see React is pickup the TypeScript version 4.7.4,
howerver I get the following error:
Child process failed to process the request: Error: Debug Failure. Palse expression. at resolveNamesWithLocalCache, at typescipt/lib
Thanks
My package json looks like:
{
"devDependencies": {
"typescript": "^4.7.4"
},
"overrides": {
"webpack-dev-server": {
"typescript": "$typescript"
}
}
}
`
So I checked, typescript is only "devDependencies" to webpack-dev-server. It's NOT supposed to be installed at all. How did you even end up in this situation 😂
It must be something about the way you install those packages. I don't know what happened, just try remove node_modules folder entirely, and also package-lock.json, then npm install again. You don't need that "overrides" field.
Additionally, it sounds to me this whole mayhem starts because of #types/prettier. HOWEVER, unless you have a very specific use case (which I seriously doubt) that requires integrating with prettier's programmatic API, through hand written TS code, you don't even need #types/prettier in the first place. Just get rid of that troublemaker. All #types/* packages are optional.

Jest "No tests found, exiting with code 1" error on Windows 10 in React Redux application

I am attempting to run Jest on my project. I am on a Windows 10. I only have one test in one test file.
In package.json:
"test": "jest"
My directory structure:
src/
app/
routeName/
redux/
action.tests.js
My output:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\myUsername\Documents\myApp
47 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 47 matches
testRegex: - 0 matches
Pattern: - 0 matches
npm ERR! Test failed. See above for more details.
According to the documentation here, Jest should look for anything that has test.js in the name.
I have also tried tests.js and that didn't work either.
I created a folder in the root of the project and put a test in there as __tests__/tests.js and that did work, but I do not want it placed there.
I have seen several tickets and questions about questions that are superficially similar, but all of those involve more complex configurations, or bugs that were supposedly patched already. I have no special configurations set. The documentation says this should work. Tutorials I have read for Jest include the exact setup I am currently using.
I am using Babel and Webpack. I installed the jest and babel-jest packages. I also added jest to the ESLint environment.
[edit] updated to properly document my problem, which I answered below. I lost track of my file naming.
I am a bloody idiot and I didn't pay attention to the details.
Jest is looking for test.js specifically. Not testS.js. My files were labeled as tests.js. It worked inside __tests__/ because Jest just looks for anything inside there.
I got it working just fine now, and it shall remain up as a testament to me not looking at the specifics of the regex matches.
I had the same Problem with a React-App. Make sure, that the jest config file has the correct file pattern to find the tests:
// jest.config.js
module.exports = {
testMatch: [
'<rootDir>/src/**/*.test.js',
'<rootDir>/src/**/*.test.jsx',
],
...
}
From my side, I was getting this error because I had placed myself (cd) in the directory where the chromeDriver was installed, so as not to have to add its path to $Path. After I added chromeDriver to $Path, and placed myself in the directory of my project, everything went fine.
No tests found, exiting with code 1
All I had to do was npm install.
Then I hit the Debug link at the top of my test. The test was found and execution stopped at the breakpoint. A simple solution to a very frustrating problem.
You just need to change the name of the file. For example
if you have a customer.js or customer.ts file and you want to test it. Create a new file name is customer.test.js or
customer.test.ts after npm test it will test the file which just for testing .
I had the same problem, I wanted to run my tests inside drone CI pipeline and had the same error what solved my problem was simply adding workspace to my project.
check if it is small case like filename.test.js.
I made a mistake ComponentName.Test.js and got error, fixed it by ComponetName.test.js

Turn off ESLint rule (in React app, using WebStorm)

I am writing a React app in WebStorm using the standard React setup. I have never previously explicitly set up any linting, so whatever error/warning messages are showing up are from some sort of default configuration. When I run npm start I get the following warning:
Compiled with warnings.
Warning in ./path/to/MyComponent.js
/my/complete/path/to/MyComponent.js
19:49 warning Unexpected whitespace before property bind no-whitespace-before-property
...
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
The last two lines make it explicitly clear that the warnings are from ESLint (as opposed to, say, JSHint or some custom React linting, etc.).
I want to keep ESLint running, i.e. I don't just want to globally disable all linting. However, I want to turn the "no-whitespace-before-property" warning off everywhere, not just on one line or in one file. How do I do that?
My package.json shows the following for npm start (which is what I run when the warnings appear):
"scripts": {
"start": "react-scripts start",
...
}
I am developing in WebStorm. The ESLint preferences panel has the "Enable" checkbox unchecked, so all of the ESLint configuration options in the IDE are grayed-out and presumably irrelevant, so presumably also the configuration and invocation of ESLint are happening elsewhere (e.g. built into React?).
I tried putting the following .eslintrc.json file into my project home directory:
{
"rules": {
"no-whitespace-before-property": "off"
}
}
alone as well as with "extends": "eslint:recommended".
I tried adding the following to my project's package.json file:
{
...
"eslintConfig": {
"rules": {
"no-whitespace-before-property": "off"
}
}
}
I've also tried setting the value to 0 instead of to "off".
It may or may not be relevant that I'm writing a React app, and it may or may not be relevant that I'm developing in WebStorm, but I include those facts just in case.
I've checked around on StackOverflow and can't find an answer.
The note below the errors is not coming from ESLint (error is). So I'm assuming you are using some sort of wrapper, like github.com/facebookincubator/create-react-app Those wrappers do not use .eslintrc file and can't be configured directly. You will have to read through documentation of your wrapper to figure out how to disable this rule.
In general ESLint wrappers like create-react-app, standard, xo, etc. are specifically designed to "just work", and hence remove ability to configure and fine tune styles/rules.

How to create aurelia typescript project with vs2017rc

I am new to aurelia, and I need create a prototype project of the framework. At the beginning, I planed to use skeleton-typescript-aspnetcore skeleton, but when I tried the vs2017rc, I found it uses .csproj as the default format(while vs2015 is project.json/.xproj), I think we should follow the vs2017 because we will upgrade our IDE after it's been launched.
The vs2017 have a wizard to upgrade .xproj project, but after the upgrading(skeleton-typescript-aspnetcore), there still lots of error ahead me...
I also tried aurelia-cli, but seems it has not support vs2017 yet, does anyone could give a guide to create the prototype project? I will integrate some plugins like the skeleton mentioned above, such as gulp,karma,breeze...
thank you in advance.
Since Visual Studio 2017 just launched I thought I'd answer how I solved this, as there are still many errors when using "skeleton-typescript-aspnetcore".
Using https://github.com/aurelia/skeleton-navigation/releases/tag/1.1.2 as a starting point, these are the steps to get it running:
When you first run the project you will get errors complaining that some files located in /test/ is not under 'rootDir'. In your tsconfig.json the rootDir is defined as "src/", this can be solved simply by moving your test folder inside your src folder. This will cause new errors because the paths defined in those files has now changed. You will need to edit app, child-router and users imports like this:
import {Users} from '../../users'; IntelliSense should help you out here.
The command gulp test will also not run before changing to the new path, you can change the path in karma.conf.js:
files: [
'src/test/unit/setup.ts',
'src/test/unit/*.ts'
],
Next the file users.ts will throw errors like Type 'Response' is not assignable to type 'any[]'. You will need to tell TypeScript what you're declaring like this: public users : Object = []; or simply: public users = {};
The final problem is that you're going to have a lot of duplicate identifier errors, at the time of writing this the cause of this seems to be from the changes brought on by TypeScript version 2.2.1. I don't know what specifically breaks, but I know that previous version 2.1.5 still works. So what you need to do is to run npm install typescript#2.1.5 --save in your src/skeleton directory, the --save is just to update your package.json file, you can do this on your own later as well if you wish.
After you've done that your gulp errors (20~ of them) should be resolved. But there are still some errors remaining caused by duplicate signatures. Again, things have changed in TypeScript 2.0+, there is now a simplified way of getting and using declaration files. Here is an answer on SO on how to use the #types feature: How should I use #types with TypeScript 2 , but to keep this short and sweet you will have to go to your tsconfig.json file and explicitly tell where to find the #types/node folder. It would look something like this:
"compilerOptions": {
...
"typeRoots": [
"node_modules/#types"
],
"types": [ "node" ]
...
},
Hope this helps, with these changes the project should now build and launch correctly.
EDIT:
I recently ran into some problems again with building my project. I got a lot of duplicate identifiers again... I however ran across this answer on SO: TypeScript throws multiple duplicate identifiers
Apparently TypeScript latest ships with fetch definitions out of the box, so I was able to run the command from the answer in the link:
npm uninstall #types/whatwg-fetch
And upgrading from typescript 2.1.5 to latest:
npm install typescript --save
You might even want to install typescript globally by appending -g.
Also this will continue to be an issue unless you comment out/delete url and whatwg-fetch from typings.json globalDependencies in order to prevent it from recreating itself:
"globalDependencies": {
//"url": "github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
//"whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
}
Then you can either delete the typings folder, running typings install again or edit index.d.ts in the typings folder and delete the reference paths to whatwg-fetch and url.
Hope this helps someone who might've encountered the same problems even after "fixing" it.

How to set .eslintrc to recognize 'require'?

I am new to ESLint, and I have successfully integrated ESLint with IntelliJ.
Out of the box, my integration of ESLint did not recognize node, but basic review of documentation made clear that by creating the configuration file named .eslintrc at the root of my project folder (with the proper IntelliJ setting to access this file) and setting "node":true, ESLint recognizes node (i.e., the following complete .eslintrc works).
// Contents of .eslintrc at root of project - support for Node and jQuery
{
"env" : {
"node" : true,
"jquery" : true
},
}
However, ESLint still does not recognize require(), as evidenced by this screenshot:
I have done my best in a reasonable amount of time searching for a solution to the basic question of how to get ESLint to recognize require(). In particular, I found a possible hint here, where it suggested to add "amd":false in (I presumed) the .eslintrc file - but no go.
This seems basic. How can I get .eslintrc to recognize require()?
(If, in your answer, you can provide insight how to cover more general cases, that would also be helpful. Thanks!)
Adding amd to env inside .eslintrc will enable you to use define() and require(), as per the amd spec:
{
"env": {
"amd": true
}
}
The problem is not with ESLint. If you look closely at your message, it says JSHint.
Since you're trying to configure ESLint, simplest solution would be to disable or remove JSHint plugin form your IDE.
If you still want to use JSHint along with ESLint, you can do the following:
Single file solution: add /* global require */ at the top of your file.
General solution for all files: add "node": true line to your .jshintrc.
"amd":true in env
defines require() and define() as global variables as per the amd spec.
See http://eslint.org/docs/user-guide/configuring#specifying-environments
On a Mac ... global solution. (2021)
If you are using the amazing ESLint in the amazing VS Code on Mac,
Simply go to ~ (ie /users/your-name)
edit .eslintrc.json (you can edit it in VSCode of course!)
You'll likely add
"node": true
if you're working with node, or perhaps "amd" as stated in the answers here. ("amd" gives specifically and only require and define).
This is a global solution for all workspaces you open.
Importantly, this also works if you are using VS Code "remotely", so, with no workspace. For example, you may open a file on a server just using sftp, and work on the file in VSCode. Or you may be opening just a single local file on the Mac, not part of a workspace. In both these cases the setting (eg, node=true) will in fact work - it needn't be a workspace.

Categories

Resources