intern.js How to test legacy non modular code - testing

I'm using intern.js as a test framework to test dojo modules and it works well.
Now I have to test some non modular legacy code but I can't.
This is an example of a simple file to test:
var Component = function() {
this.itWorks = function() {
return true;
}
};
And this is the test
define([
'intern!object',
'intern/chai!assert',
'intern/order!controls/component',
], function (registerSuite, assert) {
registerSuite({
name: 'test legacy code',
'simple test': function () {
console.log(Component);
}
});
});
The test fails sayng that "Component is not defined".
I've notice that it works only if I write
window.Component = Component
At the bottom of file to test.
I can't modify all the file to test, is it possible to test the file in a different way?

This should work fine. One possible issue is where you're loading component from. The 'controls/component' dependency in 'intern/order!controls/component' is, barring any special loader config, relative to the file doing the loading. That means that if the project is setup like this:
project/
controls/
component.js
tests/
intern.js
componentTest.js
and component is being loaded from componentTest.js, then the dependency should be 'intern/order!../controls/component.js'. (It will actually work without the '../' in this case since controls is a top level directory in the project.)
Another potential issue is that a non-AMD identifier should use the .js suffix. This tells the loader that the thing being loaded is a generic script rather than an AMD module.
Also note that the order plugin is only needed to load multiple legacy files in a specific order. If order doesn't matter, or you're just loading one script, you can just use the script itself '../controls/component.js' as the dependency.

<"/"https://stackoverflow.com/tags" term="legacy" /">
<"/!-- begin snippet: js hide: false console: true babel: false --"/">
"var Component" = function() {
"this.itWorks" = function() {
return=true;
}
};
<"/"!-- end snippet --"/">

Related

requirejs loading file from different path

