Jest "testRegex" throws "Unexpected token . in JSON" - jestjs

I'm using jest to unit test my server and when I set the "testRegex" on my package.json to be
"testRegex": "(/test/.*|(\.|/)test)\.js$"
I get this error: Unexpected token . in JSON
Any ideas?

"\." is invalid escape character in JSON. You need to escape the backslash:
"testRegex": "(/test/.*|(\\.|/)test)\\.js$"

Related

Node.js VSCode Debugger Missing Env Variables

When I run the debugger in vscode I get this error:
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
I realized this was because the debugger isn't getting access to my .env file. My database uri is stored in my .env file. So the debugger can't see it.
How can I give my debugger access to the my .env file variables?
I fixed it by adding this to my launch.json file in my .vscode workspace folder. I added two values to the configurations object:
"env": { "PORT": "4000" },
"envFile": "${workspaceFolder}/backend/.env"

Jest "Cannot find module" with typescript paths in CI

On the Gitlab-CI environment 2 of our Jest tests fail with Cannot find module.
The strange thing is that it works on my local Win10 machine - even when I run the tests in a similar docker-container (node 12.12.0).
Here is the console output:
FAIL apps/server/src/domain/dashboard/permission-group.service.spec.ts
Test suite failed to run
Cannot find module '#cm/utils-server' from 'license.service.ts'
9 | isLicenseFileContent,
10 | LicenseStatus,
> 11 | parseLicenseInfo
| ^
12 | } from '#cm/license-shared';
13 | import { ExitCode } from '../../util/exit-codes';
14 | import { readFile } from '#cm/utils-server';
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (src/domain/license/license.service.ts:11:24)
I am not sure how to correctly interpret this output:
permission-group.service.spec.ts: this is the test that fails
Cannot find module '#cm/utils-server' from 'license.service.ts':
Ok, the test or some of its dependencies, use license.service.ts and in the license.service.ts file the '#cm/utils-server' module cannot be found.
What is the meaning of error-indicator (> at parseLicenseInfo)?
This is for the import #cm/license-shared - not for #cm/utils-server as indicated by the error message in 2
#cm/utils-server is also imported, but 2 lines below in line 14: So is this maybe just a bug in jest?
I just had this issue and searched for some solutions. Found this site which gave a clue about what could be done: to configure Jest's moduleNameMapper property.
So, reading the documentation I found this solution:
Open the tsconfig.json and jest.config.js files (or equivalent)
In tsconfig.json, find your absolute paths definition. My configuration looks like this:
"paths": {
"#modules/*": ["modules/*"],
"#config/*": ["config/*"],
"#shared/*": ["shared/*"]
}
In the jest.config.json, find and uncomment the moduleNameMapper property and start to translate your TS absolute paths into the Jest mapper syntax. Sounds complicated, but it isn't:
moduleNameMapper: {
"#modules/(.*)": "<rootDir>/src/modules/$1",
"#config/(.*)": "<rootDir>/src/config/$1",
"#shared/(.*)": "<rootDir>/src/shared/$1",
}
The <rootDir> if defined automatically, and points to the package.json directory
"#modules/(.*)" is a Regex for "any string starting with '#module/' followed by anything after it
"<rootDir>/src/modules/$1" is the corresponding directory. $1 is a pointer to the Regex expression between the parenthesis ((.*)). Other expressions will be pointed by $2, $3 and so on
After doing this, I was able to execute my tests without any problem.
Console output before follow the above steps:
$ jest
FAIL src/modules/appointments/services/CreateAppointmentService.spec.ts
● Test suite failed to run
Cannot find module '...'
Console output after:
$ jest
PASS src/modules/appointments/services/CreateAppointmentService.spec.ts
Hope this help someone,
Thanks!
For those who are facing this issue in 2022. Please add this code in your
jest-unit.json (or your jest config json file).
"moduleDirectories": ["<rootDir>/../", "node_modules"]
Result:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".\\.spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleDirectories": ["<rootDir>/../", "node_modules"]
}
For now we use a workaround: we had paths defined in multiple tsconfig.json files of our mono-repo. We moved all paths up to the root-tsconfig and now the tests work again.
But we don't really understand why this works.
And a drawback is that it's now easy to accidentally refer to a path that you shouldn't use in the lib (because the IDE now always uses all paths for code-assistance)
I meet the same problem, I found the reason is the package(which cannot found) doesn't set the main field in package.json, add it then everythings ok.

"dotenv: error when sourcing '.env' file"?

Every time I cd a particular directory using either Terminal or iTerm2 (I'm running Macos 10.14.5, Node 12.13.0), I get the following error that seems to be complaining about an ´.env´ file provided to me by my team. They are not getting the error.
.env:22: parse error near '}'
dotenv: error when sourcing '.env' file
.env:22: parse error near '}'
Line 22, which seems to be causing the error is
COOKIE_SETTINGS={"isSecure": false, "isSameSite": false, "isHttpOnly": true, "encoding": "base64json", "path": "/"}
Any clue how I might remedy this? Thanks for any insights.
You can't store objects inside .env file.
The solution is to:
Stringify JSON object and save as env variable. Then parse and use it when you need your object.
Another solution is to write variables like this:
COOKIE_SETTINGS_IS_SECURE = false
COOKIE_SETTINGS_IS_SAME_SITE = false
...
This seem error when parsing env.
I think env just support like string or number for this case.
Maybe you can use in .env
COOKIE_SETTINGS="{'isSecure': false, 'isSameSite': false, 'isHttpOnly': true, 'encoding': 'base64json', 'path': '/'}"
In JS just use JSON.parse to turn back to Object
cookieSettings= process.env.DB_HOST ? JSON.parse(process.env.DB_HOST) : null;

Electron register protocol not working

I am trying this:
https://electron.atom.io/docs/api/protocol/
And I get this error:
https://google.com/#q=standard%2Fno-callback-literal Unexpected literal in error position of callback
Why is it not working?
Solution is to install this so the callback can work:
https://github.com/xjamundx/eslint-plugin-standard

node.js send object from server to client console for debugging

How can I pass an object from server to client make it looking like this in the console?
I tried to use util.inspect(myObject, {showHidden: false, depth: null}),
but it returns a string and I cannot fold/unfold it in the console:
I tried to convert it to an object using var obj = JSON.parse(str);, but it gives me an error:
Uncaught SyntaxError: Unexpected token S in JSON at position 0
or var obj=eval("("+str+")");, but it gives me an error:
Uncaught SyntaxError: Unexpected token {
If you are using devtool or node monkey to connect node.js to your console, then you can simply use:
console.log(myObject);
Or for a more detailed view:
console.dir(myObject);
Node Inspector seems to have (had?) some issues with console ouput.
If you wish to log to stderr instead of stdout you can use:
console.error('%o',myObject)

Resources