Replacing karma with jasmine-node for my AngularJS tests? - node.js

Jasmine AngularJS test (passes in karma start configs/karma.conf.js)
describe('IndexController', function () {
beforeEach(module('myApp'));
var ctrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('IndexController', {
$scope: scope
});
}));
it('should add name parameter to scope', function () {
expect(scope.name).toBeDefined();
});
});
Contents of controllers.js
var myApp = angular.module('myApp', []);
myApp.controller('IndexController', function ($scope) {
$scope.name = 'bob';
});
Output of: jasmine-node test/ --junitreport
Message:
TypeError: object is not a function
Stacktrace:
TypeError: object is not a function
at null.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:38:16)
at Object.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:36: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 Module.require (module.js:364:17)
at require (module.js:380:17)

beforeEach() taks in a function. Be sure module('myApp') and inject(...) are returning actual function definitions. Jasmine's beforeEach is like "call the passed function before each test", so you may want:
beforeEach( function(){ module('myApp') } );
I am unfamiliar with karma, but do use jasmine's done() method in my beforeEach() like this:
var valueForEachTest = null;
beforeEach( function(done) {
doSomething( function(value){
valueForEachTest = value;
done();
});
} );
Not using that done() call breaks my tests because I'm doing a few asynchronous call in there (perhaps Jasmine is not waiting for beforeEach to finish?).

Angular is made to run in the browser. It will not run in node. At least, not without a lot of effort.
There has been an attempt to port it to node, but that project is really intended to render angular pages server side for search engine optimization. Unless you have a really good reason, you shouldn't be trying to test Angular apps in Node.

Related

Issue with module wrapper function

I'm trying to learn node.js, and having an issue with running a code with module wrapper function. Here is the code
logger.js (1)
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
logger.js(2)
( function (exports, require, module, __filename, __dirname)
{
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
})
app.js
const logger = require('./logger.js')
console.log(logger);
logger.log('Hiya');
The logger.js(1) works fine, logger.js(2) gives out following error.
TypeError: logger.log is not a function
at Object.<anonymous> ()
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
I was expecting to get the same result from both cases
In the snippet which you have attached as logger.js(2),
function (exports, require, module, __filename, __dirname) is irrelevant and does not make sense to the NodeJS Compiler.
The correct way of doing what you expect is the one listed in logger.js(1)
If you are exporting multiple functions then,
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
function log_twice(message) {
console.log(message);
console.log(message);
}
module.exports = { log: log, log_twice: log_twice }; //and so on
Request to accept the answer if it helps...

Nodejs, Electron nightmare is not defined when it's installed?

I've installed Nightmare via NPM this is my code:
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
$( "#test" ).addEventListener('click',() => {
nightmare
.goto('http://akhiljose.me/master/paste/')
.type('.form-control', 'Test')
.type('input[type=test]', 'nightmare_test')
.click('input[type=submit]')
.wait(7000)
.evaluate(function () {
return document.querySelector('pre').innerText;
})
.end()
.then(function (result) {
console.log(result);
})
.cat(function (error) {
console.error('Search failed:', error);
})});
However console logs:
C:\Users\ninja_000\Desktop\clu-gen\index.js:3 Uncaught ReferenceError: Nightmare is not defined
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:22:3)
at Module._compile (module.js:642:30)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at file:///C:/Users/ninja_000/Desktop/clu-gen/index.html:12:5
I'm very new to nodejs what is causing this error? Am I do something wrong?
You are calling an undefined variable.
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
The second line declares a variable nightmare but the next line you are calling Nightmare. Make the second line uppercase.
var jquery = require('jquery')
var Nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
You can see from the second line of the stack trace:
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
Line 3:17, there is an uncaught ReferenceError: Nightmare. This make sense because Nightmare is not defined, so nodejs cannot find it. The line numbers in the stack trace are useful to pinpoint where in the code the error is occurring. You can also use a linter which will show an error for trying to use an undefined variable. Something like eslint.
Should've defined as Nightmare not nightmare

