Is there a Java classpath-like feature for server-side Javascript? - javascript

When using JUnit and Maven in Java, one can have separate property files for src/main and src/test. This allows different configuration for code and tests, having Maven to manage the resources by using Java classpath.
Is there a similar way in Javascript code run by Node.js? I use Mocha for unit-testing and Grunt for task management.
Code example for script.js:
var config = require('./config/dev/app.js');
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
What I need is to make the script.js use different config file when being required in a test.js unit test like this:
var assert = require('assert');
var s = require('./script.js');
describe('Test', function () {
it('should use different config file', function() {
assert.equal('test.txt', s.getFileName());
});
});
Is there a way to use different configuration ./config/test/app.js in the script.js without having to alter the code of script.js? What I really try to avoid is to adjust the code to support unit tests. Instead, I want to achieve similar functionality such as mentioned Java classpath.

Please try this code.
Script.js
var config;
if(process.env.dev===true){
config = require('./config/dev/config.js');
}
if(process.env.prod===true){
config = require('./config/prod/config.js');
}
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
test.js
//set the environment here
process.env.dev = true;
var assert = require('assert');
var s = require('./script.js');
describe('Test', function () {
it('should use different config file', function() {
assert.equal('test.txt', s.getFileName());
});
});

I have not found any elegant solution out there on the web so I have implemented and published my own.
Check it out here: https://npmjs.org/package/app-config
Using the app-config plugin, only the script.js needs to get changed this way:
var config = require('app-config').app;
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
The app needs to be run this way for example
NODE_ENV=dev node script.js
NODE_ENV=unitTest mocha test.js
Depending on the NODE_ENV environmental variable, the right set of configuration files will be loaded by the app-config plugin.

Related

Using Webpack to add JavaScript module to ASP.NET MVC app

