I am using https://github.com/sequelize/sequelize to learn using the database migrations. This works fine.
As a next step, I would like to be able to run tests. My test is very simple (not using anything related to Sequelize) and looks like
import request from 'supertest';
import app from '../src/app.js';
describe('GET /', () => {
it('should render properly', async () => {
await request(app).get('/').expect(200);
});
});
describe('GET /404', () => {
it('should return 404 for non-existent URLs', async () => {
await request(app).get('/404').expect(404);
await request(app).get('/notfound').expect(404);
});
});
When I run this as npm test, I get error as
➜ contactz git:(master) ✗ npm test
> express-babel#1.0.0 test /Users/harit/bl/sources/webs/q2/contactz
> jest
FAIL test/routes.test.js
● Test suite failed to run
TypeError: Cannot read property 'use_env_variable' of undefined
at Object.<anonymous> (db/models/index.js:11:11)
at Object.<anonymous> (src/routes.js:3:14)
at Object.<anonymous> (src/app.js:4:15)
at Object.<anonymous> (test/routes.test.js:2:12)
at Generator.next (<anonymous>)
at Promise (<anonymous>)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.702s
Ran all test suites.
npm ERR! Test failed. See above for more details.
➜ contactz git:(master) ✗
I am new to NodeJS, Express so not sure what is going wrong here.
The code is available at https://github.com/hhimanshu/contactz
Could someone please help me know what's wrong and how to fix it?
I got this error today and fixed it.
When running jest, by default it will set the NODE_ENV (process.env.NODE_ENV) to "test".
If you generated basic sequelize files using sequelize-cli, in your sequelize config.json file there should be (by default) three types of config options used which are: "development", "test", and "production".
However I see that you are using your own config.js file and there is no "test" option there, only development and production https://github.com/hhimanshu/contactz/blob/master/db/config.js
You are receiving this error as the model/index.js file is looking for said "test" option but finds it undefined instead. Specifically, at line 12 of https://github.com/hhimanshu/contactz/blob/master/db/models/index.js it will find the config as undefined, and throw error looking for undefined's use_env_variable property.
The solution is to add "test" config to your config.js file. Just copy the config you used for development and it should run.
*note that you should probably set a different db for each of the different types of config, but this is another topic.
Export your config.js file for example check this below
module.exports ={
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
I simply used javascript trim()
before
process.env.NODE_ENV() // return "development " with space
After
process.env.NODE_ENV.**trim()** // "development" no space
Here is my solution
I'm a newbie in server stuff, specifically heroku + node express + sequelize. So in my case, my config var on Heroku settings was wrong.
NODE_ENV was set to a wrong value like live instead of production.
The correct value production must be equal to your config.js, assuming you're using Sequelize too.
instead of npm test, can you try this command ?
jest yourfile.js --env=node --runInBand
Related
Hi guys can you help me with my problem, somebody experienced db-migrate up for posgre
here that nothing happens after using use command db-migrate up
$ db-migrate up add-terminal-business-addr
terminal screenshot
Database config:
{
"dev": {
"driver": "pg",
"user": "postgres",
"password": "",
"host": "localhost",
"port": "5432",
"database": "postgres"
}
}
database config screenshot
'use strict'
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from the dbmigrate initially.
* This enable us to not have to rely on NODE_PATH.
*/
export.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = options.dataType;
seed = seedLink;
};
export.up = function(db) {
return db.removeColumn('terminals', 'business_address');
};
export.down = function(db) {
return db.addColumn('terminals', 'business_address', {type: 'jsonb', notNull: false});
};
export._meta = {
"version": 1;
};
Migration file screenshot
Well the problem might be :
problem with just the version of db-migrate-pg
OR
In production or having important data in development you should take time to investigate the issue. In this case you most likely had created an empty migration, ran rake db:migrate, then added instructions to the migration, so you don't see a new field and further rake db:migrate does nothing. To resolve this issue you need to comment your change instructions, perform rake db:rollback, uncomment instructions and then rake db:migrate to apply instructions you missed.
Try to rebuild your database structure(WARNING: all db-data will be lost):
rake db:drop:all
rake db:create:all
rake db:migrate
If you use Rails < 4.1, don't forget to prepare test database:
rake db:test:prepare
This is the easiest solution since you are working with tutorial.
First question so bare with me if it is not very clear, but I'll try my best.
I am currently running through a youtube video to test my contract with hardhat, ethers, and waffle (https://www.youtube.com/watch?v=oTpmNEYV8iQ&list=PLw-9a9yL-pt3sEhicr6gmuOQdcmWXhCx4&index=6).
Here is the contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract MyContract is ERC721 {
constructor(string memory name, string memory symbol)
ERC721(name, symbol) {
}
}
And here is test.js:
const { expect } = require('chai');
describe("MyContract", function() {
it("should return correct name", async function() {
const MyContract = hre.ethers.getContractFactory("MyContract");
const myContractDeployed = await MyContract.deploy("MyContractName", "MCN");
await myContractDeployed.deployed();
expect(await myContractDeployed.name()).to.equal("MyContractName");
});
});
when I run "npx hardhat test" in the terminal it returns:
MyContract
1) should return correct name
0 passing (7ms)
1 failing
1) MyContract
should return correct name:
TypeError: Cannot read properties of undefined (reading 'getContractFactory')
at Context.<anonymous> (test\test.js:7:35)
at processImmediate (node:internal/timers:464:21)
My code matches the one from the video, and I am having a tough time understanding why I am getting a TypeError here. Any guidance is much appreciated!
EDIT:
I somehow fixed it, I dont understand how exactly it fixed it but it did. Instead of just installing
npm install #nomiclabs/hardhat-waffle ethereum-waffle chai #nomiclabs/hardhat-ethers ethers
I installed
npm install --save-dev #nomiclabs/hardhat-waffle ethereum-waffle chai #nomiclabs/hardhat-ethers ethers
Then the terminal printed
npm WARN idealTree Removing dependencies.#nomiclabs/hardhat-waffle in favor of devDependencies.#nomiclabs/hardhat-waffle
npm WARN idealTree Removing dependencies.ethereum-waffle in favor of devDependencies.ethereum-waffle
npm WARN idealTree Removing dependencies.#nomiclabs/hardhat-ethers in favor of devDependencies.#nomiclabs/hardhat-ethers
npm WARN idealTree Removing dependencies.ethers in favor of devDependencies.ethers
then I removed the hre in front of ethers.getContractFactory("MyContract") and it worked! If anyone would like to explain why this might have fixed it I'd be happy to read it, otherwise I am moving on.
Add the following code snippet at the top of your hardhat.config.js file
require("#nomiclabs/hardhat-waffle");
Sometimes it is because any of these dependencies below missing. Especially if you are using dotenv file and forgetting to import it. So, put these import statements on your hardhat.config or truffle.config file:
require("#nomicfoundation/hardhat-toolbox");
require("#nomiclabs/hardhat-ethers");
require("dotenv").config();
You needed to import hre in the test code.
const hre = require("hardhat");
Running commands via Node's execFile on windows is a nightmare. Many a time, when I get a "Command failed" error if I copy the "failed" command from the error it executes just fine. Sometimes, trying windowsVerbatimArguments: true helps but usually, it does not.
For example, right now I am running Visual Studio's MSBuild.exe, with the following parameters in Node.js - I have printed the exact array passed to execFile:
Running MSBuild with parameters: [
'D:\\PROJECT\\vcxproj\\HelperProject.vcxproj',
'-t:OutputBuildMacro',
'-p:ProjectToImport=D:\\PROJECT\\vcxproj\\HelperProject.vcxproj;PropertyToGet="OutputType,BlueProjectsVersionPropsGlobalIncluded"'
]
Executable path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\MSBuild.exe
If I copy these items from the array and paste them into the command line it will run just fine. Clearly, Node.js is messing up when passing the command. Because this has happened to me many times, just a few weeks ago with Irfan View, I am not looking for a solution for this specific problem - I would just be asking a similar question again very soon.
I am looking for a guide how to see what is Node.js actually passing so that I can make a guess how to edit the parameters so that they are accepted by the command I call.
How to see what is Node.js exactly sunning why I call execFile?
You can use NODE_DEBUG environment variable to get extra info out of NodeJS.
You can find docs here.
For example this index.js:
const { execFile } = require('child_process');
execFile('/bin/ls', ['/Volumes'], {}, (err, stdout, stderr) => {
if (err) {
console.error('Command failed');
} else {
console.log('Command succeded');
}
});
And to enable debug logging for child_process module execute:
NODE_DEBUG=CHILD_PROCESS node index.js
(On Windows the environment variable seems to be set differently)
set NODE_DEBUG=CHILD_PROCESS & node index.js
in my case it produces this kind of output:
CHILD_PROCESS 85208: spawn {
cwd: null,
env: null,
gid: undefined,
uid: undefined,
shell: false,
windowsHide: false,
windowsVerbatimArguments: false,
args: [ '/bin/ls', '/Volumes' ],
detached: false,
envPairs: [
'COMMAND_MODE=unix2003',
...
'TERM=xterm-256color',
'NODE_DEBUG=CHILD_PROCESS',
],
file: '/bin/ls'
}
P.S.
Setting NODE_DEBUG=* will produce all debug log information that is available in NodeJS.
So I have install npm config module.
I have trying to set a local variable that stores a secret/privateKey.
Tried setting an environment variable/private key using the following command
export VIDLY_JWTPRIVATEKEY=MYSECUREKEY
however it don't think It is being set as I get an error via
console.log("FATAL ERROR: JWTPRIVATEKEY is not defined");
This is how I am checking if the key is set..
index.js
if (!config.get("JWTPRIVATEKEY")) {
console.log("FATAL ERROR: JWTPRIVATEKEY is not defined");
// node environment variable. 1 (any other number exc. 0) is exit the app, 0 is success
process.exit(1);
}
userAuth.js I once again try to get the private, however its not set (?)
#code above
const token = jwt.sign({ _id: user._id }, config.get("JWTPRIVATEKEY"));
default.json (in config module folder)
{
"JWTPRIVATEKEY": ""
}
custom-environment-variables.json (in config folder)
{
"JWTPRIVATEKEY": "VIDLY_JWTPRIVATEKEY"
}
**
ERROR: "FATAL ERROR: JWTPRIVATEKEY is not defined"
**
What am I doing wrong?
Instead of setting the variable with this way, you can try to set it in production and development config folders like this:
config/development.js
const config = {
env: 'development',
JWTPRIVATEKEY: <your_dev_key>
};
module.exports = config;
config/production.js
const config = {
env: 'production',
JWTPRIVATEKEY: <your_prod_key>
};
module.exports = config;
it is two years later! but i think it can be useful, atleast for others.
if you set environment variable AND run the app in IDE's Terminal, it will not work!
but if do these in "cmd", it works.
I have the following demo: https://github.com/pc-magas/pupAndroidDemo
And I try to build it for android. I have installed the androis SDK and set the correct enviromental parameters.
Then as Readme.md says I run the following commands:
meteor build ~/builds/ --server=192.168.30.137:3821
cd ~/builds
tar -xvf pup.tag.gz
cd bundle/program/server
npm install
cd ../
cp ^project_folder^/settings-development.json ~/builds/settings.json
env MONGO_URL="mongodb://localhost:27017/tesedb" ROOT_URL="192.168.30.137:3821" PORT=3821 METEOR_SETTINGS="$(cat ../settings.json)" node main.js
But the last one:
env MONGO_URL="mongodb://localhost:27017/tesedb" ROOT_URL="192.168.30.137:3821" PORT=3821 METEOR_SETTINGS="$(cat ../settings.json)" node main.js
Throws me the following error:
/home/pcmagas/builds/bundle/programs/server/boot.js:391 }).run(); ^
TypeError: Cannot read property 'slice' of null
at packages/meteor.js:1234:19
at packages/meteor.js:1246:4
at packages/meteor.js:1393:3
at /home/pcmagas/builds/bundle/programs/server/boot.js:338:34
at Array.forEach (native)
at Function..each..forEach (/home/pcmagas/builds/bundle/programs/server/node_modules/underscore/underscore.js:79:11)
at /home/pcmagas/builds/bundle/programs/server/boot.js:158:5
at /home/pcmagas/builds/bundle/programs/server/boot.js:387:5
at Function.run (/home/pcmagas/builds/bundle/programs/server/profile.js:510:12)
at /home/pcmagas/builds/bundle/programs/server/boot.js:386:11
I have also seen the: TypeError: Cannot read property 'slice' of null
But it does not help me at all.
Edit 1:
My settings.json contains:
{
"public": {},
"private": {
"MAIL_URL": "",
"OAuth": {
"facebook": {
"appId": "^FACEBOOK app id^",
"secret": "^facebook_secret^",
"loginStyle": "popup"
},
"google": {
"clientId": "^client_id^",
"secret": "^client_sectet^",
"loginStyle": "popup"
}
}
}
}
* Values between ^ is replacement for the actual values.
First, check that you did copy correct settings.json file.
Second, remove env at the start of the line. If you're using sh-compatible shell then you don't need it.
The problem is when you set the ROOT_URL enviromental variable value. You must ensure that starts with http://
As seen in: https://github.com/meteor/meteor/issues/8124