How to read data from console in Node.js?

Actually I have tried one code. This code is working fine but I want to access this information outside of callback function. But i am unable to find solution.
var prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
data = result.username;
});
console.log(data);
Here if i'm trying to retrieve print data variable it show's error.
Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js
prompt: username: /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
^
ReferenceError: data is not defined
at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
You could use promise, check docs about promise and newer es 6 Async/ await. With promise you could use something like this:
var prompt = require('prompt');
function getPromt () { return new Promise( (resolve, recect) => {
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
resolve( result.username);
});
});
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});
"You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task."
Refer to this one: how can find return variable value outside anonymous function in node js mysql query function
You can also check this link to learn how to handle with async flow: http://book.mixu.net/node/ch7.html

NodeJS script with async/await causing syntax error (v7.10.0)

I am trying to use async/await in NodeJS but my script is throwing a syntax error.
I was under the impression that async/await is supported naively since Node 7.6. When I run node -v I get v7.10.0.
Here is the contents of index.js:
async function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}
let value = await getValueAsync();
console.log(value);
But when I invoke this script with node index.js I get:
let value = await getValueAsync();
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
I am running Linux Mint 18.1.
How can I get my script to compile and run?
await is only valid inside async functions, so you need, for example, an async IIFE to wrap your code with:
void async function() {
let value = await getValueAsync();
console.log(value);
}();
And, since return values from async functions are wrapped by a promise, you can shorten getValueAsync to simply this:
async function getValueAsync() {
return 'foo';
}
Or don't mark it as async and return a promise from it:
function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}

AssertionError: path must be a string

require([
'common',
// Libs
'jquery',
'parse',
'i18n',
// Modules
'modules/login/controllers/login',
'modules/page/controllers/page',
// Styles
'css!../assets/css/bootstrap.min.css',
'css!../assets/css/tablesorter-bootstrap-theme.css',
'css!../assets/css/common.css',
],
function(common, $, Parse, i18n, Login, Page) {
// Defining the application router, you can attach sub routers here.
var Router = Parse.Router.extend({
routes : {
'' : 'index'
},
index : function() {
var currentUser = Parse.User.current(),
view, container;
// Load either login screen or navigation bar,
// depending on the login state of current user.
if(currentUser){
view = new Page.Views.Navbar();
container = '#navbar';
} else {
view = new Login.Views.Login();
container = '#main';
$('#navbar').html(null); // Remove the navbar
}
view.render(function(el) {
$(container).html(el);
});
}
});
$(function() {
// Initialize internationalization
i18n.init({
saveMissing: true,
debug: true,
//preload: ['dk', 'en'],
getAsync: false
});
Parse.initialize('****','****');
// Initialize the Router
var router = new Router();
Parse.history.start({ pushState: false });
});
$(document).on( 'click', 'a:not([data-bypass])', function(evt) {
// Get the anchor href and protcol
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href && href.slice(0, protocol.length) !== protocol && href.indexOf('javascript:') !== 0) {
evt.preventDefault();
Parse.history.navigate(href, { trigger: true });
}
});
});
Got error:
assert.js:85
throw new assert.AssertionError({
^
AssertionError: path must be a string
at Module.require (module.js:482:3)
at require (internal/module.js:20:19)
at Object. (/home/historiejagt.portaplay.dk/public_html/app/app.js:4:1)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
Read the error:
AssertionError: path must be a string
at Module.require (module.js:482:3)
at require (internal/module.js:20:19)
at Object. (/home/historiejagt.portaplay.dk/public_html/app/app.js:4:1)
Look at your code:
require([
An array is not a string.
I think I worked out what's going on, though it would have been a lot easier if someone had been more specific about where they're copy-pasting code from.
The function require(array, callback) is part of RequireJS. NodeJS doesn't use that and has require(string) instead. If you want to use RequireJS in NodeJS you need to install and require requirejs first.

Resources