Can't get Intern to run Node.js Module - intern

I am trying to test Intern to see if it would be a good fit for a testing framework. I am trying to test the following code in Intern.
var HelloWorld;
HelloWorld = (function () {
function HelloWorld (name) {
this.name = name || "N/A";
}
HelloWorld.prototype.printHello = function() {
console.log('Hello, ' + this.name);
};
HelloWorld.prototype.changeName = function(name) {
if (name === null || name === undefined) {
throw new Error('Name is required');
}
this.name = name;
};
return HelloWorld;
})();
exports = module.exports = HelloWorld;
The file is located in 'js-test-projects/node/lib/HelloWorld.js' and Intern is located at 'js-test-projects/intern'. I am using the 1.0.0 branch of Intern. Whenever I try to include the file and run the test I don't get any output after "Defaulting to console reporter". Here is the test file.
define([
'intern!tdd',
'intern/chai!assert',
'dojo/node!../lib/HelloWorld'
], function (tdd, assert, HelloWorld) {
console.log(HelloWorld);
});

1. Assuming the following directory structure (based on the question):
js-test-projects/
node/
lib/
HelloWorld.js - `HelloWorld` Node module
tests/
HelloWorld.js - Tests for `HelloWorld`
intern.js - Intern configuration file
intern/
2. Your Intern configuration file should contain info on the node package and any suites to run:
// ...
// Configuration options for the module loader
loader: {
// Packages that should be registered with the loader in each testing environment
packages: [ 'node' ]
},
// Non-functional test suite(s) to run
suites: [ 'node/tests/HelloWorld' ]
// ...
3. Your test file should load HelloWorld using Intern's version of Dojo, like this:
define([
'intern!tdd',
'intern/chai!assert',
'intern/dojo/node!./node/lib/HelloWorld.js'
], function (tdd, assert, HelloWorld) {
console.log(HelloWorld);
});
Note: You don't have to use Intern's version of Dojo to load the HelloWorld node module in this AMD test, it is just a convenient way to do so. If you have some other AMD plugin that node-requires a node module, that's perfectly fine.
4. Finally, to run the tests in a Node.js environment, use Intern's client.js node runner by issuing the following command from within the intern directory:
node client.js config=node/tests/intern

Related

How do I configure Intern 4 to use RequireJS?

I've got RequireJS installed in my node_modules directory, and my intern.json file has:
"node": {
"loader": "requirejs"
},
However, when I run "npx intern", it fails with:
Error: Loader script requirejs did not register a loader callback
at
at
Is there a way to get Intern 4 to use RequireJS?
To use a particular loader, Intern needs a 'loader' script that will actually initialize the loader and handle loading modules with it. Intern includes loader scripts for several loaders, such as Dojo 1, Dojo, and SystemJS. It doesn't include a loader script for RequireJS, but you can add one fairly easily.
A simple script for RequireJS would look like:
// your_project/reqjs.js
intern.registerLoader(function(options) {
function initLoader(requirejs) {
// Configure requireJS -- use options passed in through the intern.json
// config, and add anything else
requirejs.config(options);
// This is the function Intern will actually call to load modules
return function(modules) {
return new Promise(function(resolve, reject) {
requirejs(modules, function() {
resolve();
}, function(error) {
reject(error);
});
});
};
};
if (typeof window !== 'undefined') {
return intern
.loadScript('node_modules/requirejs/require.js')
.then(function() {
return initLoader(window.requirejs);
});
} else {
return initLoader(require('requirejs'));
}
});
Note that Intern doesn't use loaders to actually retrieve modules for its own use (which is why the resolve call above doesn't include the loaded modules), it only uses them to load test suites. The suites themselves may use the loader normally.
You would use the script in your config with
"node": {
"loader": "./reqjs.js"
}

node + requirejs: module is not defined

