configuring jest to run tests in a different folder - jestjs

I have been trying to configure Jest so it could run test cases written in another folder in the same hierarchy. But it throws the below error.
I am trying to run jest from the as_test folder while my test case files and actual code to be tested resides in asCore folder.
I think Jest is unable to find enzyme as it resides in node_modules of as_test,while the test case which uses it resides in asCore folder.
Could someone help me how solve this problem.
● Test suite failed to run
Cannot find module 'enzyme' from 'Button.test.js'
1 |
> 2 | import { shallow, mount } from 'enzyme';
| ^
3 | import Button from '../JSX/Button';
4 |
5 |
at Resolver.resolveModule (as_test/node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (asCore/components/button/__tests__/Button.test.js:2:1)
The jest config files and my development reside in the below structure.
Package.JSON
{
"private": true,
"version": "0.0.0",
"name": "example-enzyme",
"dependencies": {
"react": "16.5.2",
"react-dom": "16.5.2"
},
"devDependencies": {
"#babel/core": "^7.1.2",
"#babel/node": "^7.0.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "*",
"babel-loader": "^8.0.4",
"jest": "*",
"react-test-renderer": "*",
"enzyme": "*",
"enzyme-adapter-react-16": "*",
"enzyme-to-json": "*",
"jest-html-reporter": "*"
},
"scripts": {
"test": "jest --no-cache"
}
}
Jest.config.js
const { resolve } = require('path');
const root = resolve(__dirname, '..');
console.log(root);
module.exports = {
"verbose": true,
"rootDir": root,
"setupTestFrameworkScriptFile": "<rootDir>/as_test/config/jestSetup.js",
"collectCoverage": true,
"coverageDirectory":"<rootDir>/as_test/coverage",
"coverageReporters": [
"html", "text"
],
"moduleDirectories": ["node_modules", "bower_components", "<rootDir>/*"],
"testResultsProcessor": "<rootDir>/as_test/node_modules/jest-html-reporter",
"snapshotSerializers": ["<rootDir>/as_test/node_modules/enzyme-to-json/serializer"],
"moduleNameMapper": {
"core/extendables/reactHelper$": "<rootDir>/as_test/deps/js/reactHelper.js",
"core/components/button/JSX-generated/Button$": "<rootDir>/as_test/deps/jsx/Button"
}
};
babel.config.js
module.exports = {
presets: [['#babel/preset-env'],'#babel/preset-react'],
};
JestSetup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

Related

Weird behavior to import libraries after install Babel

After installing Babel in a backend project, it started to have a weird behavior.
All the libraries that were already installed and used in project, were using import statement, but now, only accept require method.
This is really strange, because it has situations where there are both calling methods at the same place.
For example at server.ts file:
const cors = require('cors');
import 'dotenv/config';
var corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`server runnig on port ${port}`);
});
This is babel.config.js code:
module.exports = {
presets: [
'#babel/preset-typescript',
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
plugins: ['#babel/plugin-transform-runtime'],
};
This is package.json code:
{
"engines": {
"node": "18.4.0"
},
"scripts": {
"start": "babel-node -x .ts -- server.ts",
"start-old": "ts-node -r tsconfig-paths/register server.ts",
},
"prisma": {
"seed": "ts-node prisma/seed.ts"
},
"devDependencies": {
"prettier": "^2.6.2",
},
"dependencies": {
"#aws-sdk/client-cognito-identity": "^3.128.0",
"#aws-sdk/client-s3": "^3.128.0",
"#aws-sdk/credential-provider-cognito-identity": "^3.128.0",
"#aws-sdk/s3-request-presigner": "^3.130.0",
"#aws-sdk/types": "^3.127.0",
"#babel/cli": "^7.18.6",
"#babel/core": "^7.18.6",
"#babel/node": "^7.18.6",
"#babel/plugin-transform-runtime": "^7.18.6",
"#babel/preset-env": "^7.18.6",
"#babel/preset-typescript": "^7.18.6",
"#babel/runtime": "^7.18.6",
"#prisma/client": "^4.0.0",
"#types/babel__core": "^7.1.19",
"#types/express": "^4.17.13",
"#types/node": "^17.0.40",
"aws-cli": "^0.0.2",
"aws-sdk": "^2.1172.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pino": "^8.1.0",
"prisma": "^4.0.0",
"ts-node": "^10.8.1",
"tsconfig-paths": "^4.0.0",
"typescript": "^4.7.4"
}
}
Does anyone know why this is happening, and what may be done to be possible to use import again?
Thanks a lot!

Node12/next9 SyntaxError: Cannot use import statement outside a module

I have been trying to run a project in debug mode for quite a long time and I get an import error, I have already studied a lot of information on this issue and decided to move along the path of setting up babel. The fact is that this project is working and everything started fine, but now I upgraded the version of node 10> 12, next 8> 9, went through all typescript errors, was able to build the build and tried to run it locally, but got an import error
Project: next v9, node v12
// package.json (shortcut):
{
"name": "mysite",
"version": "1.0.0",
"main": "index.js",
"description": "some",
"private": true,
"scripts": {
"dev": "nodemon server/server.ts"
},
"dependencies": {
...
"express": "^4.16.3",
"node-sass": "^4.9.3",
"next": "9.2.2",
"react": "^16.8.4",
...
},
"devDependencies": {
"#babel/plugin-proposal-decorators": "^7.1.0",
"#types/body-parser": "^1.17.0",
"#types/connect-mongo": "^0.0.38",
"#types/cookie-parser": "^1.4.1",
"#types/debug": "^4.1.0",
"#types/express": "^4.16.0",
"#types/express-session": "^1.15.10",
"#types/mongodb": "^3.1.4",
"#types/mongoose": "^5.2.6",
"#types/multer": "^1.3.7",
"#types/node": "^10.7.1",
"#types/passport": "^0.4.6",
"#types/passport-local": "^1.0.33",
"#types/react": "^16.4.11",
"#types/react-dom": "^16.0.7",
"#types/redux-form": "^7.4.7",
"#types/set-value": "^2.0.0",
"#types/shortid": "^0.0.29",
"autoprefixer": "^9.4.3",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-node": "^0.0.1-security",
"babel-plugin-import": "^1.13.3",
"babel-plugin-module-resolver": "^4.1.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-plugin-wrap-in-js": "^1.1.1",
"babel-preset-env": "^1.7.0",
"css-purify-webpack-loader": "^1.0.1",
"eslint": "^5.4.0",
"eslint-plugin-react": "^7.11.1",
"faker": "^4.1.0",
"next-purgecss": "^3.0.1",
"next-size": "^2.0.2",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"purgecss-whitelister": "^2.3.1",
"stylelint-config-recommended": "^2.1.0",
"tailwindcss": "^0.7.4",
"ts-node": "^7.0.1",
"typescript": "^3.0.1",
"webpack-pwa-manifest": "^4.0.0"
}
}
// server.ts:
import bodyParser from 'body-parser';
... // other lib imports, config imports, middlevare, routes
import middlewareOAuth from './middlewareOAuth';
...
import authRoute from './routes/auth';
...
const app = next({ dev: config.dev });
app.prepare()
.then(() => {
const server = express();
...
server.use() // connecting middleware, passports, routes and others
// babel.rc
{
"plugins": [
[
"module-resolver",
{
"root": ["."],
"alias": {
"app": "./app",
"pages": "./pages",
"server": "./server",
"styles": "./styles",
"wavesurfer.js": "./wavesurfer.js"
},
"extensions": [ ".wasm", ".mjs", ".js", ".jsx", ".json", ".ts", ".tsx" ],
"cwd": "babelrc"
}
],
["#babel/plugin-proposal-decorators", { "legacy": true }],
"transform-class-properties",
[
"import",
{
"libraryName": "antd",
"style": "css"
}
]
],
"presets": [
["next/babel",
{
"preset-env": { "targets": { "node": "current" } }
}
]
],
"ignore": []
}
When I use yarn dev command in console:
$ nodemon server/server.ts
[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): server/**/*.ts
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node --compiler-options '{"module":"commonjs"}' server/server.ts`
[nodemon] app crashed - waiting for file changes before starting...
When I want to see what kind of error occurred I use the command: ts-node server/server.ts and get an error =>
/home/roma/project/mysite/server/server.ts:1
import bodyParser from 'body-parser';
^^^^^^
SyntaxError: Cannot use import statement outside a module
What am I missing or not doing? Thanks!
Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.
answered in: https://stackoverflow.com/a/60225870/16471349

Why is contextBridge not being imported in my Electron app?

I'm writing an Electron app with React and Typescript, using Webpack, Babel and ESLint but I'm having trouble setting:
mainWindow = new BrowserWindow({
title: "Biomech",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
sandbox: true,
preload: path.join(__dirname, "./preload.js"),
nativeWindowOpen: true,
},
});
which I want as a security measure.
The reason being that, if I set the webPreferences as specified above, I need to use contextBridge and a preload script that binds the functions that are using IPC to the window. And the problem is that contextBridge is not being properly imported in my preload.ts:
import { contextBridge, ipcRenderer } from "electron";
import { readFileSync } from 'fs';
import { History } from 'history';
import { LIST_DRIVE_FILES_CHANNEL, LOAD_PREV_TEST_RESULTS_CHANNEL, OAUTH2_ACCESS_TOKEN_REQUEST_CHANNEL } from "../src/constants/ipcChannels";
import { VISUALIZE_RESULTS_PATH } from "../src/constants/urls";
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
exchangeCodeForAccessToken: (code: string) => {
ipcRenderer.invoke(OAUTH2_ACCESS_TOKEN_REQUEST_CHANNEL, code);
},
listDriveFiles: (accessToken: string) => {
ipcRenderer.invoke(LIST_DRIVE_FILES_CHANNEL, accessToken);
},
openDirectoryDialog: (history: History) => {
ipcRenderer.invoke(LOAD_PREV_TEST_RESULTS_CHANNEL).then((dialog: any) => {
if (dialog.canceled) { // canceled with one l is correct
return;
} else {
const selectedDirectory = dialog.filePaths[0];
console.log(readFileSync(selectedDirectory + "/README.md", 'utf-8'));
history.push(VISUALIZE_RESULTS_PATH);
}
})
}
}
);
The way I see it it's properly used like the examples I've seen here in SO, or in the Electron docs. But when I run my main process script: npm run dev:electron which is specified in my package.json:
{
"name": "electron-react-ts-app",
"version": "1.0.0",
"description": "Electron + React + Typescript",
"main": "./dist/main.js",
"preload": "./dist/preload.js",
"scripts": {
"dev": "concurrently --success first \"npm run dev:electron\" \"npm run dev:react\" -k",
"dev:electron": "NODE_ENV=development webpack --config webpack.electron.config.js --mode development && electron .",
"dev:react": "NODE_ENV=development webpack serve --config webpack.react.config.js --mode development",
"build:electron": "NODE_ENV=production webpack --config webpack.electron.config.js --mode production",
"build:react": "NODE_ENV=production webpack --config webpack.react.config.js --mode production",
"build": "npm run build:electron && npm run build:react",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"lint": "eslint .",
"format": "prettier --write \"**/*.+(js|jsx|json|yml|yaml|css|md|vue)\""
},
"keywords": [],
"license": "MIT",
"build": {
"files": [
"dist/",
"node_modules/",
"package.json"
],
"productName": "Example",
"appId": "com.example.app",
"directories": {
"output": "dist"
}
},
"devDependencies": {
"#babel/preset-env": "^7.9.5",
"#babel/preset-react": "^7.9.4",
"#babel/preset-typescript": "^7.9.0",
"#types/electron-devtools-installer": "^2.2.0",
"#types/react-router-dom": "^5.1.7",
"#types/regenerator-runtime": "^0.13.0",
"dpdm": "^3.6.0",
"electron": "^11.2.1",
"electron-builder": "^22.7.0",
"electron-devtools-installer": "^3.1.1",
"eslint": "^7.18.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.1",
"husky": "^4.3.8",
"lint-staged": "^10.5.3",
"prettier": "^2.2.1",
"react-router-dom": "^5.2.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^3.11.1"
},
"dependencies": {
"#babel/core": "^7.12.10",
"#popperjs/core": "^2.6.0",
"#types/node": "^14.14.22",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"axios": "^0.21.1",
"babel-loader": "^8.2.2",
"bootstrap": "^4.5.3",
"chokidar": "^3.5.1",
"core-js": "^3.8.3",
"css-loader": "^5.0.1",
"electron-fetch": "^1.7.3",
"fsevents": "^2.3.1",
"ini": "^2.0.0",
"jquery": "^3.5.1",
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-google-login": "^5.2.2",
"style-loader": "^2.0.0"
},
"husky": {
"hooks": {
"pre-commit": "npm run lint && npm run format"
}
},
"lint-staged": {
"*.+(js|jsx)": "eslint --fix",
"*.+(json|css|md)": "prettier --write"
}
}
I get the following error: Cannot read property 'exposeInMainWorld' of undefined
webpack 5.19.0 compiled successfully in 1793 ms
App threw an error during load
TypeError: Cannot read property 'exposeInMainWorld' of undefined
at Object../electron/preload.ts (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:24:53)
at __webpack_require__ (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:128:41)
at /Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:252:11
at Object.<anonymous> (/Users/lucas_sg/Documents/ITBA/PF/pf-biomech/dist/preload.js:254:12)
at Module._compile (internal/modules/cjs/loader.js:1152:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1173:10)
at Module.load (internal/modules/cjs/loader.js:992:32)
at Module._load (internal/modules/cjs/loader.js:885:14)
at Function.f._load (electron/js2c/asar_bundle.js:5:12738)
at Module.require (internal/modules/cjs/loader.js:1032:19)
I've checked out this repo regarding Electron security and it doesn't look like he's doing things too different, at least at first glance, but I'm clearly messing something up.
Here's my webpack config (webpack.electron.config.js) in case it's useful:
const path = require("path");
module.exports = [
{
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
devtool: "source-map",
entry: {
main: {
import: "./electron/main.ts",
dependOn: "preload"
},
preload: "./electron/preload.ts"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
},
target: "electron-main",
module: {
rules: [
{
test: /\.(js|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
node: {
__dirname: false,
},
},
];
I think the issue resides in you webpack.config file:
entry: {
main: {
import: "./electron/main.ts",
dependOn: "preload"
},
preload: "./electron/preload.ts"
},
Might be that webpack tries to resolve all "preload.ts" dependency at compile time, plus tries to bundle it together with main.ts file. And in such case it will never get access to contextBridge. The preload.js file should only be run in a separate "context" - "Isolated World" as they refer in the docs.
What I would try is:
remove the dependOn: and preload: lines from you webpack config.
convert preload.ts file to JS (ie. to CommonJS format) - try doing that with TS CLI for now
Your preload.js file should look more or less like this:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
copy preload.js to a __dirname (in my case it was /dist)
run electron again
That was the only way I could access "contextBridge" object.

Jest Babel Error: Test suite failed to run

Here's my package.json
{
"name": "js-stack",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"start": "babel-node src",
"test": "eslint src && flow && jest --coverage"
},
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^26.0.1",
"babel-preset-env": "^1.7.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react": "^6.24.1",
"eslint": "^7.1.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-plugin-compat": "^3.7.0",
"eslint-plugin-flowtype": "^5.1.3",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^2.5.0 || ^1.7.0",
"flow-bin": "^0.126.1",
"jest": "^26.0.1",
"react": "^16.13.1"
},
"browserslist": [
"> 1%"
]
}
Here's my .babelrc file
{
"presets": [
"env",
"react",
"flow"
]
}
While it got me the error
Test suite failed to run
Plugin/Preset files are not allowed to export objects, only functions.
In /Users/Codes/Javascript/js-stack/node_modules/babel-preset-react/lib/index.js
Could Someone tell me how to deal with it? I tried some solutions as they said but still get it! SO confused!!!! THX
Remember having a problem similar to this before. have you tried getting rid of the .babelrc with babel.config.js ? This is how the file will look like
/* eslint-disable func-names */
module.exports = function (api) {
const presets = [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-flow'
];
const plugins = [];
api.cache(false);
return {
presets,
plugins
};
};

ES2015 modules does not work in Node.js with Babel.js?

I want to use ES2015 modules in Node.js with babel.js compiler, but it won't work. Here is what I have:
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel-core": "^6.9.0",
"babel-plugin-transform-runtime": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-node5": "^11.1.0",
}
}
.babelrc
{
"presets": ["es2015"],
"plugins": [
"transform-runtime"
]
}
server/index.js
require('babel-core').transform('code', {
presets: ['node5'],
});
import { test } from './file1';
console.log(test);
server/file1.js
export const test = 'its working!';
But console throws error SyntaxError: Unexpected token import
Does ES2015 modules not working in node5, or I am doing something wrong here? Appreciate your help.
Please install babel-register npm module and require this in index.js
server/index.js
require('babel-register');
import { test } from './file1';
console.log(test);
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel": "^6.5.2",
"babel-preset-es2015": "^6.6.0",
"babel-register": "^6.8.0"
}
}
.babelrc
{presets:[es2015]}
for me it works
Thanks

Resources