I'm trying to use Jest to write unit tests for some JavaScript code I have. The problem is that the code file contains functions that aren't defined or imported, so when I try to import the file to test, Jest throws an error about the undefined functions. Is there a way I can get around this? Only import the functions I want to test, for example?
Here's a snippet of the file with the code that I'm trying to test:
// run any data migrations
on("sheet:opened", () => {
sheetMigration();
getAttrs(["btatow_sheet_version"], ({
btatow_sheet_version
}) => {
if (btatow_sheet_version >= 3) {
recalculateSkills();
}
});
});
...
// calculate stat values when XP amount changes
on("change:strength_xp change:body_xp change:reflex_xp change:dexterity_xp change:intelligence_xp change:will_xp change:charisma_xp change:edge_xp", calculateAbilityScore)
const calculateLinkedAttributeValue = attribute => {
if (attribute > 10) {
return Math.floor(attribute / 3);
} else {
if (attribute < 1)
return -4;
else if (attribute < 2)
return -2;
else if (attribute < 4)
return -1;
else if (attribute < 7)
return 0;
else if (attribute < 10)
return 1;
else
return 2;
}
}
...
// exports for testing
module.exports = calculateLinkedAttributeValue
Here's the code in the test file:
const calculateLinkedAttributeValue = require('./sheet-worker')
test('should calculate linked attribute value for attribute value of 0', () => {
expect(calculateLinkedAttributeValue(0)).toBe(-4)
})
I have a package.json file set up, and have brought in Jest as a dependency, like so:
{
"name": "battletech-a-time-of-war",
"version": "1.0.0",
"description": "Character sheet for Roll20 for the A Time of War TTRPG system.",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"jest": "^26.0.1"
},
"type": "module",
"sourceType": "module"
}
Attempting to run the tests via the command line produces the following output:
C:\Stuff\Development\roll20-character-sheets\BattleTech-A-Time-of-War\development>npm run test
> battletech-a-time-of-war#1.0.0 test C:\Stuff\Development\roll20-character-sheets\BattleTech-A-Time-of-War
> jest
FAIL development/sheet-worker.test.js
● Test suite failed to run
ReferenceError: on is not defined
1 | // run any data migrations
> 2 | on("sheet:opened", () => {
| ^
3 | sheetMigration();
4 |
5 | getAttrs(["btatow_sheet_version"], ({
at Object.<anonymous> (development/sheet-worker.js:2:1)
at Object.<anonymous> (development/sheet-worker.test.js:1:39)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.226 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! battletech-a-time-of-war#1.0.0 test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the battletech-a-time-of-war#1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\<User>\AppData\Roaming\npm-cache\_logs\2020-06-01T09_59_15_484Z-debug.log
EDIT: Add examples and remove link to GitHub source code.
After digging around for a while on the internet and trying different things, I was able to determine the cause of the problem. It's actually nothing to do with Jest, it's the Node require() function. I found out from this StackOverflow comment that the Node require() function basically runs all the code in the file you're importing. Hence it tries to run the undefined functions, and errors.
Related
I have created an input and button in my project. the user is supposed to enter domain name and get its NS by clicking on button through a node JS function that returns nameserver.
getNs.js file in #/plugins/
export function getNs(domain) {
const dns = require('node:dns');
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
options.all = true;
dnsPromises.resolveNs(domain, options).then((result) => {
console.log('addresses: %j', result);
return result
});
}
declaring function in component script:
importing the plugin:
import {getIp} from "~/services/displayIp";
in methods:
goToSecondStep() {
getIp()
}
the event is happening on the button:
#click="goToSecondStep"
the error i get:
This dependency was not found: friendly-errors 09:54:39
friendly-errors 09:54:39
node:dns in ./services/displayIp.js friendly-errors 09:54:39
friendly-errors 09:54:39
To install it, you can run: npm install --save node:dns
i get the same error even though i run npm install --save node:dns command.
how can i use node js function or plugins in vuejs temeplates.
I am creating my first react-native app. I am attempting to install the react-native command line interface as shown here. I keep getting an error when I type the command to initiate the react-native command line
OS: Windows 10
Node: 10.15.3
npm: 6.4.1
I am not behind a proxy
I have removed the http and https environment variables
Updating node and npm creates a different error as shown here
Here's the error
C:\>npm install -g react-native-cli
npm ERR! Cannot read property 'startsWith' of null
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\dnort\AppData\Roaming\npm-cache\_logs\2019-04-15T09_52_28_346Z-debug.log
Here's npm get registry
C:\>npm get registry
https://registry.npmjs.org/
Here's npm config get proxy
C:\>npm config get proxy
null
Here's npm config get http-proxy
C:\>npm config get http-proxy
undefined
Here's npm config get https-proxy
C:\>npm config get https-proxy
null
Here's the log file
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'install',
1 verbose cli '-g',
1 verbose cli 'react-native-cli' ]
2 info using npm#6.4.1
3 info using node#v10.15.3
4 verbose npm-session 8e6a6f9ef2e9298d
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 silly fetchPackageMetaData error for react-native-cli#latest Cannot read property 'startsWith' of null
8 timing stage:rollbackFailedOptional Completed in 7ms
9 timing stage:runTopLevelLifecycles Completed in 1811ms
10 verbose stack TypeError: Cannot read property 'startsWith' of null
10 verbose stack at getProxy (C:\Program Files\nodejs\node_modules\npm\node_modules\make-fetch-happen\agent.js:164:25)
10 verbose stack at getAgent (C:\Program Files\nodejs\node_modules\npm\node_modules\make-fetch-happen\agent.js:37:19)
10 verbose stack at remoteFetch (C:\Program Files\nodejs\node_modules\npm\node_modules\make-fetch-happen\index.js:310:17)
10 verbose stack at opts.cacheManager.match.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\make-fetch-happen\index.js:172:14)
10 verbose stack at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
10 verbose stack at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
10 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
10 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
10 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
10 verbose stack at Promise._fulfill (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:638:18)
10 verbose stack at Promise._resolveCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:432:57)
10 verbose stack at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:524:17)
10 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
10 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
10 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
10 verbose stack at Promise._fulfill (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:638:18)
11 verbose cwd C:\
12 verbose Windows_NT 10.0.17134
13 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "react-native-cli"
14 verbose node v10.15.3
15 verbose npm v6.4.1
16 error Cannot read property 'startsWith' of null
17 verbose exit [ 1, true ]
I expect to install the react-native command line to be able to initiate react-native projects.
EDIT
Please see the npm config ls -l input below
C:\Windows\System32>npm config ls -l
; cli configs
long = true
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.4.1 node/v10.15.3 win32 x64"
; userconfig C:\Users\dnort\.npmrc
https-proxy = null
proxy = null
strict-ssl = false
; builtin config undefined
prefix = "C:\\Users\\dnort\\AppData\\Roaming\\npm"
; default values
access = null
allow-same-version = false
also = null
always-auth = false
audit = true
audit-level = "low"
auth-type = "legacy"
bin-links = true
browser = null
ca = null
cache = "C:\\Users\\dnort\\AppData\\Roaming\\npm-cache"
cache-lock-retries = 10
cache-lock-stale = 60000
cache-lock-wait = 10000
cache-max = null
cache-min = 10
cafile = undefined
cert = null
cidr = null
color = true
commit-hooks = true
depth = null
description = true
dev = false
dry-run = false
editor = "notepad.exe"
engine-strict = false
fetch-retries = 2
fetch-retry-factor = 10
fetch-retry-maxtimeout = 60000
fetch-retry-mintimeout = 10000
force = false
git = "git"
git-tag-version = true
global = false
global-style = false
globalconfig = "C:\\Users\\dnort\\AppData\\Roaming\\npm\\etc\\npmrc"
globalignorefile = "C:\\Users\\dnort\\AppData\\Roaming\\npm\\etc\\npmignore"
group = 0
ham-it-up = false
heading = "npm"
https-proxy = null
if-present = false
ignore-prepublish = false
ignore-scripts = false
init-author-email = ""
init-author-name = ""
init-author-url = ""
init-license = "ISC"
init-module = "C:\\Users\\dnort\\.npm-init.js"
init-version = "1.0.0"
json = false
key = null
legacy-bundling = false
link = false
local-address = undefined
loglevel = "notice"
logs-max = 10
; long = false (overridden)
maxsockets = 50
message = "%s"
; metrics-registry = null (overridden)
node-options = null
node-version = "10.15.3"
noproxy = null
offline = false
onload-script = null
only = null
optional = true
otp = null
package-lock = true
package-lock-only = false
parseable = false
prefer-offline = false
prefer-online = false
; prefix = "C:\\Program Files\\nodejs" (overridden)
preid = ""
production = false
progress = true
proxy = null
read-only = false
rebuild-bundle = true
registry = "https://registry.npmjs.org/"
rollback = true
save = true
save-bundle = false
save-dev = false
save-exact = false
save-optional = false
save-prefix = "^"
save-prod = false
scope = ""
script-shell = null
scripts-prepend-node-path = "warn-only"
searchexclude = null
searchlimit = 20
searchopts = ""
searchstaleness = 900
send-metrics = false
shell = "C:\\WINDOWS\\system32\\cmd.exe"
shrinkwrap = true
sign-git-commit = false
sign-git-tag = false
sso-poll-frequency = 500
sso-type = "oauth"
; strict-ssl = true (overridden)
tag = "latest"
tag-version-prefix = "v"
timing = false
tmp = "C:\\Users\\dnort\\AppData\\Local\\Temp"
umask = 0
unicode = false
unsafe-perm = true
update-notifier = true
usage = false
user = 0
; user-agent = "npm/{npm-version} node/{node-version} {platform} {arch}" (overridden)
userconfig = "C:\\Users\\dnort\\.npmrc"
version = false
versions = false
viewer = "browser"
There was no proxy set in my configs in npm. I tried npm config get proxy it was null.
Try this link
Solution found
Uninstall current version of node.js and npm from C:\Users{your_username}\AppData\Roaming
Install an older version of node.js. You can do that here. At the time of this post I installed the LTS (Node-10.15.3 & npm-6.4.1).
Remove http & https environment variables. (type in environment variables in search bar which should take your straight to system variables).
Temporarily disable windows defender features.
Restart system
Open administrator node.js command prompt
Enter npm install -g react-native-cli
My result output is now as expected:
C:\Windows\System32>npm install -g react-native-cli
C:\Users\dnort\AppData\Roaming\npm\react-native -> C:\Users\dnort\AppData\Roaming\npm\node_modules\react-native-cli\index.js
+ react-native-cli#2.0.1
added 41 packages from 15 contributors in 19.22s
This post is a continuation of my 'How to fix 'npm does not support Node.js v11.14.0 error' on Windows?' here
Note: Most solutions to similar problems have been related to proxy issues, unsupported versions of node.js/npm, environment variables
this may occur cause of coding error, in my case this line caused error
<img class="cat-icon" v-bind:src="require('img/icon/' + icon)" style="width:25px;" />
try to run "npm run watch" to see detailed error
I ran in to similar problem which was caused by wrong ralative path when registring components by require.context
I have tried a variety of commands to delete proxy settings.
I found that the best way to clear out proxy settings is to clear out related entry in .npmrc.
In my case, I simply empty the whole file and restart cmd. And it works.
This helped me:
npm config set proxy http://username:password#host:port
npm config set https-proxy http://username:password#host:port
I've a Testing framework with node, cypress, mocha, mochawesome and mochawesome-merge as below with this github repo:
and in my package.json I have two scripts as
`"scripts": {
"cy": "./node_modules/.bin/cypress open",
"cy_test": "node cypress.js"
},`
If I run npm run cy_test it works fine in headless state, but if I run npm run cy i get following error:
But If I remove cypress.js from my project then it works as expected.
cypress.js
const cypress = require('cypress')
const marge = require('mochawesome-report-generator')
const { merge } = require('mochawesome-merge')
const currRunTimestamp = getTimeStamp();
const mergedReport = {
reportDir: 'mochawesome-report',
}
const finalReport = {
reportDir: 'reports',
}
cypress.run({
reporter: 'mochawesome',
reporterOptions: {
reportDir: 'mochawesome-report',
overwrite: false,
html: true,
json: true
}
}).then(
() => {
generateReport()
},
error => {
generateReport()
console.error(error)
process.exit(1)
}
)
function generateReport(options) {
return merge(mergedReport).then(report => marge.create(report, finalReport))
}
I think this is a problem with npm on Windows that is messing with file names, because npm is trying to run the script as binary instead of getting it from ./node_modules/.bin.
So, I'll suggest, as first try, if you can, change the name of the cypress.js to something other than cypress. I think this can solve your problem.
If not, as a workaround remove .JS from PATHEXT environment variable and restart the processes that are running the script, including your IDE, if applicable.
Hope it works.
I've installed d3": "^3.5.17" and "d3-tip": "^0.7.1" using npm (d3-tip documentation). Then in my index.js file I have this code:
var d3 = require('d3');
var d3tip = require('d3-tip')(d3);
console.log('d3 version', d3.version);
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
But when I build the index file with browserify and load it in the browser, I see an error from the var tip line:
index.js:247 Uncaught TypeError: Cannot read property 'node' of undefined
This is coming from this function in the d3-tip source code:
function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() === 'svg')
return el
return el.ownerSVGElement
}
It looks like this function is expecting a node to be passed to it? But where would this come from?
The build itself does not throw any errors, and I think I'm requiring d3-tip correctly, as per this question. The console statement shows d3 version 3.5.17, as expected.
UPDATE: Here's my package.json file:
{
"name": "myapp",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "watchify index.js -o main.js --debug --verbose",
"build": "browserify index.js | uglifyjs > main.min.js"
},
"dependencies": {
"d3": "^3.5.17",
"d3-tip": "^0.7.1",
"datatables.net": "^1.10.12",
"datatables.net-bs": "^1.10.12"
},
"devDependencies": {
"uglifyjs": "^2.4.10",
"watchify": "^3.2.1"
}
}
And I installed the files with npm install.
This was happening because I was trying to use the latest version of d3-tip (which requires v4 of D3) with v3 of D3.
Reverting to older versions of both fixed things:
"d3": "^3.5.17",
"d3-tip": "^0.6.7"
Your line
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
must be
var tip = d3.tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
You can check my implementation #:
Source (Lines: 17, 91, 333-339, 685-692)
Demo
The problem is your line:
var d3tip = require('d3-tip')(d3);
You should not be calling d3.tip(foo) with the d3 reference itself, but with a d3 selection (which it can then invoke .node() on).
I think this should probably be:
d3.tip = require('d3-tip');
I'm trying to use a node process to kick off an interactive docker session then automate some commands to it:
var spawn = require('pty.js').spawn;
var proc = spawn('docker', [ 'run', '-i', '-t', 'mycontainer' ], {
name: 'test',
rows: 30,
cols: 200,
cwd: process.env.HOME,
env: process.env
});
proc.on('data', function (data) {
console.log(data);
});
proc.write('cd /tmp');
proc.write('nvm install 0.10\r');
proc.write('npm install');
This seems to work, the only issue is it seems like it's just writing in all the commands and firing them. I don't seem to have any control over catching the output or errors of individual commands.
I'm curious if there's a better way to approach this?
You can pipe streams to this process, however it is not advised to do so.
const { pipeline } = require('stream');
const { spawn } = require('node-pty')
const proc = spawn('docker', ['run', '--rm', '-ti', 'alpine', '/bin/sh'], {
name: 'xterm-color',
cwd: process.env.HOME,
env: process.env,
encoding: null,
});
pipeline(process.stdin, proc, (err) => err && console.warn(err.message))
pipeline(proc, process.stdout, (err) => err && console.warn(err.message))
The maintainer have suggested to not use pty in like a stream. It's simply a matter of changing the pipeline for something like this.
(async (stream) => {
for await (const chunk of stream) {
proc.write(chunk.toString())
}
})(process.stdin).catch(console.warn)
The gist is that we should pass string into the write function. We also should expect string as its output. Therefore, we should not set any encoding in the object so that it by default outputs utf8 string.
Regarding your initial question. proc.write('ls\r') is the correct way of doing it. Note the trailing \r to virtually press enter. Just like in a normal terminal, when you execute a command, you cannot fire a second one simultaneously. The commands will just queue up and run one after another.
Input:
const { spawn } = require('node-pty')
const proc = spawn('docker', ['run', '--rm', '-ti', '--network=host', 'node', '/bin/sh'], {
name: 'xterm-color',
cwd: process.env.HOME,
env: process.env,
});
proc.write('npm init -y\r')
proc.write('npm i eslint\r')
proc.write('ls node_modules /\r')
const disposable = proc.onData((text) => process.stdout.write(text))
const exitDisposable = proc.onExit(() => {
disposable.dispose()
exitDisposable.dispose()
})
Output:
npm i eslint
ls node_modules /
# Wrote to /package.json:
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"lib": "lib"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN #1.0.0 No description
npm WARN #1.0.0 No repository field.
+ eslint#7.1.0
added 136 packages from 82 contributors and audited 136 packages in 9.461s
9 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
# /:
bin etc lib64 node_modules package.json run sys var
boot home media opt proc sbin tmp
dev lib mnt package-lock.json root srv usr
node_modules:
#babel is-extglob
#types is-fullwidth-code-point
...
...
#
You see it wrote ls before npm install was completed but it ran afterwards.
Also note that I used -ti instead of just -t for the docker args.
Looking through the source for the pty.js module, it is clear that your proc.write is really the standard Node net.Socket.write -- https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback
In short, yes, you are just spamming the commands to the socket. You need to wait for each command to finish before executing the next. Thus, you'll need to use the callback parameter of .write to determine when a command has finished and then proceed from there. Something like this may work:
// this is a quick and dirty hack
let cmdcount = 0;
function submitcmd() {
switch (cmdcount) {
case 0:
proc.write('nvm install 0.10\r', 'utf8', submitcmd);
break;
case 1:
proc.write('npm install', 'utf8', submitcmd);
break;
}
cmdcount += 1;
}
proc.write('cd /tmp', 'utf8', submitcmd);