How to create QUnit tests with reference to another class? - javascript

I'm trying to add unit testing for JavaScript into my web site. I use VS2013 and my project is an ASP.NET web site.
Based on recommendations (http://www.rhyous.com/2013/02/20/creating-a-qunit-test-project-in-visual-studio-2010/) I've done so far:
Created new ASP.NET app
Imported QUnit (using NuGet)
Into "Scripts" added links to js-file in my original web site (files PlayerSkill.js - containts PlayerSkill class and trainings.js - contains Trainer and some other classes)
Created new folder "TestScripts"
Added TrainingTests.js file
Wrote simple test:
test( "Trainer should have non-empty group", function () {
var group = "group";
var trainer = new Trainer(123, "Name123", group, 123);
EQUAL(trainer.getTrainerGroup(), group);
});
Notice: my trainings.js file among others contains
function Trainer(id, name, group, level) {
...
var _group = group;
this.getTrainerGroup = function () { return _group ; }
};
When I execute my test I see error: Trainer is not defined.
It looks like reference to my class is not recognized. I feel like linking file is not enough, but what did I miss?
Please help add reference to the original file with class and run unit test.
Thank you.
P.S. Question 2: Can I add reference to 2 files (my unit test will require one more class which is in another file)? How?

You should add all the relevant logic of your application to your unit testing file so they all execute before you run your tests
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Test Results</title>
<link rel="stylesheet" href="/Content/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="/Scripts/qunit.js"></script>
<script src="/Scripts/PlayerSkill.js"></script>
<script src="/Scripts/trainings.js"></script>
<script src="/TestScripts/TrainingTests.js"></script>
</body>
</html>
You should not use linked files because they will not exist physically in the script folder.
If you really want to use them you should let the Visual Studio intellisense resolve the physical path of the file like this.
Type the script tag <script src=""></script>
Place the cursor inside the quotes in the src attribute and press CTRL + SPACE
Search your files and let the resolved path untouched
If your project location changes you must update the linked files and also the script references.
{Edit1}
Solution 2:
You could also use an MVC Controller and a Razor View to create your unit testing page and the linked files will work as expected with the only issue that you will have an extra controller in your project but this is not bad at all if for example you want to test the loading of content using ajax that is by default blocked by the browser if they are run from a local file.
Solution 3:
You can also setup a new MVC project just for your javascript unit testing just as you usually setup a new project for any server side code and this will help to prevent your testing to interfere with your production code
{Edit 2}
Solution 4:
As part of the javascript ecosystem you could use grunt or gulp to automate the copy of your scripts from anywhere to your project before running the tests. You could write a gulpfile.js like this
var sourcefiles = [/*you project file paths*/];
gulp.task('default', function () {
return gulp.src(sourcefiles).pipe(gulp.dest('Scripts'));
});
And then run it opening a console and running the command gulp or gulp default

Looks like trainings.js is not defined when calling TrainingTests.js . See this question for more details regarding why this happens! Once that is fixed it does work. And yes similar to trainings.js you can have any number of files in any folder as long as you reference them properly. I have created a sample fiddle accessible # http://plnkr.co/edit/PnqVebOzmPpGu7x2qWLs?p=preview
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="http://code.jquery.com/qunit/qunit-1.18.0.js"></script>
<script src="trainings.js"></script>
<script src="TrainingTests.js"></script>
</body>

In my case I wanted to run my tests from within my ASP.NET web application, and also on a CI server. In addition to the other information here I needed the following, otherwise I experienced the same error as the OP on my CI server:
Add one or more require() calls to test scripts.
Set the NODE_PATH environment variable to the root of my application.
Example of require()
Within my test scripts I include a requires block, the conditional allows me to use this script from a web browser without needing to adopt a third-party equivalent such as requirejs (which is convenient.)
if (typeof(require) !== 'undefined') {
require('lib/3rdparty/dist/3p.js');
require('js/my.js');
require('js/app.js');
}
Example of setting NODE_PATH
Below, 'wwwroot' is the path of where /lib/ and other application files are located. My test files are located within /tests/.
Using bash
#!/bin/bash
cd 'wwwroot'
export NODE_PATH=`pwd`
qunit tests
Using powershell
#!/usr/bin/pwsh
cd 'wwwroot'
$env:NODE_PATH=(pwd)
qunit tests
This allowed me to run tests both within my ASP.NET web application, and also from a CI server using a script.
HTH.

If you're wondering how to make your tests see your code when running from command line (not from browser!), here is a bit expanded version of Shaun Wilson's answer (which doesn't work out-of-the-box, but contains a good idea where to start)
Having following structure:
project
│ index.js <--- Your script with logic
└───test
tests.html <--- QUnit tests included in standard HTML page for "running" locally
tests.js <--- QUnit test code
And let's imagine that in your index.js you have following:
function doSomething(arg) {
// do smth
return arg;
}
And the test code in tests.js (not that it can be the whole content of the file - you don't need anything else to work):
QUnit.test( "test something", function( assert ) {
assert.ok(doSomething(true));
});
Running from command line
To make your code accessible from the tests you need to add two things to the scripts.
First is to explicitly "import" your script from tests. Since JS doesn't have sunch a functionality out-of-the box, we'll need to use require coming from NPM. And to keep our tests working from HTML (when you run it from browser, require is undefined) add simple check:
// Add this in the beginning of tests.js
// Use "require" only if run from command line
if (typeof(require) !== 'undefined') {
// It's important to define it with the very same name in order to have both browser and CLI runs working with the same test code
doSomething = require('../index.js').doSomething;
}
But if index.js does not expose anything, nothing will be accessible. So it's required to expose functions you want to test explicitly (read more about exports). Add this to index.js:
//This goes to the very bottom of index.js
if (typeof module !== 'undefined' && module.exports) {
exports.doSomething = doSomething;
}
When it's done, just type
qunit
And the output should be like
TAP version 13
ok 1 Testing index.js > returnTrue returns true
1..1
# pass 1
# skip 0
# todo 0
# fail 0

Well, due to help of two answers I did localize that problem indeed was in inability of VS to copy needed file into test project.
This can be probably resolved by multiple ways, I found one, idea copied from: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
Solution is simple: add tag dynamically
In order to achieve this, I've added the following code into tag:
<script>
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
var path = 'path'; // here is an absolute address to JS-file on my web site
fileref.setAttribute("src", path);
document.getElementsByTagName("head")[0].appendChild(fileref);
loadjscssfile(, "js") //dynamically load and add this .js file
</script>
And moved my tests into (required also reference to jquery before)
$(document).ready(function () {
QUnit.test("Test #1 description", function () { ... });
});
Similar approach also works for pure test files.

Related

Minify/uglify html page with embedded script tags in a nodejs app

I have an express app that, among other things, delivers some html code based on a single handlebars template.
It would be great for the use-case to deliver it with short latency. So I read and compile the template when the app starts and for now I simply call
res.send(
compiledTemplateIframeContent({ data: iframeData })
)
All of that works flawlessly.
The problem
Now I would like to minify the html and uglify the js code. I tried with html-minifier but the embedded javascript is not uglified (renaming variables), not even minified (eg remove whitespaces). I guess uglify-js is not called in the background because of some miss-configuration. I can't find my mistake by reading the docs.
I wrote some test html code and tried it in this online tool. It is just a simple gui infront of html-minifier and therefor potentially a good way to test my problem.
In the online version I can at least make it compress the javascript code when I add type="text/javascript" to the tag and text/javascript to the Process scripts option (even this does not work in my express app).
But also in the online tool the Minify JavaScript checkbox does not change anything.
I don't know the possibilities of uglifyjs yet (a dependency of html-minifier) but with that name I would assume it should not only compress but also uglify the js code.
Edit / Update
I did some more research. I extracted the js code by regex match and just called uglify-js directly with the code. It had some problems with the handlebar fragments {{ }}. After removing them uglif-js works on the embedded js part of the template.
As I have set the option ignoreCustomFragments: [/{{.*}}/g] for the html-minifier I guess this should not be the problem?!
Here is the part that directly uses uglify-js
function minifyWithUglifyJs(orig: string): string {
const re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
const match = re.exec(orig);
if(match == null) {
throw new Error(`Can't minify js in iframe template as found no match for js script!`);
}
const origJs = match[1] as string;
console.log(origJs);
const minifyResult = uglifyjs.minify(origJs);
if(minifyResult.warnings != null) {
minifyResult.warnings.forEach(logger.warn);
}
if(minifyResult.error) {
throw new Error(`Can't minify the iframe template!`, {cause:minifyResult.error});
} else {
// replace orig js with minified js in code
return orig.replace(origJs, minifyResult.code);
}
}
Summing it up:
does anyone know what I do wrong with the http-minifier?
Here is my attempt to minify in my node app (using html-minifier#4.0.0)
import htmlMinifier from 'html-minifier';
function minifyWithHtmlMinifier(orig: string):string {
return htmlMinifier.minify(orig, {
minifyJS: true,
processScripts: ["text/javascript"],
ignoreCustomFragments: [/{{.*}}/g]
});
}
And here is some test code one can use in the online tool
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test ad</title>
</head>
<body onload="onLoad()">
<div id="img-container" style="width:100%;height:100%">test text in page</div>
<script type="text/javascript">
const longNameThatShouldBeUglified= 12;
console.log("test");
//{{another test}}
function onLoad() {
console.log("longNameThatShouldBeUglified (Not this time as it's a string) "+longNameThatShouldBeUglified);
}
</script>
</body>
</html>
The problem is, that html-minifier does not give you any warnings when uglify-js throws any errors. I thought I had misconfigured html-minifier becaue it did not minify.
After splitting my code to get only the content between the tags and using uglify-js directly I saw the problems and could fix the to-be-minified code. As soon as it worked I switched back to using html-minifier and it worked.
I now use the following code where I tell html-minifier to use uglify-js wrapped in some code to recognize any problems.
function minifyWithHtmlMinifier(orig: string):string {
return htmlMinifier.minify(orig, {
// I have replaced the default minifyJS usage of the html-minifier
// as this silently ignores any uglifyjs errors and just displays
// the non-minified code. Has cost me half a day to figure out
// that it was not a configuration problem but problem with the
// to-be-minified-code.
// By setting the call to uglifyjs myself I can catch the errors and
// rethrow them, failing fast, as this is much better than recognizing
// a not-minified code much later when I don't remember what I changed
minifyJS: (text, _inline) => {
const minifyResult = uglifyjs.minify(text, {
compress: {
drop_console: true // remove all console log entries
}
});
if(minifyResult.warnings != null) {
minifyResult.warnings.forEach(logger.warn);
}
if(minifyResult.error) {
// TODO maybe use terser. I think it supports
// newer ES versions than uglifyjs
throw new Error(`Can't minify the iframe template!`, {cause:minifyResult.error});
}
return minifyResult.code;
},
minifyCSS: true,
ignoreCustomFragments: [/{{.*}}/g], // handlebars fragments
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: true,
collapseWhitespace: true
});
}
Important to note:
there is also html-minifier-terser that did not come up during my upfront research on what minifier to use with nodejs. Maybe it als does better reporting.

Copy files with Yeoman generator doesn't work

I'm developing my own generator with Yeoman. When I try to copy some files, nothing happens. No error, the process continues until it reach the end, but no files are copied. The generator has a /templates dir with a bunch of html files, each file has a few html lines, at the moment quite simple stuff.
This is my copy method:
copyMainFiles: function(){
console.log('copyMainFiles dir:' + process.cwd() + '+++++');
console.log('file exists? '+fs.existsSync('_footer.html') );
this.copy("_footer.html", "app/footer.html");
console.log('footer copied');
this.copy("_gruntfile.js", "Gruntfile.js");
console.log('gruntfile copied');
this.copy("_package.json", "package.json");
console.log('package copied');
this.copy("_main.css", "app/css/main.css");
console.log('main.css copied');
var context = {
site_name: this.appName
};
console.log('all files copied');
//template method makes the replacement and then copy
this.template("_header.html", "app/header.html", context);
console.log('header template processed');
},
this is the console output:
$ yo trx
method 1 just ran
method 2 just ran
? What is your app's name ?
Kosheen
? Would you like to generate a demo section ? Yes
all dirs created
copyMainFiles dir:C:\cygwin\Applications\MAMP\htdocs\prueba-trx+++++
file exists? false
footer copied
gruntfile copied
package copied
main.css copied
all files copied
header template processed
running npm
and that's it. Never returns to system prompt.
Besides the fact that fs.existsSync returns false (the file exists: htdocs\generator-trx\generators\app\templates_footer.html ), if I try to copy a non-existent file I get the typical error.
Folders are created previously with no issue. There's a .yo_rc.json file with {} in the root of the destination folder. The Yeoman version is 1.4.8, working on Windows 7.
Is copy() the proper way to do this or is no longer valid? How can I copy a simple file in this scenario?
Beside the fact of I was using deprecated methods, the proper way to achive this task is as follow:
this.fs.copy(
this.templatePath('_bower.json'),
this.destinationPath('bower.json')
);
Not sure what your issue is, but you should read the Yeoman official documentation on how to handle files: http://yeoman.io/authoring/file-system.html
You're using old and deprecated methods.

gulp: Automatically add version number to request for preventing browser cache

I deploy my project by building source files with gulp right on the server. To prevent caching issues, the best practice could be adding a unique number to request url, see: Preventing browser caching on web application upgrades;
In npm repositories, I couldn't find a tool for automatically adding version number to request. I'm asking if someone has invented such tool before.
Possible implementation could be the following:
I have a file index.html in src/ folder, with following script tag
<script src="js/app.js<!-- %nocache% -->"></script>
During build it is copied to dist/ folder, and comment is replaced by autoincrement number
<script src="js/app.js?t=1234"></script>
You can use gulp-version-number for this. It can add version numbers to linked scripts, stylesheets, and other files in you HTML documents, by appending an argument to the URLs. For example:
<link rel="stylesheet" href="main.css">
becomes:
<link rel="stylesheet" href="main.css?v=474dee2efac59e2dcac7bf6c37365ed0">
You don't even have to specify a placeholder, like you showed in your example implementation. And it's configurable.
Example usage:
const $ = gulpLoadPlugins();
const versionConfig = {
'value': '%MDS%',
'append': {
'key': 'v',
'to': ['css', 'js'],
},
};
gulp.task('html', () => {
return gulp.src('src/**/*.html')
.pipe($.htmlmin({collapseWhitespace: true}))
.pipe($.versionNumber(versionConfig))
.pipe(gulp.dest('docroot'));
});
NOTE:
I can no longer recommend this plugin. It is no longer maintained and there are some issues with it. I created a pull request some time ago, but there is no response from the author.
You can use the gulp-rev module. This will append a version number to the files, the version is a hash of the file content, so it will only change if the file changes.
You then output a manifest file containing the mapping between the file e.g. Scripts.js to Scripts-8wrefhn.js.
Then use a helper function when returning the page content to map the correct values.
I have used the above process. However there's another module gulp-rev-all which is an forked extension of gulp-rev which does a little more, e.g. automatic updating of file references in pages.
Documentation here:
gulp-rev: https://github.com/sindresorhus/gulp-rev
gulp-rev-all: https://www.npmjs.com/package/gulp-rev-all
I worked onto writing an regex, which in use along with gulp-replace works just fine.
Please find the code below. Following is a quick code for the image and css for views files codeigniter framework. But it should work fine for all the kinds of files given the source folder specified correctly.
You may customize the code as per your use.
You can call the tasks altogether, using gulp default or individual task at a time.
'use strict';
var gulp = require('gulp');
var replace = require('gulp-replace');
function makeid() {
return (Math.random() + 1).toString(36).substring(7);
}
gulp.task('versioningCss', () => {
return gulp.src('application/modules/**/views/*.php')
.pipe(replace(/(.*)\.css\?(_v=.+&)*(.*)/g, '$1.css?_v='+makeid()+'&$3'))
.pipe(replace(/(.*)\.css\"(.*)/g, '$1.css?_v='+makeid()+'"$2'))
.pipe(replace(/(.*)\.css\'(.*)/g, '$1.css?_v='+makeid()+'\'$2'))
.pipe(gulp.dest('application/modules'));
});
gulp.task('versioningJs', () => {
return gulp.src('application/modules/**/views/*.php')
.pipe(replace(/(.*)\.js\?(_v=.+&)*(.*)/g, '$1.js?_v='+makeid()+'&$3'))
.pipe(replace(/(.*)\.js\"(.*)/g, '$1.js?_v='+makeid()+'"$2'))
.pipe(replace(/(.*)\.js\'(.*)/g, '$1.js?_v='+makeid()+'\'$2'))
.pipe(gulp.dest('application/modules'));
});
gulp.task('versioningImage', () => {
return gulp.src('application/modules/**/views/*.php')
.pipe(replace(/(.*)\.(png|jpg|jpeg|gif)\?(_v=.+&)*(.*)/g, '$1.$2?_v='+makeid()+'&$4'))
.pipe(replace(/(.*)\.(png|jpg|jpeg|gif)\"(.*)/g, '$1.$2?_v='+makeid()+'"$3'))
.pipe(replace(/(.*)\.(png|jpg|jpeg|gif)\'(.*)/g, '$1.$2?_v='+makeid()+'\'$3'));
});
gulp.task('default', [ 'versioningCss', 'versioningJs', 'versioningImage']);
It looks like you may have quite a few options.
https://www.npmjs.com/package/gulp-cachebust
https://www.npmjs.com/package/gulp-buster
Hope this helps.
You can use
<script type="text/javascript" src="js/app.js?seq=<%=DateTime.Now.Ticks%>"></script>
or
<script type="text/javascript" src="js/app.js?seq=<%=DateTime.Now.ToString("yyyyMMddHHmm") %>"></script>

Use prelude-ls with LiveScript

I just need to use prelude-ls library in LiveScript, but no from the REPL. In my little test, I have 4 files:
main.htm
application.ls
application.js
require.js
I have the latest version of require.js (2.1.15) and in my main.htm I load the scripts:
<!DOCTYPE html>
<html>
<head>
<script src="./require.js" type="text/javascript"></script>
<script src="./prelude.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Then, I go to my application.ls to test:
require! 'prelude-ls'
[1 2 3] |> prelude-ls.map (* 2)
My compile command is:
lsc -cwd $myFilePath
And it compiles just fine. Then, I go there to get the final result, to test and receive the following error:
Uncaught Error: Module name "prelude-ls" has not been loaded yet for context: _. Use require([])
Well, I saw the this is a very common error and its corrections would happen in the js file, not in the ls and none of the links I followed solved my problems. I've tried it in 2 computers and had the really same result.
My final js file, application.js is:
// Generated by LiveScript 1.2.0
(function(){
var preludeLs;
preludeLs = require('prelude-ls');
preludeLs.map((function(it){
return it * 2;
}))(
[1, 2, 3]);
}).call(this);
Plase, help me if possible. I really read all the documentation of livescript and it doens't cites its first use with prelude-ls.
I think you're confusing AMD.js (here, Require.JS) and CommonJS.
AMD.js uses the
require(['dep1', 'dep2'], function (dep1, dep2) {
dep1.callSomething();
});
(this allows for async loading)
CommonJS (which is what prelude-ls uses), on the other hand, is basically what node does (and what we generate with require!):
var preludeLs = require('prelude-ls')
At first I didn't understand, I find the answer confusing, though correct. Please let me sum it up.
Actually it's very simple and it works as says the doc.
We must install prelude-ls with npm or bower. We need to include the file prelude-browser.js (at prelude-ls/browser/prelude-browser.js).
Then we just require prelude at the beginning of our code:
prelude = require 'prelude-ls'
and we can call prelude.sum, etc.
A second option is to import exactly the function we need, like so:
{map, filter, lines} = require 'prelude-ls'
so we can call them directly.
That works with gulp and angularjs FYI.
This answer is clear.

Problem using Dojo build tool, 'could not load' error now occuring when trying to use compiled scripts

I was following along to this post by Rebecca Murphey: http://blog.rebeccamurphey.com/scaffolding-a-buildable-dojo-application
I was substituting her file structure with my own.
Running the normal version of the scripts works fine, but the moment I compile them using the build tool, the script errors.
It's very likely a small problem with how the files are referenced via my Profile.js script but maybe someone here can help me get the settings correct before running the build tool so the compiled files will work as they should.
My file structure is as follows...
/www
/Assets
/Scripts
/Classes
build.sh
Init.js
Load.js
Profile.js
/Dojo
Dojo.js
/dojo-sdk
index.html
My index.html file has the following code...
<script>
var djConfig = {
modulePaths : {
'Integralist' : '../Classes'
}
};
</script>
<script src="Assets/Scripts/Dojo/Dojo.js"></script>
<script>
dojo.require('Integralist.Init');
</script>
...and the Init.js file has the following code...
dojo.provide('Integralist.Init');
dojo.require('Integralist.Load');
dojo.declare('MyApp', null, {
constructor: function(config) {
this.version = config.version || '1.0';
this.author = config.author || 'Unknown';
}
});
var myapp = new MyApp({
author: 'Mark McDonnell'
});
alert(myapp.author);
alert(myapp.version);
...lastly, the Load.js file has nothing in it but this...
dojo.provide('Integralist.Load');
alert('I\'m the Load.js file');
...and this all runs fine. When I load index.html I get 3 alert messages, brilliant.
The problem occurs when I try to run the build tool.
Via Mac OSX i locate the /Classes/ directory and run 'sh build.sh' and the build.sh file within the /Classes/ directory consists of the following code...
cd ../../../dojo-sdk/util/buildscripts
./build.sh profileFile=../../../Assets/Scripts/Classes/Profile.js releaseDir=../../../Assets/Scripts/Release
...now, after running the build tool I have a new /Release/ directory created within my /Scripts/ directory, this /Release/ directory consists of...
/www
/Assets
/Scripts
/Release
/Integralist
/Classes
Init.js
Init.js.uncompressed.js
/dojo
--loads of dojo related files--
...I then created a separate index file called index-release-version.html and changed the script code as suggested by the article, so it looks like this...
<script src="Assets/Scripts/Release/Integralist/dojo/dojo.js"></script>
<script>
dojo.require('Integralist.Init');
</script>
...from here I get the following error...
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught Error: Could not load 'Integralist.Init'; last tried '../Integralist/Init.js'
...and just for reference my Profile.js file that is used by the build tool consists of the following (and it's here I think the problem may be)...
dependencies = {
stripConsole : 'all',
action : 'clean,release',
optimize : 'shrinksafe',
releaseName : 'Integralist',
localeList : 'en-gb',
layers: [
{
name: "../Classes/Init.js",
resourceName : "Integralist.Init",
dependencies: [
"Integralist.Init"
]
}
],
prefixes: [
[ "Integralist", "../Classes" ]
]
}
Any help really appreciated as I desperately want to get my head around how Dojo works :-)
Thanks!
M.
I'd suggest working from the repo I linked to from my blog post (http://github.com/rmurphey/dojo-scaffold) -- I double-checked that it's definitely working :) -- and make changes to it until your changes break something, rather than trying to create your own structure right off the bat.
At a glance, I'm not 100% clear why you've got a Dojo.js file inside your directory structure, (is this the base Dojo lib or something else?), but the rest of Dojo is located elsewhere. If you use the structure I proposed, you can safely remove the djConfig declaration when using the built files, but as Dan mentioned, you may need to keep it if you're using a different configuration.
Do you have that djConfig variable in your index-release-version.html? It looks like Dojo is trying to find init.js at ../Integralist/Init.js, but you somehow need to tell it to look in ../Classes/Init.js
This is what your modulePaths : {'Integralist' : '../Classes'} was doing in your Index.html

Categories

Resources