test case giving errors: "Cannot find name require" - node.js

I have installed mocha and chai to write test cases for node.js written in typescript
when ever i am running my test case (npm test) getting error as below
package.json:
{
"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha --compilers js:babel-register"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.5.2",
"babel-preset-es2015": "^6.14.0",
"babel-register": "^6.14.0",
"chai": "^3.5.0",
"mocha": "^3.0.2"
},
"babel":{
"presets": [
"es2015"
]
}
}
test file :
"use strict"
/// <reference path="./typings/globals/chai/index.d.ts" />
/// <reference path="./typings/globals/mocha/index.d.ts" />
require('babel-register')({
presets: ['es2015']
});
import chai = require('chai');
var expect = chai.expect;
// Import the Rectangle class.
let Rectangle = require('./src/db/util/MetricsResponseParser.js');
describe('DistanceDateMetricResponseParser', () => {
describe('parseResponse', () => {
let dateTimeMetrics;
beforeEach(() => {
dateTimeMetrics = new DistanceDateMetricResponseParser();
});
it('Parse Response method ', (done) => {
// This will fail if "rectangle.width" does
// not equal 10.
expect(dateTimeMetrics.parseResponse()).to.equals(Object);
done();
});
});
});
I have also installed babel as it transpiles the code to ES5
I dont understand the issue here
Any help would be appreciated

Related

facing problem while importing files in nodejs

I don't know what's going wrong with these extensions, when I provide the extension ".js" the app runs fine but it gives a warning on that line saying Unexpected use of file extension "js" for "./models/user.js", but when I remove the extension the whole app crashes and says Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\React\AuthenticationApp\backend\src\models\user' imported from F:\React\AuthenticationApp\backend\src\index.js, I know that files can be imported in node.js without providing the extension but I just know-how
here's my code
// eslint-disable-next-line no-unused-vars
import express from 'express'
import User from './models/user'
import './db/mongoose'
const app = express()
const port = 4000
app.use(express.json())
app.post('/users', (req, res) => {
const user = new User(req.body)
user
.save()
.then(() => {
res.send(user)
console.log(user)
})
.catch((e) => {
res.status(401).send(e)
})
})
app.listen(port, () => {
console.log(`Server is up on ${port}`)
})
and this is package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"type": "module",
"scripts": {
"build": "babel ./src --out-dir ./build",
"start": "nodemon --exec babel-node src/index.js",
"dev": "nodemon src/index.js",
"lint": "eslint ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.13.16",
"#babel/core": "^7.13.16",
"#babel/node": "^7.13.13",
"#babel/preset-env": "^7.13.15",
"#babel/runtime": "^7.13.17",
"eslint": "^7.25.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.4.0",
"nodemon": "^2.0.7",
"prettier": "^2.2.1"
},
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.12.6",
"validator": "^13.6.0"
}
}
Adjust your eslint config with this rule:
"rules": {
"import/extensions": [
"error",
{
"js": "ignorePackages"
}
]
},
Detailed description of the rule is in this page.
That way a nodejs will successfully run, eslint will not show error.
CommonJS modules are still able to be without extension in 'require' functions.
But you have to specify an extension of ESmodule when using 'import' (except 'Bare specifiers' like 'some-package'), this is according to nodejs docs.

Environment variables not working with Typescript and NodeJS

My process.env file has this:
DB_NAME = hello
When I run my index.ts file which has this:
import { MikroORM } from '#mikro-orm/core';
import { __prod__ } from './constants';
import { Post } from './entities/Post';
import microConfig from './mikro-orm.config';
console.log(`console log is : ${process.env.DB_NAME}`);
const main = async () => {
const orm = await MikroORM.init(microConfig);
const post = orm.em.create(Post, { title: 'my first post' });
orm.em.persistAndFlush(post);
};
main();
It gives the value of process.env.DB_NAME as undefined.
My package.json is set up as follows:
{
"name": "shreddit-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "nodemon dist/index.js",
"watch": "tsc -w",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/node": "^14.14.10",
"nodemon": "^2.0.6",
"ts-node": "^9.0.0",
"typescript": "^4.1.2"
},
"dependencies": {
"#mikro-orm/cli": "^4.3.2",
"#mikro-orm/core": "^4.3.2",
"#mikro-orm/migrations": "^4.3.2",
"#mikro-orm/postgresql": "^4.3.2",
"pg": "^8.5.1"
},
"mikro-orm": {
"useTsNode": true,
"configPaths": [
"./src/mikro-orm.config.ts",
"./dist/mikro-orm.config.js"
]
}
}
I even tried using dotenv but that too wasn't able to fix the problem. Am I missing something?
Thanks a lot.
Doesn't the process.env file automatically get loaded?
No, You're going to have to use dotenv.config as the following (at the very start of the script).
require('dotenv').config({ path: './process.env' })
// the rest of your code
Note that you can simply call .config without any arguments should your file be named just '.env' (which the de facto standard name for such purposes) - and not 'process.env'

Trying to use an async function with npm http-hash

