casperjs: how to include other javascript files during unit tests in tests themselves? - dependency-injection

I am doing some unit test in casperjs and I got stuck: how do include dependency file from the test itself? Included javascript file can be just a bunch of functions, and does not declare any interface (module.exports = ... etc).
I know I can include from the command line
$ casperjs test --include=./my-mock.js mytest.js
but how can I include files from the test itself?
Putting following on the top does not work for me... my_mock is undefined
casper.options.clientScripts = ["./my-mock.js"]; //push() does not help either
//mytest.js is below
// ------------------------------------------
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
test.assertEquals( ......);
test.done();
});
// ------------------------------------------
CasperJS version 1.1.0-DEV using phantomjs version 1.9.1

Using phantom.injectJs method is the best option I've found so far. E.g. you're having two files in your directory: "tests.js" and "settings.js". You want to include "settings.js" into "test.js". The first thing you should do with your "test.js" is write the following:
phantom.injectJs('settings.js');
casper.test.begin(...
...

The reason that clientScripts isn't working is that it is loaded on each page load, so you don't have access to the objects/functions defined in the file outside of a casper.evaluate() call.
You can use require() to pull in modules, however you may need to modify your included script to work with this method.
Here is what I changed your mytest.js to:
var my_mock = require('my-mock');
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
//test.assertEquals( ... );
test.done();
});
And this is a quick script (my-mock.js) that I threw together to print out when you use the functions you provided.
module.exports = {
setFetchedData: function(a) {
console.log('setFetchedData: ' + a);
},
doRequest: function() {
console.log('doRequest');
}
};

I found useful this sample demonstrating --includes option:
$ casperjs test tests/ --pre=pre.js --includes=inc.js --post=post.js
to load functions that you often use in your tests.

Related

Getting going with jsbundling-rails

Trying to grok how to work with js files in Rails 7 using the jsbundling-rails gem and ES modules...
In short, I want to code up functions and have them available in the page.
Here's a simple example. Working with app/javascript/controllers/application.js....
If I paste
alert("HI");
I get an alert in the browser so I know I'm in the right file.
Now, if I paste a simple function
function hello() {
alert("hello");
}
That function does not appear in the compiled js file.
I've tried including the export keyword in front of the function as well...
export function hello() {
alert("hello");
}
I don't know if it's the gem or the way I am writing javascript, but I'm not sure how to proceed.
window.hello = function(){
alert("hello");
}

Import my own files into the electron renderer process

This seems really dumb, but I need help for importing some source code into the renderer process in electron:
I have an electron app:
index.html (loads window.js with a tag)
- index.js
- window.js
- useful_functions.js
In window.js, I want to import some functions from useful_functions.js, so I've tried the following:
// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';
// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');
// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')
I also tried the nodeIntegration flag, but that didn't help either
Note: I'm not trying to import npm modules but my own code, in an other file right next to it.
I'm looking for examples, but I only find super small samples with just the basic files. (Or huge apps like atom that would take me a while to figure out)
I don't have webpack setup for this project yet, but I'm sure there is a simpler way to do this very basic task...
Thanks for any help.
In index.html, use require() instead of loading window.js with a tag, i.e., replace:
<script src="window.js"></script>
with:
<script>require('./window.js');</script>
Then, in window.js, the following statement should work too:
const { very_useful } = require('./useful_functions.js');
Note that nodeIntegration: true is needed in the options passed to new BrowserWindow() anyway:
webPreferences:
{
nodeIntegration: true
}
See:
Node Modules
Functions and objects are added to the root of a module by
specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is
wrapped in a function by Node.js (see module wrapper).
Module Wrapper
Before a module's code is executed, Node.js will wrap it with a
function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

How can I interop with existing JS objects?

