Using es6 on mocha tests - javascript

I'm trying to incorporate es6 in my server side code. Using babel-node works when running the server , however i'm having trouble compiling es6 to es5 code when running mocha tests.
This is my folder structure
I have a server.js which starts up a worker.js file(which has the express server)
the server.js file
import {SocketCluster} from 'socketcluster';
const socketCluster = new SocketCluster({
workers:1,
brokers:1,
port: 3000,
appName:null,
workerController: __dirname + '/worker.js',
brokerController: __dirname + '/broker.js',
socketChannelLimit: 1000,
crashWorkerOnError: true
})
the worker.js file
export const run = (worker) => {
console.log(' >> worker PID: ',process.pid);
const app = express();
const httpServer = worker.httpServer;
const scServer = worker.scServer;
app.use(cookieParser())
httpServer.on('request', app);
app.get('/',(req,res) => {
console.log('recieved')
res.send('Hello world')
})
}
When running the server manually , it works with the below script
"start": "nodemon server/server.js --exec babel-node"
however , when i try running the test file with mocha i get an 'unexpected token "export" error'
(function (exports, require, module, __filename, __dirname) { export const run = (broker) => {
^^^^^^
SyntaxError: Unexpected token export
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:511:25)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at initBrokerServer (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:178:25)
at process.<anonymous> (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:498:9)
this is the script to start the mocha tests
"test": "mocha test/server/*.js --compilers js:babel-register"
am i missing something else?
this is the test file
import server from '../../server/server';
import http from 'http';
import assert from 'assert';
import {expect} from 'chai';
describe('Express server',() =>{
it('should return "Hello World"',() => {
http.get('http://127.0.0.1:3000',(res) => {
expect(res).to.contain('wtf world')
})
})
})

You need to transpile test scripts from ES2015 to ES5 using Babel before passing it to mocha to run the tests. You can do it as follows adding/editing test script in package.json
...
"scripts": {
"test": "mocha --compilers js:babel-core/register --recursive"
},
...
Update:
Mocha deprecated the --compiler flag. Please check this page for more information. The new npm script should look like below
...
"scripts": {
"test": "mocha --require babel-register --recursive"
},
...

Turns out i need to specify an initController in my server.js file to ensure that all files are compiled by babel. This is a problem specific to the websocket framework i'm using.

Related

Must use import to load ES Module

I am trying to create a service to convert an SVG to a PNG using the svg2img package. I have it working locally using vercel dev, however when I try to deploy to vercel I always get this error:
2021-09-27T01:11:56.532Z e3a35069-8a51-4e1d-81b9-110e1b17e2be ERROR Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/api/node_modules/canvg/lib/index.js
require() of ES modules is not supported.
require() of /var/task/api/node_modules/canvg/lib/index.js from /var/task/api/node_modules/svg2img/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /var/task/api/node_modules/canvg/lib/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /var/task/api/node_modules/canvg/package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/var/task/api/node_modules/svg2img/index.js:1:13)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
code: 'ERR_REQUIRE_ESM'
}
RequestId: e3a35069-8a51-4e1d-81b9-110e1b17e2be Error: Runtime exited with error: exit status 1
Runtime.ExitError
Here is what my code looks like:
import svg2img from 'svg2img';
export default function(req, res) {
const url = req.query.url;
const width = req.query.width;
const height = req.query.height;
const size = Math.min(width, height);
svg2img(url, {width: size, height: size, preserveAspectRatio: true},
function(error, buffer) {
if (buffer) {
res.send(buffer);
}
});
};
Here is the package.json
{
"name": "svg2png",
"version": "1.0.0",
"description": "convert svgs to pngs",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "me",
"license": "ISC",
"dependencies": {
"svg2img": "^0.9.3"
},
"type": "module"
}
You can try lowering the version of svg2img to one that doesn't use 3.0.8 of canvg which uses "type": "module" in their package.json. svg2img uses require('canvg') which causes the error because it is trying to use commonjs in an esm context.
See this issue.

Unable to run docker image, Docker looking for different extension

I have the below Dockerfile:
# Use NodeJS base image
FROM node:12
# Create app directory
#RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm#5+)
COPY package*.json /usr/src/app/
COPY src/. /usr/src/app # this is to copy contents of src/ one level up otherwise they aren't recognised
RUN npm install
# Bundle app source
COPY . /usr/src/app/
#RUN rm -f /usr/src/app/src/*
EXPOSE 8080
# Define the Docker image's behavior at runtime
CMD ["node", "server.js"]
But on running the docker image after a successful build, below error appears:
internal/modules/cjs/loader.js:965
throw err;
^
Error: Cannot find module '/usr/src/app/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
Since I have a server.ts file and docker is somehow looking for server.js. On changing the extension, its unable to import other typescript files. Below is my server.ts:
import cors from 'cors';
import express from 'express';
import {sequelize} from './sequelize';
import {IndexRouter} from './controllers/v0/index.router';
import bodyParser from 'body-parser';
import {config} from './config/config';
import {V0_FEED_MODELS} from './controllers/v0/model.index';
(async () => {
await sequelize.addModels(V0_FEED_MODELS);
//await sequelize.addModels(V0_USER_MODELS);
await sequelize.sync();
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(cors({
allowedHeaders: [
'Origin', 'X-Requested-With',
'Content-Type', 'Accept',
'X-Access-Token', 'Authorization',
],
methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
origin: config.url,
}));
app.use('/api/v0/', IndexRouter);
// Root URI call
app.get( '/', async ( req, res ) => {
res.send( '/api/v0/' );
} );
// Start the Server
app.listen( port, () => {
console.log( `server running ${config.url}` );
console.log( `press CTRL+C to stop server` );
} );
})();
Why is docker picking up server.js automatically? where can I configure the docker to do otherwise?
FROM node:12
WORKDIR /usr/src/app
COPY . .
RUN npm install
EXPOSE 8080
CMD ["node", "server.js"]
I think this is what you are trying to do. It should work fine. If you're trying to do anything else please let me know.

