Gulp Node.js Istanbul Isparta - javascript

I'm trying to get unit tests coverage with Istanbul and Isparta, and I'm having some trouble.
Actually, here's my gulp file tasks:
gulp.task('pre-test', ['default'], function() {
return gulp.src('src/app/**/*.js')
.pipe(plumber())
.pipe(istanbul({
instrumenter: isparta.Instrumenter,
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function() {
return gulp.src('src/test/**/*.js')
.pipe(mocha({reporter: 'spec'}))
.pipe(istanbul.writeReports({}));
});
When I start the gulp "test" task, I have the following errors:
[08:34:17] Plumber found unhandled error:
Error in plugin 'gulp-istanbul'
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Line 1: Unexpected token
[08:34:17] Finished 'pre-test' after 2.11 s
[08:34:17] Starting 'test'...
stream.js:94
throw er; // Unhandled stream error in pipe.
^
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Object.Module._extensions.(anonymous function) [as .js] (C:\projects\nodejs\mon-notaire\node_modules\gulp-istanbul\node_modules\istanbul\lib\hook.js:109:37)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at C:\projects\nodejs\mon-notaire\node_modules\mocha\lib\mocha.js:192:27
at Array.forEach (native)
npm ERR! Test failed. See above for more details.
How can I prevent these errors from occurring?

Have you set up .babelrc?
If you're using the latest version of isparta, which depends on babel v6, then you need to set up .babelrc like the following. ( You also need to do npm install --save-dev babel-preset-es2015 )
{
"presets": [
"es2015"
]
}

From gulp-istanbul github page.
var isparta = require('isparta');
var istanbul = require('gulp-istanbul');
gulp.src('lib/**.js')
.pipe(istanbul({
// supports es6
instrumenter: isparta.Instrumenter
}));

This line :
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Means that there is a problem in your code in ConsoleLogger.js , so you might want to check that file out.
This Line :
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
Suggests that you are using ES6, but your gulp task is not transpiling it to ES5 before running it, which is why you are getting the error.
I have made a yeoman generator which creates a project for exactly this purpose (writing nodeJs projects in ES6) and includes code coverage using istanbul with source code mapping. You might want to take a look at that.
Otherwise, here is my working gulpfile from that generator.
I use istanbul, along with a module called remap-istanbul.

The error message indicates that you are using ES6, but the gulp-istanbul doesn't support it by default.
Of course, you can write your functions to compile the ES6 codes, but considering you are using gulp in this case, IMHO the simplest way you can do is to use gulp-babel-istanbul instead of gulp-istanbul, no need to change your code attached above at all.
import istanbul from 'gulp-babel-istanbul'
And the rest of the code remains the same.

Related

How to provide test ESModule implementation in mocha test?

I have a mocha test which tests my code. My code uses another "core" npm package (which uses CommonJS modules). One of "core" the files ("synchronizer.js" file) requires "prefs" modules which is assumed to be provided at some point:
const {Prefs} = require("prefs");
In the mocha test i'd like to implement this "prefs" module, so i've created "prefs.mjs" file (with exports that "synchronizer.js" expects). However during the test i have the following error:
Error: Cannot find module 'prefs'
Require stack:
- /Users/developer/Documents/dev/src/project/node_modules/core/lib/synchronizer.js
- /Users/developer/Documents/dev/src/project/node_modules/core/lib/index.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1026:15)
at Module._load (node:internal/modules/cjs/loader:872:27)
at Module.require (node:internal/modules/cjs/loader:1092:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/developer/Documents/dev/src/project/node_modules/core/lib/synchronizer.js:26:17)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
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 Module.require (node:internal/modules/cjs/loader:1092:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/developer/Documents/dev/src/project/node_modules/core/lib/index.js:33:24)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
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 ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
My project structure:
\sdk
\test
\unit
\ prefs
\prefs.mjs
\test.js
I run the tests (package.json):
"dependencies": {
...
"core": "^0.10.1",
...
},
"scripts": {
...
"unittest": "mocha --recursive ./test/unit/*.js",
...
}
}
test.js looks as follows:
describe("Section1", function() {
beforeEach(async function() {
await configureTestEnv();
// TODO: set "prefs" module
// TODO: set "io" module
// TODO: set "info" module
});
describe("subscriptions", function() {
it("throws if no condition is achieved", async function() {
...
I can run the tests (which does not include "core") successfully, so the testing works in general.
I suspect i have to use smth like webpack or babel, but i'd like to keep it clean and not using any deps or intermediate build steps if possible.
Should i pass modules directories paths to mocha to let node.js somehow find it?
Ended up using webpack and generating a module with aliased modules including prefs.

TypeError: Cannot read property 'compile' of undefined

I'm currently trying to follow this tutorial for Ethereum Solidity coding, and for the following code:
const path = require('path');
const fs = require('fs'); // File system module
const solc = require('solc').default; // Solidity Compiler module
// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link
// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile
// Generates a path that points directly to the inbox file. __dirname will be the root direction
// inboxPath = desktop/inbox/contracts/inbox.sol
const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
// The next step is to actually read the contents of the source file now
// utf8 is the encoding to read the file's content
const source = fs.readFileSync(inboxPath, 'utf8');
// Call solc.compile and pass in our source code, with only 1 contract
// console.log() means put the output in the console
console.log(solc.compile(source, 1));
I get the following error when I hover over const solc = require('solc').default:
Could not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)
When I try node compile.js, I get:
C:\Users\Hana PC\Desktop\inbox\compile.js:18
console.log(solc.compile(source, 1));
^
TypeError: Cannot read property 'compile' of undefined
at Object.<anonymous> (C:\Users\Hana PC\Desktop\inbox\compile.js:18:18)
[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:928:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m
I've never used/interacted with TypeScript or JavaScript or anything of the sorts, so I honestly don't even know what this error means. I've already tried uninstalling and reinstalling solc multiple times, all to no avail.
My node.js version is:
6.14.8
I tried doing some searching online for what the implicitly has an 'any' type. means or how it could be fixed, but I honestly didn't get any of it. If it helps, my package.json looks like this:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "compile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"solc": "^0.8.0"
}
}
Any help is appreciated!
**** Update:**
Tried it with uninstall solc and a fresh install (without using version 0.4.17), and got an Assertion Error:
assert.js:383
throw err;
^
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:97:7)
at compileStandard (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:214:14)
Wish I knew what was goin on
As per the discussion we had above, since the solidity file is using v0.4.17, you should use the same version of solc library in your code.
I have created a working example of your code here and the only two changes required were:
Making sure I use v0.4.17 of solc.
Import const solc = require("solc"); and not const solc = require("solc").default;
If you are having trouble downgrading the solc package, then
Delete package-lock.json file and node_modules/ folder.
Update the package.json files dependency to "solc": "0.4.17" and not to "^0.4.17"
Simply run npm install one last time.
This should be enough to get you up and running.

How do I add more than one Gatsby Plug-in using the gatsby-config.js file?

I am trying to add additional Gatsby Plug-ins to a Gatsby Project. I want to add 'gatsby-plugin-styled-components' to the gatsby-config.js file. Any help would be appreciated. Newbie to React and learning a lot fast.
added already and threw errors all over the place after running npm run build
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
module.exports = {
plugins: [`gatsby-plugin-emotion`],
}
gatsby-starter-hello-world#0.1.0 build /Users/jappleman/code/hello-world/tutorial-part-two
gatsby build
error We encountered an error while trying to load your site's gatsby-config.
Please fix the error and try again.
Error: /Users/jappleman/code/hello-world/tutorial-part-two/gatsby-config.js:8
plugins: ['`gatsby-plugin-emotion`],['`gatsby-plugin-styled-components'],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unterminated template literal
- v8-compile-cache.js:226 NativeCompileCache._moduleCompile
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:226:18
- v8-compile-cache.js:172 Module._compile
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:172:36
- loader.js:712 Object.Module._extensions..js
internal/modules/cjs/loader.js:712:10
- loader.js:600 Module.load
internal/modules/cjs/loader.js:600:32
- loader.js:539 tryModuleLoad
internal/modules/cjs/loader.js:539:12
- loader.js:531 Function.Module._load
internal/modules/cjs/loader.js:531:3
- loader.js:637 Module.require
internal/modules/cjs/loader.js:637:17
- v8-compile-cache.js:159 require
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:159:20
- get-config-file.js:33
[tutorial-part-two]/[gatsby]/dist/bootstrap/get-config-file.js:33:22
- Generator.next
- new Promise
gatsby-config.js exports an object
module.exports = {}
and within that object, the plugins you want to use on your project are specified as an array of plugin names (strings) that you have already installed as dependencies to your project (for example by typing npm install gatsby-plugin-react-helmet or yarn add gatsby-plugin-react-helmet into your terminal).
module.exports = {
plugins: [
`gatsby-plugin-react-helmet`
]
}
However, some of the plugins you will install might need some options to be set in order to work correctly. So these plugins should each be specified as an object within the same plugins array. And in this case, the value of each object's resolve property is the name of the plugin, usually followed by an object for their own options.
module.exports = {
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-remark`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src/data/`
}
}
]
}
For more information see Using a Plugin in Your Site
Also, given that your error is caused by a SyntaxError, please see MDN - Template_literals for information on backticks vs regular quotes, the differences between:
`gatsby-plugin-styled-components` & 'gatsby-plugin-styled-components'
& why the following line might be causing the Unterminated string literal SyntaxError:
plugins: ['`gatsby-plugin-emotion`],['`gatsby-plugin-styled-components']
After that, if the solution is not obvious, try changing your plugins to either of the following:
plugins: [`gatsby-plugin-emotion`],[`gatsby-plugin-styled-components`]
or
plugins: ['gatsby-plugin-emotion'],['gatsby-plugin-styled-components']

Import not working on Node.js version 11.8.0

I am writing a simple program that uses a object full of dictionary words. I want to import that object from a different file as it is very large. When trying to import it I get an error that looks like Node.js doesn't know what it is.
I have already tried reinstalling the latest version of Node.js.
Here is the important code:
import {dict} from './words_dictionary'
And here is all of it:
import {dict} from './words_dictionary'
function exists(obj,str) {
if(obj[str]) {
return true
} else {
return false
}
}
console.log(exists(dict, 'hello'))
Here is the gist of the dictionary code:
export let dict = {a: 1, aa: 1, aaa: 1, aah: 1, aahed: 1, aahing: 1, aahs:
1, aal: 1, aalii: 1, aaliis: 1, aals: 1, aam: 1, aani: 1, aardvark: 1,
aardvarks: 1,...~3000 more}
I expected true, but I got this error:
SyntaxError: Unexpected token {
at new Script (vm.js:84:7)
at createScript (vm.js:264:10)
at Object.runInThisContext (vm.js:312:10)
at Module._compile (internal/modules/cjs/loader.js:696:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
at Function.Module._load (internal/modules/cjs/loader.js:560:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
ECMAScript 6 is now working, but I am now getting the error of dict not being defined. Could this have something to do with the file size, because I have checked multiple times for spelling errors?
Have you been able to use the import keyboard elsewhere in your code? The issue here may be that you aren't transpiling your code into ECMAScript 5. Since import is an ECMAScript 6 feature, it hasn't yet been fully supported by Node.js. If you use a tool like Babel to transpile your code, you may fix this issue. If you don't want to do this, try using require instead.
As noted, in Node.js 9+ you can also use it in .mjs files with the --experimental-modules flag enabled.
node --experimental-modules file.mjs
Node.js import compatibility
It's only supported with an experimental flag. You should use the --experimental-modules flag.
Or just use require simple as that or if you really want, you can transpile your code with browserify, babel or parcel or whatever.
I think this should work if you run code like this:
node --experimental-modules index.mjs
Note that it uses the mjs extension (modular JavaScript I think).
You try this. Hope it helps
const 'your_variable' = require('your_required_module or file_path')
In your case
const dict = require( './words_dictionary')
Install necessary packages
npm install #babel/core #babel/register #babel/preset-env --save-dev
Add start.js file
// Transpile all code following this line with babel and use
'#babel/preset-env' (aka ES6) preset.
require("#babel/register")({
presets: ["#babel/preset-env"]
});
// Import the rest of our application.
module.exports = require('./server.js')

I want to run d3 from a Cakefile

I'd like to execute some d3 code from the command line. Initially I just tried something like:
task 'data', 'Build some data with d3', ->
d3 = require('lib/d3.v2')
console.log "d3 version = "+ d3.version
But this didn't work. I got errors like this:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: CSSStyleDeclaration is not defined
at /Users/mydir/Documents/classes/middleclass/app/lib/d3.min.js:1:21272
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/app/lib/d3.min.js:2:25395)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at Object.action (/Users/mydir/Documents/classes/middleclass/Cakefile:22:10)
at /usr/local/lib/node_modules/coffee-script/lib/coffee-script/cake.js:39:26
So...I figured this exception was telling me that I need to execute d3 inside of a browser. I tried this in a couple different ways. Basically though, I thought if I just fired up phantomjs I'd probably be able to do what I wanted to do. Here was my Cakefile:
task 'data2', 'Build some data with d3', ->
hem = spawn 'hem', ['server']
phantom = require('phantom')
phantom.create (ph) ->
ph.createPage (page) ->
page.open 'http://localhost:9294/sandbox.html', (status) ->
page.evaluate (-> window), (window) ->
require = window.require
require('lib/d3.v2')
console.log("d3 version = "+ d3.version)
ph.exit()
hem.kill()
When I go this route though, I always end up getting exceptions like this:
TypeError: object is not a function
at Object.CALL_NON_FUNCTION (native)
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/Cakefile:52:13)
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:274:16)
at apply (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:143:17)
at EventEmitter.handle (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:120:13)
at /Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:81:20
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:62:13)
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:46:19)
at EventEmitter.emit (events.js:67:17)
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:46:39)
What am I doin wrong??
Thanks to mbostock I got the following working:
My package.json:
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"d3": "~2.8.0",
"jsdom": "~0.2.13"
}
}
My Cakefile:
task 'd3', 'Do something with d3', ->
jsdom = require('jsdom')
jsdom.env({
html: 'public/sandbox.html'
done: (errors,window) ->
require('d3/index.js')
console.log("d3 version = "+ d3.version)
})
See D3's package.json. More specifically, the file you want to require when running inside Node or similar environments is index.js rather than d3.v2.js; this file contains some special patches that make D3 compatible with the require operator.
To try it out for yourself, cd to the d3 repository, run node to create an interactive shell, and then say
var d3 = require("./");
Or, if you're in your own project folder, if you've installed D3 into node_modules/d3 via npm (npm install d3), you can say:
var d3 = require("d3");

Categories

Resources