Node.js Mocha Error: ReferenceError: test is not defined - node.js

I've got an error after running test scripts.
app.test.js
const { app } = require('../src/app');
describe('Basic functionality', () => {
test('App should receive a command to run', () => {
expect(app('1'))
.toEqual('Run command 1');
});
test('Should return instructions when no command is given', () => {
expect(app())
.toEqual('Usage: node index.js <COMMAND>');
});
test('Should throw an error when no such command exists', () => {
expect(() => {
app('100')
})
.toThrow('No such command exists');
});
});
package.json (I've installed mocha in my project. I've tried to install mocha globally, but the result was same)
"scripts": {
"test": "mocha __tests__/app.test.js"
},
"devDependencies": {
"mocha": "^8.0.1"
}
I've got an error after running
yarn run test
Below is the error code
ReferenceError: test is not defined
at Suite.describe (/test/__tests__/app.test.js:4:2)
at Object.create (/test/node_modules/mocha/lib/interfaces/common.js:143:19)
at context.describe.context.context (/test/node_modules/mocha/lib/interfaces/bdd.js:42:27)
at Object.<anonymous> (/test/__tests__/app.test.js:3:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.exports.requireOrImport (/test/node_modules/mocha/lib/esm-utils.js:20:12)
at Object.exports.loadFilesAsync (/test/node_modules/mocha/lib/esm-utils.js:33:34)
at Mocha.loadFilesAsync (/test/node_modules/mocha/lib/mocha.js:421:19)
at singleRun (/test/node_modules/mocha/lib/cli/run-helpers.js:156:15)
at exports.runMocha (/test/node_modules/mocha/lib/cli/run-helpers.js:225:10)
at Object.exports.handler (/test/node_modules/mocha/lib/cli/run.js:366:11)
at innerArgv.then.argv (/test/node_modules/yargs/lib/command.js:241:49)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Please teach me where I went wrong.

I solved it by specifying the route:
Like this:
npx mocha "src/testing-examples/index.test.js" --recursive --require #babel/register
I hope you find it useful :)

Related

Test a Node.js Application with Mocha including ES6-Modules in Dependencies