Got 'Cannot find module' error when I tried to import certain JS file

I am currently learning JS and this is codes from practice.
(which is from YDKJSY)
This is a publication.js
function printDetails(title,author,pubDate) {
console.log(`
Title: ${ title }
By: ${ author }
${ pubDate } `
);
}
export function create(title,author,pubDate) {
var publicAPI = {
print() {
printDetails(title,author,pubDate);
}
};
return publicAPI;
}
And this blogpost.js import publication.js
import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
}
};
return publicAPI;
}
And finally main.js import blogpost.js
import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
"For and against let",
"Kyle Simpson",
"October 27, 2014",
"https://davidwalsh.name/for-and-against-let"
);
I converted these code by babel and got converted codes.
PS C:\users\leepc\babel> npm run build
> babel#1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w
public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js
but when I do npm run build and tried to run main.js I got this,
PS C:\users\leepc\babel\public\lib> node main.js
internal/modules/cjs/loader.js:984
throw err;
^
Error: Cannot find module 'blogpost.js'
Require stack:
at Module.require
(internal/modules/cjs/loader.js:1043:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
at Module._compile
(internal/modules/cjs/loader.js:1157:30) 3:17)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
at Module.load (internal/modules/cjs/loader.js:1001:32)
at Function.Module._load
(internal/modules/cjs/loader.js:900:14)
at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]
}
I checked whether I forgot any installment.
PS C:\users\leepc\babel> npm ls --depth=0
babel#1.0.0 C:\users\leepc\babel
+-- #babel/core#7.8.4
+-- babel-cli#6.26.0
+-- babel-preset-env#1.7.0
`-- babel-preset-es2015#6.24.1
Lastley, about .babelrc
{
"presets": ["env"]
}
and package.json build,
{
...
"build": "babel ./public/src -d ./public/lib -w"
}
I used node.js preset, but it got weird errors so I just left if with "env".
Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.
edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder
please try to have your modules relative to your file for importing. Usually, the imports with no paths are for node_modules.
import { create as newBlogPost } from "./blogpost.js";
// or wherever your blogpost.js is relative to your main.js
...
Okay it turns out, I should combine both of answers above.
First, I have to check whether my import plugin is right or wrong.
So I just re-installed it.
npm install babel-plugin-import --save-dev
Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc
{
"presets": ["es2015"],
"plugins": [["import", { "libraryName": "antd" }]]
}
this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.
And also next stuff, I have to make import path to be corrected.
import { create as newBlogPost } from "blogpost.js";
change this to
import { create as newBlogPost } from "./blogpost.js";
By doing this, now I can get a result that I wanted so far.
PS C:\Users\leePC\babel\public\lib> node main.js
Title: For and against let
By: Kyle Simpson
October 27, 2014
So majorly,
1. Check whether I missed some plugins or packages ( in my cases, I forgot import package )
2. Make sure to check your import path
Thank you for help guys.
Have you followed the setup steps from https://www.npmjs.com/package/babel-plugin-import ?
npm install babel-plugin-import --save-dev
In .babelrc
{
"plugins": [["import", options]]
}

Adding Vue.js To Rails 5.1 and Unit Tests in Mocha don't work

Repo is available here: https://github.com/systemnate/vuetesting
I created a rails app by running the command rails _5.1.2_ new vuetesting --webpack=vue
And then added mocha and chai yarn add mocha chai --save-dev
And then created a test directory by running mkdir test/javascript
Then I created a spec file to run... touch app/javascript/App.spec.js
And pasted in the following code:
const chai = require('chai')
const expect = chai.expect
describe('first test', () => {
it('is true', () => {
expect(true).to.equal(true)
})
})
And added the following to package.json
"scripts": {
"test": "mocha test/**/*.spec.js --recursive"
}
Now previous yarn test passes. Let's try to implement a Vue specific test.
I run the command yarn add avoriaz mocha-webpack --save-dev
And then modified package.json to use mocha-webpack:
"scripts": {
"test": "mocha-webpack test/**/*.spec.js --recursive"
}
yarn test still passes.
Now I want to test the single file component. To start with, I added to the top of my test so it looks like this:
import Vue from 'vue';
import App from '../../app/javascript/packs/App.vue';
const chai = require('chai')
const expect = chai.expect
describe('first test', () => {
it('is true', () => {
expect(true).to.equal(true)
})
})
And then run yarn test and get the following output
yarn test v0.27.5
$ mocha-webpack test/**/*.spec.js --recursive
ERROR in ./app/javascript/packs/App.vue
Module parse failed: /Users/natedalo/Ruby/vuetesting/app/javascript/packs/App.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <template>
| <div id="app">
| <p>{{ message }}</p>
# ./test/javascript/App.spec.js 2:0-53
error Command failed with exit code 1.
Any thoughts on what could be going wrong?
Using Unit Test Vue Components for Beginners as a guide, and copying the webpack.config.js and .setup files from the link above and then changing the test run to read like this inside the package.json:
"test": "mocha-webpack --webpack-config test/javascript/webpack.test.config.js test/**/*.spec.js --recursive --require test/javascript/.setup"

SyntaxError: Unexpected token function - Async Await Nodejs

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
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 Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await
node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

Categories