I am trying to define some endpoints and do a test using nodejs. In server.js I have:
var express = require('express');
var func1 = require('./func1.js');
var port = 8080;
var server = express();
server.configure(function(){
server.use(express.bodyParser());
});
server.post('/testend/', func1.testend);
and in func1.js:
var testend = function(req, res) {
serialPort.write("1", function(err, results) {
serialPort.write("2" + "\n", function(err, results) {
});
});
});
exports.testend = testend;
Now in test.js I am trying to use this endpoint:
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var http = require('http');
var app = require('./../server.js');
var port = 8080;
describe('Account', function() {
var url = "http://localhost:" + port.toString();
it('test starts', function(done) {
request(url).post('/testend/')
// end handles the response
.end(function(err, res) {
if (err) {
throw err;
}
res.body.error.should.type('string');
done();
});
});
});
But when I run node test.js I am getting this error:
describe('Account', function() {
^
ReferenceError: describe is not defined
at Object. (/test/test.js:9:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
How can I fix the issue?
Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.
So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.
if you are using vscode, want to debug your files
I used tdd before, it throw ReferenceError: describe is not defined
But, when I use bdd, it works!
waste half day to solve it....
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",// set to bdd, not tdd
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/**/*.js"
],
"internalConsoleOptions": "openOnSessionStart"
},
To run tests with node/npm without installing Mocha globally, you can do this:
• Install Mocha locally to your project (npm install mocha --save-dev)
• Optionally install an assertion library (npm install chai --save-dev)
• In your package.json, add a section for scripts and target the mocha binary
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha"
}
• Put your spec files in a directory named /test in your root directory
• In your spec files, import the assertion library
var expect = require('chai').expect;
• You don't need to import mocha, run mocha.setup, or call mocha.run()
• Then run the script from your project root:
npm test
You can also do like this:
var mocha = require('mocha')
var describe = mocha.describe
var it = mocha.it
var assert = require('chai').assert
describe('#indexOf()', function() {
it('should return -1 when not present', function() {
assert.equal([1,2,3].indexOf(4), -1)
})
})
Reference: http://mochajs.org/#require
i have this error when using "--ui tdd".
remove this or using "--ui bdd" fix problem.
OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd like in the docs, but that didn't work, bdd worked though.
for Jest you have to add "jest": true to .eslintrc
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
...
Make sure you have a folder named as test that contains your test.js file.
Also make sure you have mocha available in your project by running mocha -version in terminal (at project path)
Make sure your project has package.json available, if not run npm init -y
And finally to run mocha test scripts, on terminal (on project path) run npm test
Related
I created a plain #nrwl/express project with an empty web server server.ts:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.json({status: 'OK'})
});
var server = app.listen(3000);
module.exports = { server }
Whenever I add one a test file such as something.test.ts:
const { server } = require('../server');
describe('TEST: /', () => {
it('Should work just fine', async () => {
// all ok
});
});
export {};
Then ng serve express starts complaining because it tries to process the test files:
TS2593: Cannot find name 'describe'. Do you need to install type definitions for a test runner?
Try `npm i #types/jest` or `npm i #types/mocha` and then add `jest` or `mocha` to the types
field in your tsconfig.
What is the correct way to solve this? I don't necessarily want to add test libraries as a runtime dependency because test files shouldn't be bundled in the build IMO.
I figured it out after a couple of days (face-palm)
I needed to edit tsconfig.app.json and needed to add "**/*.test.ts" in the exclude option:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": ["node"]
},
"exclude": ["**/*.spec.ts", "**/*.test.ts"],
"include": ["**/*.ts"]
}
Everything is working fine now, warning messages are gone.
I am experience a Module Not Found error for an NPM package that is installed and appears to be present in the node_modules folder. Is something missing in the underlying package itself?
Here is my package.json:
{
"name": "cmtest",
"version": "0.0.0",
"description": "cmtest",
"main": "server.js",
"author": {
"name": "Andrew"
},
"dependencies": {
"cloudmersive": "^1.3.2"
}
}
And then I am calling a require:
'use strict';
var http = require('http');
var Cloudmersive = require('cloudmersive');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
var api = new Cloudmersive.BarcodeLookupApi()
var value = "value_example"; // {String} Barcode value
var callback = function (error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
api.barcodeLookupEanLookup(value, callback);
}).listen(port);
But I am getting this error:
"Cannot find module 'cloudmersive'"
"Error: Cannot find module 'cloudmersive'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
at Function.Module._load (internal/modules/cjs/loader.js:497:25)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (c:\users\andrew\documents\visual studio 2017\Projects\cmtest\cmtest\server.js:3:20)
at Module._compile (internal/modules/cjs/loader.js:675:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)"
Any ideas? Is there something wrong with the package itself? Is it a development/configuration issue on my part?
The package cloudmersive is installed with NPM and shows up in the node_modules folder. I also tried using nvm to switch between several different versions.
Underlying package source is here: https://github.com/Cloudmersive/Cloudmersive.APIClient.Javascript
Is there something wrong with the index.js file?
package.json for cloudmersive says main is src/client.invoker/index.js but the file is not in that directory.
To use the library locally without publishing to a remote npm registry, first install the dependencies by changing
into the directory containing package.json. Let’s call this JAVASCRIPT_CLIENT_DIR. Then run:
npm install
Next, link it globally in npm with the following, also from JAVASCRIPT_CLIENT_DIR:
npm link
Finally, switch to the directory you want to use your cloudmersive from, and run:
npm link /path/to/<JAVASCRIPT_CLIENT_DIR>
You should now be able to require('cloudmersive') in javascript files from the directory you ran the last
command above from.
You can checkout the README.md file inside the cloudmersive module which you have installed inside your node_modules directory to get more detailed instructions on this.
I know I'm missing something here. I'm running node through babel and using koa2 on my server. Fairly new to this so not quite sure what I'm missing, as I've been referencing a lot of things online.
Versions: Node 6.4, babel-core 6.14.0, babel-polyfill": 6.13.0
Getting a fun error. Looks like a generator is not being produced somehow.
assert.js:89
throw new assert.AssertionError({
^
AssertionError: app.use() requires a generator function
at Application.app.use (/Users/administrator/Dropbox/Development/moonlite/moonlitewww/node_modules/koa/lib/application.js:106:5)
Here's what I'm running off of:
Package.json
"start:dev": "node -r babel-core/register index.js",
.Babelrc
{
"presets": ["es2015", "react", "stage-3"]
}
Index.js
require("babel-polyfill");
import nodeServer from "./web-server.js";
var config = {
prod: process.env.NODE_ENV === "production",
serverPort: process.env.PORT || 3000
};
nodeServer(config);
web-server.js
import Koa from 'koa';
import koaRouter from 'koa-router';
import send from 'koa-send';
import serve from 'koa-serve';
import logger from 'koa-logger';
const router = koaRouter();
const app = new Koa();
export default (config) => {
app.use(logger());
app.use(serve(__dirname + '/client/build'));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(config.serverPort, () => {
console.log('Server running on port:' + config.serverPort);
});
};
What am I missing here?
Noob mistake on my part. I was merging the packages from another package.json file in, and somehow koa got reverted back to the 1.x branch. Was chasing a red haring thinking it was babel.
If you see a similar error double check your koa version, and upgrade to koa2 like so:
npm install koa#next --save
"NOW YOU KNOW, AND KNOWING IS HALF THE BATTLE..."
I have an existing node app. My Node directory structure is setup like this:
./
node_modules/
src/
views/
index.html
...
server.js
test/
gulpfile.js
package.json
I can successfully start my app my running node ./src/server.js from the root shown above. Once started, I can visit "http://localhost:3000" in the browser and see the contents of index.html like I am expecting.
I want to speed up my development and I recently learned about browsersync. In an attempt to include it in my gulp process, I have the following:
var browserSync = require('browser-sync').create();
browserSync.init({
server: {
baseDir: './src/',
server: './src/server.js'
}
});
When I run gulp, I see the following in the command-line:
BS] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://[ip address]:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://[ip address]:3001
--------------------------------------
My browser is then opened and it attempts to load http://localhost:3000. At this point, I see the following error in the browser window:
Cannot GET /
What am I doing wrong? I can successfully visit http://localhost:3000 if I start my app using node ./src/server.js, however, its like its not running with BrowserSync. What am I doing wrong?
You already have a node server so i think what you need is Proxy.
And i would also suggest you to use nodemon for going one step ahead in your speed up development thing. It will automatically restart your node development server in case of any changes. So a sample gulpfile in your case(with nodemon) might look like
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:3700", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./src/views/*.html"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({script: './src/server.js'}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
~
Why do you want to use the built-in server if you have your own in ./src/server.js ?
Check this, What server in browsersync does is create a static server for basic HTML/JS/CSS websites, so you might need to use the proxy feature as shown here.
This means that you need to run your server as normally and wrap it up in the proxy.
Using the express generator default folder structure with the start script in bin\www, and using the ejs template, this is how i modified my gulpfile.js :
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:8000", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./views/*.ejs"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({
script: './bin/www',
env: {
PORT: 8000
}}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
Notice that am watching for any files that end in .ejs. I also got a problem when using nodemon with the port in use, so i added an env to pass the port as 8000,
env: { PORT: 8000 }
Since the tag grunt is missing from the question, here's a solution that works using only NPM (package.json):
"scripts": {
"start": "browser-sync start --serveStatic 'src' --serveStatic 'node_modules' --files 'src'"
}
Now all the <script> src attributes can be relative:
<script src="/stats-js/build/stats.min.js"></script>
I am trying to setup my Nodejs/Express hosting server to have multiple applications (Sails.js app type) running on my VPS but I got this error :
/srv/data/web/vhosts/default/node_modules/vhost/index.js:78
throw new TypeError('argument server is unsupported')
^
TypeError: argument server is unsupported
at createHandle (/srv/data/web/vhosts/default/node_modules/vhost/index.js:78:9)
at vhost (/srv/data/web/vhosts/default/node_modules/vhost/index.js:39:16)
at Object.<anonymous> (/srv/data/web/vhosts/default/server.js:46:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Of course I previously installed all my dependencies.
My Nodejs/Express base configuration for multiple apps is good because it works fine with this express vhosts example configuration:
https://github.com/loicsaintroch/express-vhosts
So here my nodejs server app structure:
.../vhosts/default/server.js
package.json
/app1
/app.js
/app2
/app.js
/app3
/app.js
And here my server.js file based on this previous github example:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
// vhosts
app
.use(vhost('app1.com', require('./app1/app.js')))
.listen(8080);
And the package.json file:
{
"name": "default",
"private": true,
"version": "0.0.1",
"description": "Default git repository for some web applications.",
"dependencies": {
"express": "^4.2.0",
"vhost": "^2.0.0",
"forever": "^0.11.1",
"static-favicon": "^1.0.0",
"ejs": "^1.0.0",
"morgan": "^1.0.0",
"cookie-parser": "^1.0.1",
"body-parser": "^1.0.0",
"debug": "^0.7.4"
},
"scripts": {
"start": "forever start server.js --prod",
"debug": "node debug server.js"
},
"main": "server.js"
}
Error come from vhost npm package:
/**
* Create handle to server.
*
* #param {function|Server} server
* #return {function}
* #api private
*/
function createHandle(server){
if (typeof server === 'function') {
// callable servers are the handle
return server
} else if (typeof server.emit === 'function') {
// emit request event on server
return function handle(req, res) {
server.emit('request', req, res)
}
}
throw new TypeError('argument server is unsupported')
}
OK here precisely I think vhost package has a problem with the app.js response from sails.js framework. Here the app.js file content from my Sails.js app:
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
==============================================
UPDATE: FULL SOLUTION EXAMPLE
As a synthesis of the great answer I wrote a complete case study available here
https://github.com/migswd/express-sails-vhosts
==============================================
The problem here is that you're trying to shoehorn an example meant for Express apps to work with Sails apps.
If you look at the app.js files from the example vhost apps, they all use module.exports to return an Express app instance. The app.js from the Sails app you posted clearly does no such thing; it doesn't export anything at all. Furthermore, that file is calling sails.lift, which starts its own server listening on port 1337.
A little elbow grease can get this to work. Instead of lifting the Sails app, you can use sails.load which does everything except start listening on a port. This is an asynchronous method, so it'll require a reworking of your server.js as well.
The Sails app.js files become:
var sails = require('sails');
module.exports = function(cb) {
process.chdir(__dirname);
sails.load(cb);
};
Every running sails instance exposes its underlying Express app as .hooks.http.app, so in your server.js, use async or something similar to load all of the Sails apps, then hook them up with vhost:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
var async = require('async');
async.auto({
app1: require('./app1/app.js'),
app2: require('./app2/app.js'),
app3: require('./app3/app.js')
}, function doneLoadingApps(err, apps) {
app
.use(vhost('app1.io', apps.app1.hooks.http.app))
.use(vhost('app2.io', apps.app2.hooks.http.app))
.use(vhost('app3.io', apps.app3.hooks.http.app))
// Mix in a vanilla Express app as well
.use(vhost('app4.io', require('./app4/app.js')))
.listen(8080);
});