Jest issue when I run the test cases via the command - javascript

I am newbie on Jest and I have the following issue when I execute the command
npm test
I have the following files
functions.js
const functions = {
add: (num1,num2) => num1 + num2
};
module.exports = functions;
and the functions.test.js
const functions = require('./functions');
test(`Adds 2 + 2 to equal 4`, ()=>{
expect(functions.add(2,2)).toBe(4);
});
my package.json has the following context
{
"name": "jest-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.2.2"
}
}
I havent found a lot of resources on the internet regarding the error I just try to remove the dot (.) character from the node_modules/jest
and the output of the console (error) is below
> jest-tutorial#1.0.0 test
> jest
C:\Users\agiallelis\node_modules\jest-cli\build\run.js:129
if (error?.stack) {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:1054:16)
at Module._compile (internal/modules/cjs/loader.js:1102:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (C:\Users\agiallelis\node_modules\jest-cli\build\index.js:12:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)

Related

Both Require and import not working javascript

I am trying to create a cli tool to make a todo list. For some reason I can't figure out I'm unable to use either require or import when trying to import the Chalk package for highlighting terminal outputs
here is what I have for my index.js file
#! /usr/bin/env node
const { program } = require("commander");
const list = require("./commands/list.js");
program.command("list").description("List all the TODO tasks").action(list);
program.parse();
Here is my list.js file
#! /usr/bin/env node
const conf = new (require("conf"))();
const chalk = require("chalk");
function list() {
const todoList = conf.get("todo-list");
if (todoList && todoList.length) {
console.log(
chalk.blue.bold(
"Tasks in green are done. Tasks in yellow are still not done."
)
);
todoList.forEach((task, index) => {
if (task.done) {
console.log(chalk.greenBright(`${index}. ${task.text}`));
} else {
console.log(chalk.yellowBright(`${index}. ${task.text}`));
}
});
} else {
console.log(chalk.red.bold("You don't have any tasks yet."));
}
}
module.exports = list;
and my package.json file
{
"name": "near-clear-state",
"version": "1.0.0",
"description": "Tool to let NEAR users clear the state of their account ",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "commonjs",
"author": "Dorian",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"near-api-js": "^0.44.2"
},
"bin": {
"near-clear-state": "./index.js"
}
}
when I try running anything from this cli tool I'm making I get this error if I use require
➜ near-clear-state near-clear-state --help
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4
const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/node_modules/chalk/source/index.js from /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js not supported.
Instead change the require of index.js in /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4:15)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14) {
code: 'ERR_REQUIRE_ESM'
}
Or this error when i use import
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:3
import { Chalk } from "chalk";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Node.js v17.4.0
Please help me
Use the import syntax, and add "type": "module" into your package.json to allow for ES6 imports.

Error when import firebase-functions-test when testing with mocha