I'm trying to write Dart code that will generate a rough equivalent of this:
var disposable = vscode['commands'].registerCommand(
'extension.sayHello',
function () {
vscode['window'].showInformationMessage('Hello World!');
}
);
context.subscriptions.push(disposable);
The variables vscode and context are both globals available in the JavaScript which is executing my Dart (which is being compiled to JS with the Dart Dev Compiler).
I'm happy for context/vscode to be completely untyped for now, but I'm struggling to bend the JS package to output code like this (eg. if I put #JS() on a stub vscode, I get dart.global.vscode).
You can use the base dart:js features
Note that context happens to be dart's name for the javascript context.
var disposable = context['vscode']['commands'].callMethod('registerCommand', [
'extension.sayHello',
() {
context['vscode']['window'].callMethod('showInformationMessage', ['Hello World!']);
}]);
);
context['context']['subscriptions'].callMethod('push', [disposable]);
Let me put together a quick example on github with package:js.
Edit: OK, here you go:
https://github.com/matanlurey/js-interop-examples
It took me a couple tries to the package:js syntax correct (we probably need more documentation here and examples), but I ended up creating a "fake" visual studio code API (vscode.js), and interoping with it fine.
Watch out that you need to wrap your functions with allowInterop if you expect your examples to work in Dartium.

Karma + Rails: File structure?

When using the karma javascript test library (née Testacular) together with Rails, where should test files and mocked data go be placed?
It seems weird to have them in /assets/ because we don’t actually want to serve them to users. (But I guess if they are simply never precompiled, then that’s not an actual problem, right?)
Via this post: https://groups.google.com/forum/#!topic/angular/Mg8YjKWbEJ8
I'm experimenting with something that looks like this:
// list of files / patterns to load in the browser
files: [
'http://localhost:3000/assets/application.js',
'spec/javascripts/*_spec.coffee',
{
pattern: 'app/assets/javascripts/*.{js,coffee}',
watched: true,
included: false,
served: false
}
],
It watches app js files, but doesn't include them or serve them, instead including the application.js served by rails and sprockets.
I've also been fiddling with https://github.com/lucaong/sprockets-chain , but haven't found a way to use requirejs to include js files from within gems (such as jquery-rails or angularjs-rails).
We ended up putting tests and mocked data under the Rails app’s spec folder and configuring Karma to import them as well as our tested code from app/assets.
Works for us. Other thoughts are welcome.
Our config/karma.conf.js file:
basePath = '../';
files = [
JASMINE,
JASMINE_ADAPTER,
//libs
'vendor/assets/javascripts/angular/angular.js',
'vendor/assets/javascripts/angular/angular-*.js',
'vendor/assets/javascripts/jquery-1.9.1.min.js',
'vendor/assets/javascripts/underscore-min.js',
'vendor/assets/javascripts/angular-strap/angular-strap.min.js',
'vendor/assets/javascripts/angular-ui/angular-ui.js',
'vendor/assets/javascripts/angular-bootstrap/ui-bootstrap-0.2.0.min.js',
//our app!
'app/assets/javascripts/<our-mini-app>/**',
// and our tests
'spec/javascripts/<our-mini-app>/lib/angular/angular-mocks.js',
'spec/javascripts/<our-mini-app>/unit/*.coffee',
// mocked data
'spec/javascripts/<our-mini-app>/mocked-data/<data-file>.js.coffee',
];
autoWatch = true;
browsers = 'PhantomJS'.split(' ')
preprocessors = {
'**/*.coffee': 'coffee'
}
I found this project helpful as a starting point. https://github.com/monterail/rails-angular-karma-example. It is explained by the authors on their blog.
It's an example rails app with angular.js and karma test runner.

How should I move or delete files in a Yeoman Generator?

I'm building a generator that in part includes scaffolding from another project created with exec. Depending on user input I need to move or delete parts of this scaffolding.
Right now I'm doing it with node's fs.child_process.spawn and shelljs, but seeing as the Yo generator has mkdir, write, template, and copy, I'm wondering if there's a Yo way to move or delete files and directories.
I just use rimraf like this:
MyGenerator.prototype.removeDir = function removeDir () {
var cb = this.async(),
self = this;
rimraf('path/to/dir', function () {
self.log.info('Removing dir');
cb();
});
};
Remember to add rimraf as a dependency in your package.json file. Not sure if there's a built-in function for this but this one's been working fine for me so far.
Yeoman now supports this via the fs API, which is an in memory filesystem implementation.
this.fs.move('source/file', 'dest/file');
this.fs.copy('source', 'dest');
File System Docs
Still not documented, but this is the delete method (works for me):
this.fs.delete('file/to/delete');
Link: Yeoman issue 1505

Resources