I'm trying to use Webpack to create a couple of simple modules in an ASP.NET MVC 5 Visual Studio 2015 project. Following instructions on the Webpack site, I downloaded the latest version of Node.js. Then using the Node command prompt, changed to my project's folder. There, I ran this command to install Webpack locally:
npm install webpack --save-dev
It created a package.json file in the root of my project:
{
"devDependencies": {
"webpack": "^2.4.1"
}
}
Note that the project already has jQuery and Bootstrap as bundles via the BundleConfig.cs, which are then referenced on _Layout.cshtml; hence they're available on all pages of the app.
Now I'd like to create a very simple test to see how to create and require modules using Webpack; once I understand it better, I can add more complex modules. I've been reading about code-splitting: https://webpack.js.org/guides/code-splitting-async/ but it's still not clear how you do this.
The function test requires function isEmpty. I'd like to define isEmpty as a module and then use it with test.
var test = function(value){
return isEmpty(value);
};
var isEmpty = function(value) {
return $.trim(value).length === 0 ? true : false;
};
This article has been helping: http://developer.telerik.com/featured/webpack-for-visual-studio-developers/
The Webpack documentation mentions import() and also require.ensure(). How do I use Webpack to modularize the isEmpty code and then use it?
Webpack allows you to use the commonJS approach for dependency management which Node.js uses, so if you have experience with Node.js it's very similar.
If not have a look at this article on the module system or the spec for a description of the module system.
For this problem I will assume all files are in the same directory. I think you will need to first move the isEmpty code into a separate file maybe isEmpty.js and change it's structure a bit so that it looks like this:
module.exports = function(value) {
return $.trim(value).length === 0 ? true : false;
};
then your test function can be moved into a separate test.js file and you can require the isEmpty module and use it like this:
var isEmpty = require('./isEmpty');
var test = function(value){
return isEmpty(value);
};
You will probably have to do something about the dependency on $ (I'm guessing jquery?) but I think that can be handled with shimming
If you have a number of functions you can do something like:
someFunctions.js
var self = {};
self.Double = function(value){
return value*2;
}
self.Triple = function(value){
return value*3;
}
module.exports = self;
useFunctions.js
var useFunctions = require('./someFunctions');
var num = 5;
console.log(useFunctions.Double(num));
console.log(useFunctions.Triple(num));

Using require with relative paths

We have a rather big set of end-to-end tests on Protractor. We are following the Page Object pattern which helps us to keep our tests clean and modular. We also have a set of helper functions which help us to follow the DRY principle.
The Problem:
A single spec may require multiple page objects and helper modules. For instance:
"use strict";
var helpers = require("./../../helpers/helpers.js");
var localStoragePage = require("./../../helpers/localStorage.js");
var sessionStoragePage = require("./../../helpers/sessionStorage.js");
var loginPage = require("./../../po/login.po.js");
var headerPage = require("./../../po/header.po.js");
var queuePage = require("./../../po/queue.po.js");
describe("Login functionality", function () {
beforeEach(function () {
browser.get("/#login");
localStoragePage.clear();
});
// ...
});
You can see that we have that directory traversal in every require statement: ./../... This is because we have a specs directory where we keep the specs and multiple directories inside grouped by application functionality under test.
The Question:
What is the canonical way to approach the relative path problem in Protractor?
In other words, we'd like to avoid traversing the tree, going up to import modules. It would be much cleaner to go down from the base application directory instead.
Attempts and thoughts:
There is a great article about approaching this problem: Better local require() paths for Node.js, but I'm not sure which of the options is a recommended one when developing tests with Protractor.
We've also tried to use require.main to construct the path, but it points to the node_modules/protractor directory instead of our application directory.
I had the same problem and I ended up with the following solution.
In my Protractor config file I have a variable which stores a path to a base folder of my e2e tests. Also, Protractor config provides the onPrepare callback, where you can use a variable called global to create global variables for your tests. You define them as a properties of that global variable and use the same way you use globals browser or element in tests. I've used it to create custom global require functions to load different types of entities:
// __dirname retuns a path of this particular config file
// assuming that protractor.conf.js is in the root of the project
var basePath = __dirname + '/test/e2e/';
// /path/to/project/test/e2e/
exports.config = {
onPrepare: function () {
// "relativePath" - path, relative to "basePath" variable
// If your entity files have suffixes - you can also keep them here
// not to mention them in test files every time
global.requirePO = function (relativePath) {
return require(basePath + 'po/' + relativePath + '.po.js');
};
global.requireHelper = function (relativePath) {
return require(basePath + 'helpers/' + relativePath + '.js');
};
}
};
And then you can use these global utility methods in your test files right away:
"use strict";
var localStorageHelper = requireHelper('localStorage');
// /path/to/project/test/e2e/helpers/localStorage.js
var loginPage = requirePO('login');
// /path/to/project/test/e2e/po/login.po.js
var productShowPage = requirePO('product/show');
// /path/to/project/test/e2e/po/product/show.po.js
describe("Login functionality", function () {
beforeEach(function () {
browser.get("/#login");
localStorageHelper.clear();
});
// ...
});
We've been facing the same issue and decided to turn all page object and helper files into node packages. Requiring them in tests is now as easy as var Header = require('header-po'). Another benefit of converting to packages is that you can use proper versioning.
Here is a simple example:
./page-objects/header-po/index.js
//page-objects/header-po/index.js
'use strict';
var Header = function () {
this.goHome = function () {
$('#logo a').click();
};
};
module.exports = Header;
./page-objects/header-po/package.json
{
"name": "header-po",
"version": "0.1.1",
"description": "Header page object",
"main": "index.js",
"dependencies": {}
}
./package.json
{
"name": "e2e-test-framework",
"version": "0.1.0",
"description": "Test framework",
"dependencies": {
"jasmine": "^2.1.1",
"header-po": "./page-objects/header-po/",
}
}
./tests/header-test.js
'use strict';
var Header = require('header-po');
var header = new Header();
describe('Header Test', function () {
it('clicking logo in header bar should open homepage', function () {
browser.get(browser.baseUrl + '/testpage');
header.goHome();
expect(browser.getCurrentUrl()).toBe(browser.baseUrl);
});
});
I have had the same issue. Did similar solution to Michael Radionov's, but not setting a global function, but setting a property to protractor itself.
protractor.conf.js
onPrepare: function() {
protractor.basePath = __dirname;
}
test-e2e.js
require(protractor.basePath+'/helpers.js');
describe('test', function() {
.......
});
I think the method we use where I work might be a good solution for you. I have posted a brief example of how we handle everything. It's pretty nice b/c you can just call the page object functions in any spec file and you don't need to use require in the spec.
Call a node module from another module without using require() everywhere
All answers seem to be more of workarounds
The actual working solution would be this:
install module alias
add this to your package.json
"_moduleAliases": {
"#protractor": "protractor/_protractor",
"#tmp": "protractor/.tmp_files",
"#test_data": "protractor/.tmp_files/test_data",
"#custom_implementation": "protractor/custom_implementation",
},
add this as very first line of your protractor config
require('module-alias/register');
use it anywhere in the project like so
const params = require('#test_data/parameters');
const customImplementation require('#custom_implementation')
// etc

Jasmine - Globally available object

I have a web site that I'm testing via Jasmine. My tests are spread across multiple JavaScript files. For that reason, I would like to have a JavaScript object that I can share across my tests. For example, I'd like to have the following JSON be available to all of the tests in my files.
var settings = {
rootUrl: 'http://www.example.com',
username: 'test'
};
Then, in my tests, I'd like to do something like the following:
tests1.js
describe('TestSet1', function() {
it('Should load properly', function(done) {
var url = settings.rootUrl + '/contact';
// do stuff
});
});
tests2.js
describe('TestSet2', function() {
it('Should load properly', function(done) {
var url = settings.rootUrl + '/login';
// do stuff
});
});
How do I get settings to be available across JavaScript test files? Where do I define settings? How do I import settings into my tests?
Thank you
If this is node, you can require it in at the top of all the pages:
var settings = require('./settings.json');
If browser, you should be able to add a dependency above the test adding it to the global scope.
window.settings = {};
In node.js you would var settings = require('./settings'); at the beginning of your tests. Export the settings variable in the settings file:
var settings = {
rootUrl: 'http://www.example.com',
username: 'test'
};
module.exports = settings;
In browser you might just want to include the file with a script tag before you include your specs:
<!-- include spec files here... -->
<script src="spec/settings.js"></script>
<script src="spec/test1.js"></script>
<script src="spec/test2.js"></script>

why is jasmine-node not picking up my helper script?

This question is likely based in my lack of previous experience with node.js, but I was hoping jasmine-node would just let me run my jasmine specs from the command line.
TestHelper.js:
var helper_func = function() {
console.log("IN HELPER FUNC");
};
my_test.spec.js:
describe ('Example Test', function() {
it ('should use the helper function', function() {
helper_func();
expect(true).toBe(true);
});
});
Those are the only two files in the directory. Then, when I do:
jasmine-node .
I get
ReferenceError: helper_func is not defined
I'm sure the answer to this is easy, but I didn't find any super-simple intros, or anything obvious on github. Any advice or help would be greatly appreciated!
Thanks!
In node, everything is namespaced to it's js file. To make the function callable by other files, change TestHelper.js to look like this:
var helper_func = function() {
console.log("IN HELPER FUNC");
};
// exports is the "magic" variable that other files can read
exports.helper_func = helper_func;
And then change your my_test.spec.js to look like this:
// include the helpers and get a reference to it's exports variable
var helpers = require('./TestHelpers');
describe ('Example Test', function() {
it ('should use the helper function', function() {
helpers.helper_func(); // note the change here too
expect(true).toBe(true);
});
});
and, lastly, I believe jasmine-node . will run every file in the directory sequentially - but you don't need to run the helpers. Instead you could move them to a different directory (and change the ./ in the require() to the correct path), or you could just run jasmine-node *.spec.js.
you do not necessarily need to include your helper script in the spec (testing) file if you have the jasmine config as:
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": false
}
Everything in the helpers/ folder will run before the Spec files. In the helpers files have something like this to include your function.
beforeAll(function(){
this.helper_func = function() {
console.log("IN HELPER FUNC");
};
});
you will then be able to make references to it in your spec files