I want to test my simple Node.js (v14.15.4) application with Mocha (v8.2.1).
I also include Babel to compile the ES6 modules in my code.
In particular, I use "#babel/core" (v7.12.10), "babel/register" (v7.12.10) to use the compiler with mocha, and "#babel/preset-env" (v7.12.11) for ES6 module support.
Everything works fine, until I include an external dependency in my code. In my case, I want to use bpmn-js (v8.2.0) which itself is ready for the use with ES6 modules (https://bpmn.io/blog/posts/2018-migrating-to-es-modules.html).
My project structure is as follows:
- bpmn
- index.js
- node_modules
- ...
- babel.config.json
- index.js
- index.test.js
- package.json
The files are depicted below:
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha --require #babel/register index.test.js"
},
"devDependencies": {
"mocha": "8.2.1",
"#babel/core": "7.12.10",
"#babel/register": "7.12.10",
"#babel/preset-env": "7.12.11"
},
"dependencies": {
"bpmn-js": "8.2.0"
},
"author": "",
"license": "ISC"
}
babel.config.json
{
"presets": ["#babel/preset-env"]
}
index.js
export {
default
} from './bpmn';
bpmn/index.js
//import { Viewer } from 'bpmn-js';
export default (str) => {
return str.toUpperCase();
};
index.test.js
import toUpperCase from './index';
const assert = require('assert');
describe('The module toUpperCase', () => {
it('should transform my test string', () => {
assert.strictEqual(toUpperCase('test'), 'TEST');
});
});
As stated, everything works fine when running npm run test.
However, if I include the comment in line 1 in the bpmn/index.js file,
the error below occurs. It seems that babel compiles my local project files, but ignores the external dependencies, i.e. bpmn-js in that case
\node_modules\bpmn-js\index.js:1
export {
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Module._compile (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.newLoader [as .js] (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\Code\Neuer Ordner\bpmn\/index.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Module._compile (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.newLoader [as .js] (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\Code\Neuer Ordner\/index.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Module._compile (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.newLoader [as .js] (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\Code\Neuer Ordner\/index.test.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Module._compile (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.newLoader [as .js] (D:\Code\Neuer Ordner\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.exports.requireOrImport (D:\Code\Neuer Ordner\node_modules\mocha\lib\esm-utils.js:20:12)
at Object.exports.loadFilesAsync (D:\Code\Neuer Ordner\node_modules\mocha\lib\esm-utils.js:33:34)
at Mocha.loadFilesAsync (D:\Code\Neuer Ordner\node_modules\mocha\lib\mocha.js:431:19)
at singleRun (D:\Code\Neuer Ordner\node_modules\mocha\lib\cli\run-helpers.js:125:15)
at exports.runMocha (D:\Code\Neuer Ordner\node_modules\mocha\lib\cli\run-helpers.js:190:10)
at Object.exports.handler (D:\Code\Neuer Ordner\node_modules\mocha\lib\cli\run.js:362:11)
at D:\Code\Neuer Ordner\node_modules\yargs\lib\command.js:241:49
There are two problems in your approach. The first one, really fundamental, is that you are trying to import bpmn-js inside a Node.js process. This package can only be run in a browser as it depends on the DOM Document being available. You are never going to be able to do this. The other problem is, as you correctly figured out, that bpmn-js uses ES6 module syntax. By default, packages found in the node_modules directory are ignored by #babel/register that you require. In other words, they are not transpiled. You could configure #babel/register to make an exemption for bpmn-js and transpile it but your import would still fail with something like:
ReferenceError: document is not defined

How to use canvas for node.js on heroku

The error I get is the following:
Error: Cannot find module 'canvas'
Require stack:
- /app/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
at Function.Module._load (internal/modules/cjs/loader.js:840:27)at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (/app/index.js:6:16)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/app/index.js' ]
When I tried local it worked fine, I started having problems after I uploaded the code on Heroku. I've searched online but seems like all answers on google for this question are outdated. These are my current dependencies:
"dependencies": {
"canvas": "^2.6.1",
"discord.js": "^12.2.0",
"node": "^14.2.0"
}
And this is my code:
const Discord = require('discord.js');
const { prefix } = require ('./config.json');
const client = new Discord.Client();
const Canvas = require('canvas');
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
// Do something.
}
Anyone that could help with it?
First, with Heroku, you don't need to upload your node_modules on GitHub or something else. You can also try in the terminal :
npm start
Then :
npm install discord.js canvas node
If it isn't enough, check in your package.json file if there is :
"scripts": {
"start": "node index.js"
}

mocha test problem in Ubuntu:ReferenceError: ert is not defined

I am using mocha to test my node js code. While running on windows machine, I am able to test my application successfully. But when I am trying to test same application project in Ubuntu , I am getting ReferenceError: ert is not defined . So i did "rm -rf node_modes" and "npm i" again . But the issue still persist.
Error in terminal
$ npm test
> myapplication#1.0.0 test /NodeProject/MyApplication
> mocha Test/* --require #babel/register
/NodeProject/MyApplication/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: ert is not defined
at Object.<anonymous> (/NodeProject/MyApplication/Test/app.test.js:1:4)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Module._compile (/NodeProject/MyApplication/node_modules/pirates/lib/in dex.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Object.newLoader [as .js] (/NodeProject/MyApplication/node_modules/pira tes/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at /NodeProject/MyApplication/node_modules/mocha/lib/mocha.js:330:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/NodeProject/MyApplication/node_modules/mocha/lib/moch a.js:327:14)
at Mocha.run (/NodeProject/MyApplication/node_modules/mocha/lib/mocha.js:8 04:10)
at Object.exports.singleRun (/NodeProject/MyApplication/node_modules/mocha /lib/cli/run-helpers.js:207:16)
at exports.runMocha (/NodeProject/MyApplication/node_modules/mocha/lib/cli /run-helpers.js:300:13)
at Object.exports.handler.argv [as handler] (/NodeProject/MyApplication/no de_modules/mocha/lib/cli/run.js:296:3)
at Object.runCommand (/NodeProject/MyApplication/node_modules/yargs/lib/co mmand.js:242:26)
at Object.parseArgs [as _parseArgs] (/NodeProject/MyApplication/node_modul es/yargs/yargs.js:1087:28)
at Object.parse (/NodeProject/MyApplication/node_modules/yargs/yargs.js:56 6:25)
at Object.exports.main (/NodeProject/MyApplication/node_modules/mocha/lib/ cli/cli.js:63:6)
at Object.<anonymous> (/NodeProject/MyApplication/node_modules/mocha/bin/_ mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! Test failed. See above for more details.
And here is my app.test.js file
var assert = require('assert')
, expect = require('expect.js'),
W3CWebSocket = require('websocket').w3cwebsocket;
describe('Test Suite', function() {
var client;
beforeEach(function(done) {
client = new W3CWebSocket('ws://localhost:8091/', 'echo-protocol');
client.onopen = function() {
console.log('WebSocket Client Connected');
done();
};
client.onclose = function() {
console.log('echo-protocol Client Closed');
};
});
afterEach(function(done) {
if(client!=null){
client.close();
}
done();
});
it('My App result', (done) => {
if (client.readyState === client.OPEN) {
client.send(`"data":"dummy"}`);
}
client.onmessage = function(e) {
let data = e.data;
expect(data).to.not.equal(null);
expect(data).to.not.equal(undefined);
done();
};
});
});
I faced similar issue. It was because babel version in package.json is different from the one whose specific settings are set in .babelrc file
Try deleting .babelrc file and see if it works.
The ert probably is from
.../node_modules/babel-core/lib/transformation/file/options/option-manager.js:128
log.error or log.ert
If not search whole directory for ert, that should give you some clue

gulp + mocha + typescript unit test

I have an error when I create new instance on test file.
This is my test:
/// <reference path="../typings/globals/mocha/index.d.ts" />
import Person from '../src/person/person';
describe('Person', () => {
let person: Person;
beforeEach(() => {
person = new Person();
});
describe('getName', () => {
it('return name', () => {
});
});
});
And my gulp task:
var gulp = require("gulp");
var ts = require("gulp-typescript");
var mocha = require("gulp-mocha");
var tsProject = ts.createProject("./tsconfig.json");
gulp.task('watch', function () {
gulp.watch('./src/**/**/*.ts', ['ts']);
});
gulp.task('ts', function () {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest("dist"));
});
gulp.task('test', function () {
return gulp.src('./tests/*.spec.ts',
{
base: '.'
})
/*transpile*/
.pipe(tsProject())
/*flush to disk*/
.pipe(gulp.dest('.'))
/*execute tests*/
.pipe(mocha())
.on("error", function(err) {
console.log(err)
});
});
gulp.task("default", ['watch', 'ts']);
So, when I launch the test an error occured, but if I comment person = new Person() then everything works.
Somebody knows what I am doing wrong?
EDIT:
Sorry, this is the error:
module.js:472
throw err;
^
Error: Cannot find module '../src/person/person'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/emesislol/projects/persons/tests/person.test.js:4:21)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /Users/emesislol/projects/persons/node_modules/mocha/lib/mocha.js:222:27
at Array.forEach (native)
at Mocha.loadFiles (/Users/emesislol/projects/persons/node_modules/mocha/lib/mocha.js:219:14)
at Mocha.run (/Users/emesislol/projects/persons/node_modules/mocha/lib/mocha.js:487:10)
at Object.<anonymous> (/Users/emesislol/projects/persons/node_modules/mocha/bin/_mocha:459:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3

mocha.opts not working with babel-register

This is my mocha.opts file:
--require babel-polyfill
--require jsdom-global/register
--compilers js:babel-register
--watch
--recursive
--bail
--check-leaks
--reporter spec
This is my .babelrc file, I am using the env preset which transpiles based on the targets provided:
{
"presets":[
"react",
[
"env",
{
"targets":{
"chrome":54,
"node":true
}
}
]
],
"plugins":[
"transform-class-properties",
["transform-object-rest-spread", {
"useBuiltIns":true
}
]
]
}
I find that when I run mocha, node objects violently to the use of import which works correctly in my code:
/* eslint-env node, mocha*/
import chai, { expect } from 'chai';
import { shallow, mount } from 'enzyme';
import chaiEnzyme from 'chai-enzyme';
chai.use(chaiEnzyme());
describe('EllipsisText', function(){
it('exists', function() {
expect(EllipsisText).to.exist;
});
});
This is the error that mocha throws:
/home/vamsi/Do/css-in-js-test/test/EllipsisText.js:2
import chai, { expect } from 'chai';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at /home/vamsi/.nvm/v6.2.0/lib/node_modules/mocha/lib/mocha.js:220:27
at Array.forEach (native)
at Mocha.loadFiles (/home/vamsi/.nvm/v6.2.0/lib/node_modules/mocha/lib/mocha.js:217:14)
at Mocha.run (/home/vamsi/.nvm/v6.2.0/lib/node_modules/mocha/lib/mocha.js:469:10)
at Object.<anonymous> (/home/vamsi/.nvm/v6.2.0/lib/node_modules/mocha/bin/_mocha:404:18)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3
When using babel, mocha needs to be run like this:
mocha --compilers js:babel-core/register
Related: Running Mocha + Istanbul + Babel
More detail: http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/

Resources