Getting a module is not defined error attempting to import a module from the local project. Using node and requirejs -
Error: Evaluating /Users/Projects/stash/NODE/project_js/src/foo.js as module "foo" failed with error: ReferenceError: module is not defined
Code looks like -
(function() {
const requirejs = require('requirejs')
requirejs.config({
baseUrl: __dirname,
nodeRequire:require
});
//var foo = requirejs('foo.js');
requirejs(['foo'], function() {
foo().then(data => {
data.foreach(function(item, index, data) {
console.log(JSON.stringify(item))
})
});
})
})();
The module has the following export -
module.exports = function foo() {
.
.
.
return results
}
I've tried loading the module synchronously as well.
Check this part of their doc: if the module to be loaded (foo here) is found by RequireJS (i.e. its configuration allows it to find the module), then this module has to be declared using define instead of Node's exports.
I just tried this, which works:
directory structure
test/
index.js
foo.js
index.js
(function() {
const requirejs = require('requirejs');
requirejs.config({
baseUrl: __dirname,
nodeRequire:require
});
requirejs(['foo'], (foo) => {
console.log('loaded!', foo, foo());
});
})();
foo.js (that's the interesting part)
define(function() {
return function foo() {
return 'fooResult';
}
});
Using module.exports = ... gave me the error you have.
However this RequireJS API is not "loadable" by Node's built-in require, hence the need for a precise configuration that reflects a clear separation between Node-required modules (CommonJS API) and RequireJS-defined modules (AMD API). (Actually you can check the whole "Why AMD?" page, that should help a lot for your work with RequireJS.)

Gulp + Browserify + TypeScript To Browser

My problem is the following:
I use gulp+browserify to compile my TypeScript to JavaScript that you can use on normal HTML pages, the problem is that my class is never available on the browser:
VM633:1 Uncaught ReferenceError: Test is not defined
at <anonymous>:1:13
This is my TypeScript File:
class Test {
public test(): void {
console.log("aa");
}
}
This is my gulpfile
var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
gulp.task("default", function () {
return browserify({
//basedir: '.',
debug: true,
entries: ['app/Resources/typescript/Test.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest("web/bundles/framework/js"));
});
The file compiles without problem, and is included in my index.html (the compiled js file).
But when i try:
var t = new Test();
I get the following error:
VM633:1 Uncaught ReferenceError: Test is not defined
at <anonymous>:1:13
I can't resolve it, I have read a lot and I haven't found anything clear, I tried all and nothing worked.
There are a few things missing here:
If you want your class to be accessible outside of your module, you have to export it:
export class Test {
// ...
}
Browserify creates functions on top of the classes you define. So it won't be accessible globally (which is a good thing). Normally you would import it in another file and use it:
// in any TS file that wants to use `Test` class. Make sure this is included in the gulp entries as well
import {Test} from "test";
var t = new Test();
console.log(t);
Or if really want it to be accessible globally, you can attach it to window object:
// In Test.ts file:
(window as any).Test = Test; // This can be useful when debuging. But don't do this in production code.

Execute webpack compiled bundle in NodeJS

I want to implement server-side rendering for my ReactJS app. I use react-router. I take routes.js as webpack entry point and compile with output.libraryTarget = "commonjs2" option. Then I require the result of compilation in NodeJS script to make rendering. But I've got en error.
Webpack wrap modules in following code:
/* 277 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer, global) {
if (global.foo) {
/* ... */
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(277).Buffer, (function() { return this; }())))
/***/ }
When NodeJS tries to execute (function() { return this; }()) its return undefined. In browser it will return window. Why webpack use such wrap code? How to make this code works in NodeJS?
I use node-clone as external lib. It don't use any other libs as dependency. But webpack in its bundle makes buffer as a dependency for this lib. And inside the buffer code I've got en error Cannot read property 'TYPED_ARRAY_SUPPORT' of undefined. It happens because in nodeJS (function() { return this; }()) return undefined.
By default, webpack will package things up for browsers. If you want to build Node libraries with webpack, you need to specifiy a target in your configuration:
module.exports = {
// ...
target: 'node',
};

Calling Chai plugin in Intern returns error

I was trying to use the sinon-chai plugin within Intern but it gave me:
Error {stack: (...), message: "Cannot find the Node.js require"}
I had installed the plugin via npm and here's my test file:
define([
'intern!bdd',
'intern/chai!expect',
'app/functions',
'intern/chai',
'intern/dojo/node!sinon-chai'
], function (bdd, expect, myapp, chai, sinonChai) {
chai.use(sinonChai);
...
});
What might go wrong?
The node loader requires Node.js, so it can't be used in the browser. You'll need to load the sinon-chai library directly, as shown below (assuming the relative path from your test to node_modules is ../node_modules):
define([
'intern!bdd',
'intern/chai!expect',
'app/functions',
'intern/chai',
'../node_modules/sinon-chai/lib/sinon-chai'
], function (bdd, expect, myapp, chai, sinonChai) {
chai.use(sinonChai);
...
});
You could simplify the test include by defining a sinon-chai package in your intern config:
...
loader: {
{ name: 'sinon-chai', location: 'node_modules/sinon-chai/lib' },
...
}
...
Then you could get by with just:
define([
...
'sinon-chai/sinon-chai'
], function (bed, expect, myapp, chai, sinonChai) {
...
});

Resources