Trying to use async/await in mocha - node.js

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));

Related

How to use babel-preset-env with Jest

We are in the midst of updating our API, and Henry Zhu from Babel alerted me to this preset called babel-preset-env to replace need for babel-preset-es2015 and babel-preset-es2018.
Now, I am encountering difficulty understanding the simplest way to handle everything.
Our API uses node v8.x and async/await, native promises
I want spread operator
I want pipeline operator
I want import/export syntax
I want to support Jest
I like how babel-node transpiles the API into memory
This will be easier if I just show you the current position of our config:
.babelrc
{
"presets": [
"env",
{
"targets": {
"node": "current"
}
},
"jest"
]
}
package.json
{
"scripts": {
"test": "node --harmony-async-await node_modules/jest/bin/jest.js",
"start:local": "NODE_ENV=localhost npm run babel-node -- warpcore/server.js",
"start": "npm run babel-node -- warpcore/server.js",
"babel-node": "babel-node --presets=es2015,stage-2"
},
"dependencies": {
"babel-polyfill": "^6.23.0"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2018": "^1.0.0",
"babel-preset-stage-2": "^6.24.1",
"jest": "^20.0.4"
},
"jest": {
"testURL": "http://localhost:8080",
"testEnvironment": "node"
}
}
I am uncertain how these things need to be organized to best achieve my bullet list above.
What changes should I make?
I think the babel-node script needs to change
I suspect I can remove some of these packages
I suspect the .babelrc file isn't optimal
If you want to use babel-preset-env as a replacement for babel-preset-es2015 (which is deprecated) with Jest, then you have to make sure that the "modules" property in your "env" configuration is set to "commonjs".
Here is an exemplary configuration:
.babelrc
{
"env": {
"test": {
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"presets": [
"jest",
"react",
[
"env",
{
"debug": false,
"modules": "commonjs",
"targets": {
"node": "current"
},
"useBuiltIns": true
}
]
]
}
}
}
You can see in env.test, that the preset env (which is the "babel-preset-env" configuration) has "modules" set to "commonjs". That's important, otherwise you will get "SyntaxError: Unexpected token import".
For completeness, here is a simple test:
ExampleButton.test.jsx
import ExampleButton from './ExampleButton';
import React from 'react';
import renderer from 'react-test-renderer';
test('Example Test', () => {
const component = renderer.create(<ExampleButton />);
const json = component.toJSON();
expect(json.type).toBe('button');
});
ExampleButton.jsx
import React from 'react';
class ExampleButton extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.text}
</button>
)
}
}
export default ExampleButton;
For my Babel setup, I have used the following dependencies:
"babel-core": "6.26.0",
"babel-jest": "21.2.0",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-preset-env": "1.6.1",
"babel-preset-react": "6.24.1",
"jest": "21.2.1",
"react-test-renderer": "16.1.1",
I think I got it working. Here is the solution:
.babelrc
The one posted in the question has a syntax error because the env preset needs to be wrapped in brackets[] (from: http://babeljs.io/docs/plugins/preset-env/)
Correct:
{
"presets": [
["env",
{
"targets": {
"node": "current"
}
}],
"jest"
]
}
package.json
The one posted in the question has a few things that can be removed:
{
"scripts": {
"test": "jest --verbose",
"start:local": "cross-env NODE_ENV=localhost babel-node -- app.js",
"babel-node": "babel-node --presets=env"
},
"dependencies": {
"babel-cli": "^6.24.1",
"babel-preset-env": "^1.6.0"
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"jest": "^20.0.4"
},
"jest": {
"testURL": "http://localhost:8080",
"testEnvironment": "node"
}
}
Much cleaner in my opinion. You can modulate the presets from the .babelrc file if you want to explicitly include or exclude any, or specify which browsers to support.
This is the solution I found:
{
"presets": ["#babel/env", "#babel/react"]
}

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.

test case giving errors: "Cannot find name require"

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

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).

ES2015 modules does not work in Node.js with Babel.js?

I want to use ES2015 modules in Node.js with babel.js compiler, but it won't work. Here is what I have:
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel-core": "^6.9.0",
"babel-plugin-transform-runtime": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-node5": "^11.1.0",
}
}
.babelrc
{
"presets": ["es2015"],
"plugins": [
"transform-runtime"
]
}
server/index.js
require('babel-core').transform('code', {
presets: ['node5'],
});
import { test } from './file1';
console.log(test);
server/file1.js
export const test = 'its working!';
But console throws error SyntaxError: Unexpected token import
Does ES2015 modules not working in node5, or I am doing something wrong here? Appreciate your help.
Please install babel-register npm module and require this in index.js
server/index.js
require('babel-register');
import { test } from './file1';
console.log(test);
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel": "^6.5.2",
"babel-preset-es2015": "^6.6.0",
"babel-register": "^6.8.0"
}
}
.babelrc
{presets:[es2015]}
for me it works
Thanks

Resources