I am trying to setup a Firebase Cloud Functions repo to run mocha test. However, it throws the following error when I use import * as firebase from "firebase-functions-test"; or const firebase = require("firebase-functions-test")();. You can see in my code that I haven't even called the actual firebase functions yet so I think this a setup issue.
Question: What change do I need to make mocha test running for Firebase Functions testing using import syntax?
Working test code
import { assert } from "chai";
describe("Sanity Check", () => {
it("should pass", () => {
assert.equal(0, 0);
});
});
Failed Test Code using require
const test = require("firebase-functions-test")();
import { assert } from "chai";
describe("Sanity Check", () => {
it("should pass", () => {
assert.equal(0, 0);
test.cleanup();
});
});
Failed code using import
import * as firebase from "firebase-functions-test";
import { assert } from "chai";
const test = firebase();
describe("Sanity Check", () => {
it("should pass", () => {
assert.equal(0, 0);
test.cleanup();
});
});
Error for the failure
> functions# test /Users/cupidchan/temp/functions
> mocha -r ts-node/register test/**/*.spec.ts
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/encoder' is not defined by "exports" in /Users/cupidchan/temp/functions/node_modules/firebase-functions/package.json
at new NodeError (internal/errors.js:322:7)
at throwExportsNotFound (internal/modules/esm/resolve.js:322:9)
at packageExportsResolve (internal/modules/esm/resolve.js:545:3)
at resolveExports (internal/modules/cjs/loader.js:450:36)
at Function.Module._findPath (internal/modules/cjs/loader.js:490:31)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:888:27)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/cupidchan/temp/functions/node_modules/#cspotcode/source-map-support/source-map-support.js:679:30)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (/Users/cupidchan/temp/functions/node_modules/firebase-functions-test/lib/providers/firestore.js:26:19)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (/Users/cupidchan/temp/functions/node_modules/firebase-functions-test/lib/features.js:9:19)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at module.exports (/Users/cupidchan/temp/functions/node_modules/firebase-functions-test/lib/index.js:30:20)
at Object.<anonymous> (/Users/cupidchan/temp/functions/test/index.spec.ts:9:14)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/Users/cupidchan/temp/functions/node_modules/ts-node/src/index.ts:1371:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions.<computed> [as .ts] (/Users/cupidchan/temp/functions/node_modules/ts-node/src/index.ts:1374:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.exports.requireOrImport (/Users/cupidchan/temp/functions/node_modules/mocha/lib/nodejs/esm-utils.js:56:20)
at async Object.exports.loadFilesAsync (/Users/cupidchan/temp/functions/node_modules/mocha/lib/nodejs/esm-utils.js:88:20)
at async singleRun (/Users/cupidchan/temp/functions/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at async Object.exports.handler (/Users/cupidchan/temp/functions/node_modules/mocha/lib/cli/run.js:374:5)
npm ERR! Test failed. See above for more details.
package.json
{
"name": "functions",
"scripts": {
"lint": "eslint --ext .js,.ts .",
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log",
"test": "mocha -r ts-node/register test/**/*.spec.ts --reporter spec"
},
"engines": {
"node": "14"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1"
},
"devDependencies": {
"#types/chai": "^4.2.22",
"#types/mocha": "^9.0.0",
"#types/node": "^16.11.11",
"#typescript-eslint/eslint-plugin": "^3.9.1",
"#typescript-eslint/parser": "^3.8.0",
"chai": "^4.3.4",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-prettier": "^4.0.0",
"esm": "^3.2.25",
"firebase-functions-test": "^0.2.3",
"mocha": "^9.1.3",
"prettier": "^2.5.0",
"ts-node": "^10.4.0",
"typescript": "^3.8.0"
},
"private": true
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017"
},
"compileOnSave": true,
"include": ["src", "test"]
}
This error should be resolved after specifying the latest version of the
firebase-functions, v3.16.0, and
firebase-functions-test, v0.3.3.

node js MODULE_NOT_FOUND error in node_modules

I am new to javascript and I am having import issues.
I have installed the jquery.csv lib as npm i jquery.csv but then node is not able to import it. (this was the procedure described in https://github.com/typeiii/jquery-csv)
Here is the structure of my project:
lucapuggini#lucas-MBP js_utils % ls
index.js index.js~ node_modules package-lock.json package.json
lucapuggini#lucas-MBP js_utils % ls node_modules
jquery-csv
lucapuggini#lucas-MBP js_utils % cat index.js
var csv = require('./jquery.csv.js');
console.log("Start index.js")
lucapuggini#lucas-MBP js_utils % cat package-lock.json
{
"name": "js_utils",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"jquery-csv": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/jquery-csv/-/jquery-csv-1.0.11.tgz",
"integrity": "sha512-KDPc3wFLTFO68p/4IqsODZCjBp+y9axDa/pr36pDKrWk6yyHf8Nk1FqAGXvaUb6H7J1zJSYszABIFj0a40QXRA=="
}
}
}
lucapuggini#lucas-MBP js_utils % node index.js
node:internal/modules/cjs/loader:922
throw err;
^
Error: Cannot find module './jquery.csv.js'
Require stack:
- /Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:15)
at Function.Module._load (node:internal/modules/cjs/loader:763:27)
at Module.require (node:internal/modules/cjs/loader:991:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js:2:11)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js'
]
}
lucapuggini#lucas-MBP js_utils %
Why am I getting this error?
It seems their documentation is incorrect. You need to require the npm module like this:
const csv = require('jquery-csv');

Troubles with using gulp-eslint

Im trying to add gulp-eslint to my build process, having gulp watch my files and run eslint whenever a file is changed. However, I am getting an error that says:
D:\code\project\node_modules\gulp-eslint\index.js:4
const {CLIEngine} = require('eslint');
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (D:\code\project\gulpfile.js:5:16)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
when I try to run the ESLint task that I wrote.
Here is the code for the eslint task:
gulp.task('eslint', () => {
return gulp.src(lintscripts)
.pipe(eslint({
"env": {
"browser": true,
"node": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2017
},
"rules": {
'no-console': 'off',
'indent' : 'off',
"semi": [
"error",
"always"
]
}
})).pipe(eslint.format());
});
Please check your node version. You are using object destructuring which is available from Node v6. If you're using node v4 then this might not work.

Including local npm libraries