I am trying to use http-hash module in order to construct an API for my application. I am using AVA as my test runner for my previous test. When I run the "npm test" command, I get this error in my console:
import { send } from 'micro'
^^^^^^
SyntaxError: Unexpected token import
I am using a linter and it doesn't send me any error. Here is my package.json, where you can see that I am using some babel plugins in order to transpile generators:
{
"name": "pos_lisa-api",
"version": "0.1.0",
"description": "LISA POS REST API",
"scripts": {
"lint": "standard",
"test": "npm run lint && ava"
},
"author": "Mauricio Cano Giraldo",
"license": "MIT",
"devDependencies": {
"ava": "^0.18.1",
"babel-eslint": "^7.1.1",
"babel-register": "^6.23.0",
"standard": "^8.6.0",
"test-listen": "^1.0.1"
},
"dependencies": {
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.22.0",
"babel-runtime": "^6.22.0",
"http-hash": "^2.0.0",
"micro": "^7.0.6",
"request": "^2.79.0",
"request-promise": "^4.1.1",
"uuid-base62": "^0.1.0"
},
"standard": {
"parser": "babel-eslint"
},
"babel": {
"presets": [
"es2015"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
}
And here is my node file, where i get the error:
'use strict'
import { send } from 'micro'
import httpHash from 'http-hash'
const hash = httpHash()
hash.set('GET /:id', async function getCliente (req, res, params) {
send(res, 200, params)
})
export default async function main (req, res) {
let method = req.method
let url = req.url
let match = hash.get(`${method.toUpperCase()} ${url}`)
if (match.handler) {
try {
await match.handler(req, res, match.params)
} catch (e) {
send(res, 500, { error: e.message })
}
} else {
send(res, 404, { error: 'La ruta no fue encontrada' })
}
}
I am reading around the web and I don't find anything. Please, help me! I would appreciate it so much!
AVA only transpiles the test files you want to run, but not the modules you're importing in them. But you can tell AVA to also transpile the imported modules by requiring babel-register (https://github.com/avajs/ava#transpiling-imported-modules). And because you configured babel already you can also tell it to use your config. Add this to your package.json
"ava": {
"babel": "inherit",
"require": ["babel-register"]
}
If you'd like to use the babel config AVA uses, you can leave off the "babel": "inherit", or you can define an entirely different one if you wish. But usually it's best to just inherit your config.
Using a .babelrc instead may work.

Trying to use async/await in mocha

I want to use async/await in mocha in order to make my tests. I have read many post, but I didn't find the solution. I have already install all the babel modules in order to transpiling the code, but it doesn't work.
Here is my code inside the "test" folder:
import test from 'mocha'
import 'babel-polyfill'
import { expect } from 'chai'
import { assert } from 'chai'
import utils from '../lib/utils'
describe('long number', function () {
it("Sample", mochaAsync(async () => {
var x = utils.longNums(0);
expect(x).to.equal(5000);
}))
})
Here is my package.json where I am using all the babel dependencies and plugins that I have read I have to install, and my test script where I suggest to mocha to use the babel transpiling
{
"name": "pos_lisa-test",
"version": "1.0.0",
"description": "pos lisa test",
"main": "index.js",
"scripts": {
"test": "mocha --compilers js:babel-core/register ./src/**/*.test.js"
},
"standard": {
"parser": "babel-eslint"
},
"babel": {
"presets": [
"es2015",
"react"
]
},
"keywords": [
"test"
],
"author": "Mauricio",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.23.1",
"babel-eslint": "^7.1.1",
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"chai": "^3.5.0",
"mocha": "^3.2.0",
},
"plugins": [
"transform-async-to-generator"
],
"dependencies": {
"babel-polyfill": "^6.23.0"
}
}
And the error that I get is the following
it('should remove items that don\'t evaluate to true when passed to predicate function', async function () {
^^^^^
SyntaxError: missing ) after argument list
What I am doing wrong? In advance thanks a lot for your help
You have added "plugins": ["transform-async-to-generator"]" to the top level of your package.json, but it should be inside the "babel" section. Change it to:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-async-to-generator"
]
},
According to the Tao of Javascript, "Code flows in the moment, so knowledge is but a hint, like the map of a stream."
As of April, 2017, having the 'transform-async-to-generator' will actually cause problems.
As a more general note, every async function returns a promise, or casts its return value and exception to a promise. It is usually cleaner to test the promise and not have your test call await:
it('should have no drops left', () =>
ocean.listDrops().should.eventually.have.length(0));

Error:Unexpected reserved word

I am trying to run simple test case but facing an error "unexpected reserved keyword" and its pointing to import keyword from the line import * as chai from 'chai'
below is my test code :
"use strict"
require('babel-register')({
presets: [ 'es2015' ]
});
// Import chai.
import * as chai from 'chai'
import * as MathUtils from './sample'
const should = chai.should;
let SampleTest = require(path.join(__dirname, '..', 'sample.js'));
describe('Sampletesting', () => {
describe('function sum', function(){
it('should return number', function(){
MathUtils.sum(1).should.equal(1);
})
})
});
Package.json:
{
"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha test/*.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.5.2",
"babel-preset-es2015": "^6.14.0",
"chai": "^3.5.0",
"mocha": "^3.0.2"
}
}
trying to test the below code :
function sum(a:number):number{
return a;
}
module.exports.sum=sum;
i dont understand why i am getting the error
Infact i have installed babel
Any help would be appreciated.
You need to actually transform your source code file with babel. babel-register only affects future calls to require(), it does not automagically transform the current file (since the JavaScript parser needs to parse the document before babel has a chance to do anything).

Resources