Why do I see "define not defined" when running a Mocha test with RequireJS?

I am trying to understand how to develop stand-alone Javascript code. I want to write Javscript code with tests and modules, running from the command line. So I have installed node.js and npm along with the libraries requirejs, underscore, and mocha.
My directory structure looks like this:
> tree .
.
├── node_modules
├── src
│   └── utils.js
└── test
└── utils.js
where src/utils.js is a little module that I am writing, with the following code:
> cat src/utils.js
define(['underscore'], function () {
"use strict";
if ('function' !== typeof Object.beget) {
Object.beget = function (o) {
var f = function () {
};
f.prototype = o;
return new f();
};
}
});
and test/utils.js is the test:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils'], function(utils) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
which I then try to run from the top level directory (so mocha sees the test directory):
> mocha
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("../src/utils") failed with error: ReferenceError: define is not defined
at /.../node_modules/requirejs/bin/r.js:2276:27
at Function.execCb (/.../node_modules/requirejs/bin/r.js:1872:25)
at execManager (/.../node_modules/requirejs/bin/r.js:541:31)
...
So my questions are:
Is this the correct way to structure code?
Why is my test not running?
What is the best way to learn this kind of thing? I am having a hard time finding good examples with Google.
Thanks...
[sorry - momentarily posted results from wrong code; fixed now]
PS I am using requirejs because I also want to run this code (or some of it) from a browser, later.
Update / Solution
Something that is not in the answers below is that I needed to use mocha -u tdd for the test style above. Here is the final test (which also requires assert) and its use:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils', 'assert'], function(utils, assert) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
> mocha -u tdd
.
✔ 1 tests complete (1ms)
The reason your test isn't running is because src/utils.js is not a valid Node.js library.
According to the RequireJS documentation, in order to co-exist with Node.js and the CommonJS require standard, you need to add a bit of boilerplate to the top of your src/utils.js file so RequireJS's define function is loaded.
However, since RequireJS was designed to be able to require "classic" web browser-oriented source code, I tend to use the following pattern with my Node.js libraries that I also want running in the browser:
if(typeof require != 'undefined') {
// Require server-side-specific modules
}
// Insert code here
if(typeof module != 'undefined') {
module.exports = whateverImExporting;
}
This has the advantage of not requiring an extra library for other Node.js users and generally works well with RequireJS on the client.
Once you get your code running in Node.js, you can start testing. I personally still prefer expresso over mocha, even though its the successor test framework.
The Mocha documentation is lacking on how to set this stuff up, and it's perplexing to figure out because of all the magic tricks it does under the hood.
I found the keys to getting browser files using require.js to work in Mocha under Node: Mocha has to have the files added to its suites with addFile:
mocha.addFile('lib/tests/Main_spec_node');
And second, use beforeEach with the optional callback to load your modules asynchronously:
describe('Testing "Other"', function(done){
var Other;
beforeEach(function(done){
requirejs(['lib/Other'], function(_File){
Other = _File;
done(); // #1 Other Suite will run after this is called
});
});
describe('#1 Other Suite:', function(){
it('Other.test', function(){
chai.expect(Other.test).to.equal(true);
});
});
});
I created a bootstrap for how to get this all working: https://github.com/clubajax/mocha-bootstrap
You are trying to run JS modules designed for browsers (AMD), but in the backend it might not work (as modules are loaded the commonjs way). Because of this, you will face two issues:
define is not defined
0 tests run
In the browserdefine will be defined. It will be set when you require something with requirejs. But nodejs loads modules the commonjs way. define in this case is not defined. But it will be defined when we require with requirejs!
This means that now we are requiring code asynchronously, and it brings the second problem, a problem with async execution.
https://github.com/mochajs/mocha/issues/362
Here is a full working example.
Look that I had to configure requirejs (amd) to load the modules, we are not using require (node/commonjs) to load our modules.
> cat $PROJECT_HOME/test/test.js
var requirejs = require('requirejs');
var path = require('path')
var project_directory = path.resolve(__dirname, '..')
requirejs.config({
nodeRequire: require,
paths: {
'widget': project_directory + '/src/js/some/widget'
}
});
describe("Mocha needs one test in order to wait on requirejs tests", function() {
it('should wait for other tests', function(){
require('assert').ok(true);
});
});
requirejs(['widget/viewModel', 'assert'], function(model, assert){
describe('MyViewModel', function() {
it("should be 4 when 2", function () {
assert.equal(model.square(2),4)
})
});
})
And for the module that you want to test:
> cat $PROJECT_HOME/src/js/some/widget/viewModel.js
define(["knockout"], function (ko) {
function VideModel() {
var self = this;
self.square = function(n){
return n*n;
}
}
return new VideModel();
})
Just in case David's answer was not clear enough, I just needed to add this:
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
To the top of the js file where I use define, as described in RequireJS docs ("Building node modules with AMD or RequireJS") and in the same folder add the amdefine package:
npm install amdefine
This creates the node_modules folder with the amdefine module inside.
I don't use requirejs so I'm not sure what that syntax looks like, but this is what I do to run code both within node and the browser:
For imports, determine if we are running in node or the browser:
var root = typeof exports !== "undefined" && exports !== null ? exports : window;
Then we can grab any dependencies correctly (they will either be available already if in the browser or we use require):
var foo = root.foo;
if (!foo && (typeof require !== 'undefined')) {
foo = require('./foo');
}
var Bar = function() {
// do something with foo
}
And then any functionality that needs to be used by other files, we export it to root:
root.bar = Bar;
As for examples, GitHub is a great source. Just go and check out the code for your favorite library to see how they did it :) I used mocha to test a javascript library that can be used in both the browser and node. The code is available at https://github.com/bunkat/later.

Categories

Resources