I've a webpage , where I've included the requirejs via script tag like -
<script data-main="/media/course-book-app/courses.require.main.js" src="/media/common/vendor/requirejs/require.js"></script>
On Safari browser, I'm getting error like -
What is causing this issue?
This issue is very frequent on Safari but on chrome it is less frequent.
Testing URL
From https://requirejs.org/docs/errors.html#scripterror (which is linked right there in the error). Follow the instructions and look at the script that caused the error
This occurs when the script.onerror function is triggered in a
browser. This usually means there is a JavaScript syntax error or
other execution problem running the script. To fix it, examine the
script that generated the error in a script debugger.
This error may not show up in IE, just other browsers, and instead, in
IE you may see the No define call for ... error when you see "Script
error". This is due to IE's quirks in detecting script errors.
Here is the way to use requirejs correctly. This ensures the configuration gets loaded before loading any module -
define('requireconfig', function(){
require.config({
paths: {
"jquery": "/common/vendor/jquery/jquery-1.9.1.min",
"backbone": "/common/vendor/backbone/backbone.min-1.1.2",
"underscore": mediaPath + "/common/vendor/underscore/underscore.min-1.7.0"
},
shim: {
backbone : {
deps: ["jquery","underscore"],
exports: "Backbone"
},
}
});
});
define('main', ['requireconfig'], function () {
'use strict';
});
// loading main module which loads the requirejs configuration
requirejs(['main'],()=>{
requirejs(['jquery'], ($)=>{//jquery loaded});
}, ()=>{//error loading module})

Aurelia library js file in Bundle but is resolved as static file

My project structure is as follows:
src
..lib
....someLibrary.js
bundles.js:
"bundles": {
"dist/app-build": {
"includes": [
"[**/*.js]",
"**/*.html!text",
"**/*.css!text"
],
"options": {
"sourceMaps": 'inline'
"inject": true,
"minify": true,
"depCache": true,
"rev": true
}
},
The project builds fine, but when I check app-build.js I don't find a definition for lib/someLibrary.js. I am using typescript for my own project so I assume this has something to do with that, how can I mix regular js files and output from my transpiled TS files into the same app-build bundle?
Update
So I tried to split the 'build-system' gulp task into two tasks: 'build-typescript' which is the same as 'build-system' was before, then I created 'build-libs' which looks like so:
gulp.task('build-libs', function() {
return gulp.src(paths.root + '**/*.js')
.pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
.pipe(changed(paths.output, {extension: '.js'}))
.pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '/src' }).on('error', gutil.log))
.pipe(gulp.dest(paths.output));
});
I then added to my dist/app-build bundle config: "lib/someLibrary.min.js"
And now my app-build.js does have the library defined, however when I try to use the library in one of my views using:
<require from="lib/someLibrary.min.js">
I get an error:
Failed to load resource: the server responded with a status of 404 (Static File '/dist/lib/someLibrary.min.html' not found)
What?!?? Why is it looking for html when nowhere is html ever involved in this whole scenario? Why is something that should be easy this hard?
Update2
So apparently 'require' does not work with javascript files. I changed to use the 'script' tag, however it seems these get stripped out when rendered by Aurelia. I am at a loss as to how to get Aurelia to do what I want it to.
Ok so after much frustration and disbelief at how hard something so simple could be, in addition to the changes to the build tasks mentioned above (which includes the javascript library file that has no npm/jspm package into the app-bundle) I created a modified version of this solution which looks as follows:
import { bindable, bindingMode, customElement, noView } from 'aurelia-framework';
#noView()
#customElement('scriptinjector')
export class ScriptInjector {
#bindable public url;
#bindable public isLocal;
#bindable public isAsync;
#bindable({ defaultBindingMode: bindingMode.oneWay }) protected scripttag;
public attached() {
if (this.url) {
this.scripttag = document.createElement('script');
if (this.isAsync) {
this.scripttag.async = true;
}
if (this.isLocal) {
const code = 'System.import(\'' + this.url + '\').then(null, console.error.bind(console));';
this.scripttag.text = code;
} else {
this.scripttag.setAttribute('src', this.url);
}
document.body.appendChild(this.scripttag);
}
}
public detached() {
if (this.scripttag) {
this.scripttag.remove();
}
}
}
To use it, simply add the following tag to the view where you want the script library to be used as follows:
<scriptinjector url="lib/bootstrap-toc.js" is-local.bind='true'></scriptinjector>
This will keep the original scriptinjector functionality which allows you to add remote 3rd party libraries to your Aurelia app but it will also allow you to load any local 3rd party libraries that you have bundled with your app.
Hope this helps someone.

Sencha Touch [APPNAME].app is undefined only when testing with Jasmine

I'm trying to set up some test cases for a view using the Jasmine 2.3.4 assertion library for my Sencha Touch 2.4 app. Things seem great (I see the view rendered to a div) except the browser does not know what MyApp.app is. I have this line at my onContainerInitialize function from my view/container code:
var controller = MyApp.app.getController('loginController');
which gives this Jasmine error:
TypeError: Cannot read property 'getController' of undefined
At the time the Jasmine tests are called, from my console I do have a MyApp global object with the following structure (attached). If you expand app you will see the class name of the controller listed in an array under _controllers. The line that causes this error in my spec file is:
var myView = new MyApp.view.someViewName({ renderTo: 'test' });
I modeled my setup after a few tutorials, one of which is Sencha's https://docs.sencha.com/extjs/4.2.5/#!/guide/testing
(wish there was one for a recent version of Touch). I think my problem may be related to this note midway down that page:
Note: this Application definition is not a copy and paste of your
regular Application definition in your app.js. This version will only
include the controllers, stores, models, etc and when launch is called
it will invoke the Jasmine tests.
It may be related, but I also couldn't follow their:
ctrl = newMyApp.controller.MyController();
where I would get this error:
TypeError: app.getRouter is not a function at Ext.define.applyRoutes (http://localhost:8080/touch/sencha-t...ug.js:45800:26)
Instead, I had to add in this argument like this:
var ctrl = new Kaacoo.controller.loginController({ application : app });
Additionally, my launch file is set up like this:
Ext.require('Ext.app.Application');
Ext.Loader.setConfig({
enabled: true,
disableCaching: true
});
Ext.Loader.setPath('MyApp', '../../app');
// this file is a couple levels deep from the root of my project
Ext.application({
name : 'MyApp',
extend: 'MyApp.Application',
autoCreateViewport: true,
controllers: [
'loginController'
],
requires : [
],
launch: function() {
// Jasmine is bootstrapped with boot.js referenced in the html runner, so nothing here. My test specs are being called after this launch function is executed.
}
});
The order I have listed my resources in my html runner are: Jasmine Library with boot.js> Touch All Debug Library > Project Source Files > Spec Files > Launch file
Building and simulating the app is fine, so why can't I also have access to MyApp.app.getController('loginController') as well in my test environment?
Thanks!

Including dojo/dom library to Spring Roo

How is it possible to include and use the dojo/dom library in Spring roo.
This:
<script type="text/javascript">
dojo.require('dojo/dom');
dojo.ready(function remAttr(){
dojo.removeAttr('theId', 'value');
}
);
</script>
results in:
"NetworkError: 404 Introuvable - http://localhost:8131/suivitrc/resources/dojo/dom.js"
dom.js
Could not load 'dojo/dom'; last tried '../dojo/dom.js'
Can anyone please help?
I think the version of dojo in roo is currently less than 1.7. This means you can remove the following line from your code because the remoteAttr function is part of dojo.js:
dojo.require('dojo/dom');
see here: http://dojotoolkit.org/reference-guide/1.7/dojo/removeAttr.html
The namespace => to module path is retreived by replacing periods (.), in short - you need to replace the slash with a dot. Your require should be
dojo.require('dojo.dom'); // blocking call? djConfig.async must be false
Since the error is in regards to the dojo.require specified path, this means your dojo.js is found and loaded (dojo.require is not undefined) - and baseUrl is not of concern to dojo modules.
The thing is, youre using the legacy loader to pull in an AMD module, in 1.7+ the require statement has a different look to it.
// AMD loader form is
function callbackFunctionOnComplete(dojoDom) { }
require([ "dojo/dom" ], callbackFunctionOnComplete); // non-blocking
So, how dojo.require works is following, assume that the parameter we pass as string is called 'module;
dojo.require = function(module) {
var parts = module.split('.');
1 - get toplevel namespace (global)
var packageName = parts.shift(); // first part is the package name
2 - get the filename (minus .js)
var id = parts.pop(); // the last bit
3 - translate everything in between to a path (relative to packagelocation)
var mid = parts.join("/");
4 - lookup package (from toplevel) location
var fullpath = // in pseudo
foreach dojoconfig.packages
iff obj.name == packageName
set to obj.location
5 append the rest and start downloading module
fullpath += mid + id + '.js'
transport.get(..... fullpath .....)
You need to configure dojo with dojo config. I prefer the form explained here:
http://dojotoolkit.org/reference-guide/1.7/dojo/_base/config.html#explicitly-creating-a-dojoconfig-object-before-including-the-dojo-core.
And you need to tell dojo where to find its stuff. An example:
var dojoConfig =
{
baseUrl : "/yourApp/js", // defines the js folder in your webapp
tlmSiblingOfDojo: false,
async: true,
parseOnLoad:true,
packages: [
{ name: "app", location: "app"}, // where it is in the js folder
{ name: "dojo", location: "lib/dojo" }, // where it is in the js folder
{ name: "dijit", location: "lib/dijit" },
{ name: "dojox", location: "lib/dojox" }
]
};
Also the require form you are using is deprecated. See http://livedocs.dojotoolkit.org/dojo/require

Problems interning strings for custom Dojo build

Trying to figure out why I can't seem to intern strings in my dojo build. My layer files get created correctly, but the code associated with each of the individual dijits doesn't get interned properly.
Here is a piece of portion of the build output that illustrates where it is failing:
release: Interning strings for : ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js
release: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/templates/commenting.htm
release: Optimizing (shrinksafe, stripConsole=normal) file: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js
release: Could not strip comments for file: ../../release/fwijits5.31.2012/content/fwijits/optionalDijits/commenting.js,
error: InternalError: illegal character
It looks like the optimize fails because the template doesn't get added to the js file properly. Here is what the js looks like after the html gets interned. You can't tell from the output, but a byunch of special characters get tacked on at the end of the javascript.
if(!dojo._hasResource["fwijits.optionalDijits.commenting"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["fwijits.optionalDijits.commenting"] = true;
dojo.provide("fwijits.optionalDijits.commenting");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
//The main widget that gets returned to the browser
dojo.declare("fwijits.optionalDijits.commenting", [dijit.layout.ContentPane, dijit._Templated], {
widgetsInTemplate: true,
_earlyTemplatedStartup: true,
templateString: dojo.cache("fwijits.optionalDijits", "templates/commenting.htm"),
basePath: dojo.moduleUrl("fwijits.optionalDijits"),
//This function contains all configurable parameters
constructor: function(params){
params = params ||{};
this.inherited(arguments);
},
//This functions run on a "startup" call
startup: function(){
var _this = this;
this.inherited(arguments);
},
_addPointComment:function(){
console.debug("button clicked");
}
});
}
The htm file is pretty simple, so I don't think it's the root of my problem.
<div dojoAttachPoint="containerNode">
<div dojoattachpoint="_outerDiv">
<div dojoattachpoint="_addPoint" dojotype="dijit.form.Button" dojoattachevent="onClick:_addPointComment"><b>Add Comment</b></div>
</div>
</div>
Any suggestions?
Which version of Dojo? There is a bug in the build system with interning strings that do not end in HTML or HTM, although I've never tried with HTM to know for sure.
Might be worth a check. I know this was fixed in 1.7 and backported to 1.8.
https://bugs.dojotoolkit.org/ticket/15867