Mocha: You need to instantiate using the "new" keyword - node.js

I am just exploring mocha and I am facing a strange error. I have a not project and want to write some tests.
I have installed the node
npm install --save-dev mocha
My code is:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = Web3(ganache.provider());
class Car{
park(){
return 'stopped!';
}
drive(){
return 'vroom';
}
}
describe('Car', () => {
it('Can be', () => {
const car = new Car();
assert.equal(car.park(), 'stopped!');
})
})
I have also updated the Script element in the package.json
"scripts": {
"test": "mocha"
},
When I run the test using the command:
npm run test
I am getting the following Error:
Error: You need to instantiate using the "new" keyword.
Stack Trace:
> blockchain#1.0.0 test
> mocha
Error: You need to instantiate using the "new" keyword.
at Object.packageInit (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3-core/lib/index.js:27:15)
at Web3 (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3/lib/index.js:39:10)
at Object.<anonymous> (/Users/username/Blockchain/BlockchainEtherium/blockchain/test/inbox.test.js:5:14)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Function.Module._load (node:internal/modules/cjs/loader:834:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at ESMLoader.import (node:internal/modules/esm/loader:409:24)
at importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
at formattedImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
at Object.exports.requireOrImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:38:28)
at Object.exports.loadFilesAsync (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
at singleRun (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at Object.exports.handler (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run.js:370:5)
Looking forward to your help.
Thanks

Just instantiate Web3 with the new keyword as the error message suggests.
Change
const web3 = Web3(ganache.provider());
To
const web3 = new Web3(ganache.provider());

Related

SyntaxError: Cannot use import statement outside a module using puppeteer

Hello I keep trying to run the puppeteer test but keep getting this issue. Please help thanks.enter image description here
code:
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://developers.google.com/web/');
// Type into search box.
await page.type('.devsite-search-field', 'Headless Chrome');
// Wait for suggest overlay to appear and click "show all results".
const allResultsSelector = '.devsite-suggest-all-results';
await page.waitForSelector(allResultsSelector);
await page.click(allResultsSelector);
// Wait for the results page to load and display the results.
const resultsSelector = '.gsc-results .gs-title';
await page.waitForSelector(resultsSelector);
// Extract the results from the page.
const links = await page.evaluate(resultsSelector => {
return [...document.querySelectorAll(resultsSelector)].map(anchor => {
const title = anchor.textContent.split('|')[0].trim();
return `${title} - ${anchor.href}`;
});
}, resultsSelector);
// Print all the files.
console.log(links.join('\n'));
await browser.close();
})();
error:
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:74:18)
at wrapSafe (node:internal/modules/cjs/loader:1128:20)
at Module._compile (node:internal/modules/cjs/loader:1169:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
at Module.load (node:internal/modules/cjs/loader:1068:32)
at Module._load (node:internal/modules/cjs/loader:909:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I have tried reinstalling node js and npm but nothing has worked.
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
Add type:module in your package.json file or install the latest Nodejs

How do I Fix a Cannot find module '.functions/handleCommands.js' error?

Upon running my Bot to have it sign-on after installing a command and event handler I got the error
Error: Cannot find module '.functions/handleCommands.js'
Require stack:
C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:14:9
at Object.<anonymous> (C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:19:3)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) { code:
'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\levan\\Desktop\\Discordbot\\Bot Templates\\2 command handling\\src\\bot.js'
After looking thru the folder functions and the handleCommands.js, I Still cannot figure out what I'm missing or what I might on messed up. I thought that maybe my module.exports was in the wrong place but moving things around did not solve the issue either.
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const clientId = 'redacted'; // your bots token
const guildId = 'redacted'; // the server id the bot will be on
module.exports = (clinet) => {
clinet.handleCommands = async (commandFolders, path) =>{
clinet.commandArray = [];
for(folder of commandFolders){
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
clinet.commandArray.push(command.data.toJSON());
}
}
};
};
const rest = new REST({ version: '9' }).setToken(process.env.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: clinet.commandArray },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
As the error was MODULE_NOT_FOUND I figured that maybe I didn't run all the installs I need to make my bot work. After running thru my npm lists the error persisted.
NPM's Installed
"npm init"
"npm install discord.js"
"npm install dotenv"
"npm install discord.js dotenv"
"npm install #discordjs/rest discord-api-types #discordjs/builders"
My goal is to be the Bot back online and to figure out how to troubleshoot this sort of error in case it comes up again. Any help you can give will be greatly appreciated.
'.functions/handleCommands.js' should have been './functions/handleCommands.js' Caffeine is not a substitute for sleep

GraphQL Tutorial - Expected undefined to be a GraphQL schema

I try to learn GraphQL. I created a project and I did what this page says.
Install
npm init
npm install graphql --save
Server.js
var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});
Run
node server.js
This returns me an error.
throw new Error(
^
Error: Expected undefined to be a GraphQL schema.
at assertSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\schema.js:35:11)
at validateSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\validate.js:34:28)
at graphqlImpl (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:52:64)
at C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:43
at new Promise (<anonymous>)
at graphql (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:10)
at Object.<anonymous> (C:\Users\BK\Projects\Test\graphql-test\server.js:18:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
Versions
graphql: "^16.0.1"
node : v16.13.0
I was following the same tutorial and I had the same problem. After going to the next page, as U Rogel suggested, I had the following problem:
Could not resolve dependency:
npm ERR! peer graphql#"^14.7.0 || ^15.3.0" from express-graphql#0.12.0
npm ERR! node_modules/express-graphql
So, I decided to modify my graphql version in the package.json:
"dependencies": {
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^14.7.0"
}
Then I ran npm install, went back to the first page and it worked!
I think the problem is that version 16+ does not work with the basic examples.

How to bundle worker_thread dependencies with webpack

I'm writing an electron application that uses electron forge for setup and configuration.
The project uses Webpack 5 as a bundler and typescript as the development language. I'm having trouble running a worker_thread on the main-thread.
It all works fine, as long as the worker_thread does not use any imported local modules. But when I import modules they can't be found. I'm thinking this is because webpack doesn't bundle the dependencies from the worker.
My code looks like this:
index.ts (electron main thread):
ipcMain.handle('export', async (event, measurements: Measurement[], options: ExportOptions) => {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./export.worker.js', import.meta.url))
worker.on('message', resolve)
worker.on('error', reject)
worker.postMessage({
measurements,
options,
})
})
})
export.worker.js (same folder as main.ts):
const { parentPort } = require('worker_threads')
const { Export } = require('../preload/export')
parentPort.on('message', async (data) => {
const { measurements, options } = data
await Export.export(measurements, options)
parentPort.close()
})
When I try to run this I get:
Error occurred in handler for 'export': Error: Cannot find module '../preload/export'
Require stack:
- C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:737:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js:2:20)
at Module._compile (internal/modules/cjs/loader.js:1083:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1113:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Development\\spectro-demo\\internal-client\\.webpack\\main\\a3142abb2db60e4fab06.js'
]
}
So I'm wondering: How can I use worker_threads that reference modules in my project?
I was able to fix it. Seems to be a bug in webpack 5. See this repo for a workaround: https://github.com/DustinJSilk/web-worker-ts-webpack-test

Mongorito: save(...).then is not a function

I tried something similar to the example given on the readme.md file:
var Mongorito = require('mongorito');
var Model = Mongorito.Model;
Mongorito.connect('mongodb://localhost:27017/cr-test');
class User extends Model {
collection() {
return 'users';
}
}
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
user1.save().then(() => {
console.log('User Created');
});
when I run node --harmony server.js I get this error:
user1.save().then(() => {
^
TypeError: user1.save(...).then is not a function
at Object.<anonymous> (...\app\server.js:24:14)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Could someone explain me how could I fix that?
The readme on GitHub is outdated, the project's website now states:
MongoDB ODM for Node.js based on ES6 generators.
No callbacks or promises.
It uses generators, which can find an example of on the getting started page:
'use strict';
function* saveUser () {
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
yield user1.save();
}
In order for generators to work, you must use 'use strict;' and the function* syntax. This GitHub project has additional examples.
Also, starting with Node v4, you no longer need the --harmony (now a synonym of --es_staging) flag for generators.
or you can do like this also ... but here you can execute just a single statement
user1.save().then(savedUser => console.log(`saved user: ${savedUser}`));

Resources