I am using the serverless framework to develop lambda functions in the aws cloud. Currently, I am running into an issue when including a library that I made. It seems the recommended way to do this is to either:
1) npm install <path/to/your/lib>
2) npm link and related commands
In the first situation, when using npm install ../libs, and include the module using const Libs = require('libs') , the package appears to install correctly (it is listed in the package.json). However, on uploading the service to aws or using sls invoke local -f my-func the following error is thrown:
{ Error: Cannot find module 'libs'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:419:18)
at __webpack_require__ (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:20:30)
at Object.<anonymous> (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:376:16)
at __webpack_require__ (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:20:30)
at Object.defineProperty.value (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:63:18)
at Object.<anonymous> (/Users/Documents/GitHub/serverless-cloud-functions/dynamodb-stream-handlers/.webpack/service/service-provider-users-archive-stream-handler.js:66:10)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at AwsInvokeLocal.invokeLocalNodeJs (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:258:33)
at AwsInvokeLocal.invokeLocal (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:125:19)
at AwsInvokeLocal.tryCatcher (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:773:18)
at tryOnImmediate (timers.js:734:5)
at processImmediate [as _immediateCallback] (timers.js:711:5) code: 'MODULE_NOT_FOUND' }
Using npm link gives similar results as well. I have a hunch that the issue has to do with the fact that I'm using babel and webpack, but I'm not sure.
Here is the contents of my webpack.config.js file:
const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: slsw.lib.entries,
target: "node",
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: __dirname,
exclude: /node_modules/
}
]
},
};
Including the individual clients, instead of the overall lib seems to have solved the above error, but now I am faced with a new error.
Here is the serverless.yml file:
service: instant-response-api
plugins:
- serverless-webpack
- serverless-domain-manager
- serverless-plugin-aws-alerts
custom:
alerts:
topics:
alarm: ${file(./env.yml):${opt:stage}.ADMIN_SNS_TOPIC_ARN}
alarms:
- functionErrors
webpackIncludeModules: true
customDomain:
domainName: ${file(./env.yml):${opt:stage}.DOMAIN_NAME}
basepath: ''
stage: ${opt:stage}
createdRoute53Record: true
provider:
name: aws
runtime: nodejs6.10
region: us-west-2
stage: ${opt:stage}
environment:
${file(./env.yml):${opt:stage}}
iamRoleStatements:
- Effect: "Allow"
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
- dynamodb:DescribeTable
Resource: "arn:aws:dynamodb:us-west-2:*:*"
- Effect: "Allow"
Action:
- sns:Publish
- sns:CreateTopic
Resource: "arn:aws:sns:*:*:*"
functions:
create-service-provider-number:
handler: create-service-provider-number.main
memorySize: 3008
timeout: 30
logRetentionInDays: 30
events:
- http:
path: create-service-provider-number/{serviceProviderId}
method: post
cors: true
alarms:
- functionErrors
service-provider-sms-handler:
handler: service-provider-sms-handler.main
memorySize: 3008
timeout: 30
logRetentionInDays: 30
events:
- http:
path: service-provider-sms-handler/{serviceProviderId}
method: post
cors: true
alarms:
- functionErrors
end-user-voice-handler:
handler: end-user-voice-handler.main
memorySize: 3008
timeout: 30
logRetentionInDays: 30
events:
- http:
path: end-user-voice-handler/{userId}/{propertyId}
method: post
cors: true
alarms:
- functionErrors
end-user-sms-handler:
handler: end-user-sms-handler.main
memorySize: 3008
timeout: 30
logRetentionInDays: 30
events:
- http:
path: end-user-sms-handler/{userId}/{propertyId}
method: post
cors: true
alarms:
- functionErrors
And here is package.json:
{
"name": "instant-response-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"aws-sdk": "^2.177.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-3": "^6.24.1",,
"jest": "^22.4.2",
"jest-cli": "^22.1.4",,
"serverless-domain-manager": "^2.1.0",
"serverless-plugin-aws-alerts": "^1.2.4",
"serverless-webpack": "^4.2.0",
"webpack": "^3.10.0",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"#google/maps": "^0.4.5",
"babel-runtime": "^6.26.0",
"query-string": "^5.0.1",
"twilioClient": "file:../libs/twilioClient",
"dynamodbClient": "file:../libs/dynamodbClient",
"snsClient": "file:../libs/snsClient"
}
}
My new error:
START RequestId: a9962b1d-21dd-11e8-bc1e-35d1e2dcfd8e Version: $LATEST
Syntax error in module 'service-provider-sms-handler': SyntaxError
async sendSms({to, from, msg}) {
^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
END RequestId: a9962b1d-21dd-11e8-bc1e-35d1e2dcfd8e
REPORT RequestId: a9962b1d-21dd-11e8-bc1e-35d1e2dcfd8e Duration: 5.62 ms Billed Duration: 100 ms Memory Size: 3008 MB Max Memory Used: 22 MB

Categories