Error importing Node.js modules into Intern tests - node.js

I'm trying out Intern for testing our Node.js modules. I've got it set up to run an empty test and even require node modules, but when I try to require one of the modules in our package I get the error:
/path/to/app/node_modules/path/path.js:327
var path = (i >= 0) ? arguments[i] : process.cwd();
^
TypeError: undefined is not a function
at Object.exports.resolve (/path/to/app/node_modules/path/path.js:327:52)
at Object.exports.relative (/path/to/app/node_modules/path/path.js:405:20)
at getSource (/path/to/app/node_modules/intern/lib/util.js:368:21)
at formatLine (/path/to/app/node_modules/intern/lib/util.js:405:40)
at processChromeTrace (/path/to/app/node_modules/intern/lib/util.js:418:16)
at normalizeStackTrace (/path/to/app/node_modules/intern/lib/util.js:470:38)
at Object.getErrorMessage (/path/to/app/node_modules/intern/lib/util.js:597:14)
at PreExecutor._handleError (/path/to/app/node_modules/intern/lib/executors/PreExecutor.js:256:24)
at /path/to/app/node_modules/intern/node_modules/dojo/lang.js:78:32
at process.<anonymous> (/path/to/app/node_modules/intern/lib/executors/PreExecutor.js:302:6)
Folder structure is:
src/
**/*.coffee
tests
unit/**/*.coffee
intern.js
js/ (coffeescript is compiled here)
src/
**/*.js
tests/
**/*.js
all.js (compiled by rolling up the names of the other tests under /js/tests)
node_modules
Here's my intern.js:
define({
capabilities: {
'browserstack.selenium_version': '2.45.0'
},
environments: [
{browserName: 'internet explorer', version: '11', platform: 'WIN8'},
{browserName: 'internet explorer', version: '10', platform: 'WIN8'},
{browserName: 'internet explorer', version: '9', platform: 'WINDOWS'},
{browserName: 'firefox', version: '37', platform: ['WINDOWS', 'MAC']},
{browserName: 'chrome', version: '39', platform: ['WINDOWS', 'MAC']},
{browserName: 'safari', version: '8', platform: 'MAC'}
],
maxConcurrency: 2,
tunnel: 'BrowserStackTunnel',
loaderOptions: {
packages: [{name: 'app', location: 'js/src'}]
},
reporters: ['Console', 'Lcov'],
suites: ['js/tests/unit/all'],
excludeInstrumentation: /^(?:\.npm|js\/tests|src|tests|node_modules)\//
});
My test is just:
define (require) ->
registerSuite = require('intern!object')
assert = require('intern/chai!assert')
SchemaBuilder = require('intern/dojo/node!app/path/to/Module')
registerSuite
name: 'Testing'
'test': ->
From the project root I'm running './node_modules/.bin/intern-client config=tests/intern'
Is this a problem with my code, configuration, environment, or Intern?
I've tried with Node.js v0.12.0 and v0.12.7.

Interestingly, removing the path module from my app dependencies (package.json) resolved (well, avoided) the undefined is not a function error, seemingly falling back on Intern's own path resolution. I don't really know why, but this seems like a bug.
This presented a new, more tractable error: Error: Cannot find module 'app/path/to/Module', suggesting the path in the require() was simply wrong.
I think the problem is that the intern/dojo/node loader doesn't support the loaderOptions: {packages: [{name: 'app', location: 'js/src'}]} configuration, and hence it is searching for an app directory relative to the test module. If I replace app/ with ../../../../js/src/ then it resolves and works as expected.
It's a bit ugly, but it's the standard way of requiring local files in node, so it's also not too surprising, I had just hoped Intern's loader could make it cleaner.

Related

When I use electron-builder to package an NSIS program, I get: Fatal error: Unable to parse version string for FileVersion

Electron-Builder Version: 22.14.5
Node Version: v16.13.1
Electron Version: 16.0.6
Electron Type (current, beta, nightly): current
Not using electron-updater
Target: nsis
Here is the console log.
Compilation succeeded.
• electron-builder version=22.14.5 os=5.10.89-1-MANJARO
• loaded configuration file=/home/aszswaz/document/notebook/code-example/webpack-electron-vue/config/electron-builder-win.js
• Specified application directory equals to project dir — superfluous or wrong configuration appDirectory=./
• writing effective config file=dist/electron-builder/builder-effective-config.yaml
• skipped dependencies rebuild reason=npmRebuild is set to false
• packaging platform=win32 arch=x64 electron=v16.0.6 appOutDir=dist/electron-builder/win-unpacked
• asar usage is disabled — this is strongly not recommended solution=enable asar and use asarUnpack to unpack files that must be externally available
• asar usage is disabled — this is strongly not recommended solution=enable asar and use asarUnpack to unpack files that must be externally available
⨯ cannot execute cause=exit status 1
errorOut=Fatal error: Unable to parse version string for FileVersion
0024:fixme:ver:GetCurrentPackageId (0032FE94 00000000): stub
command=wine /home/aszswaz/.cache/electron-builder/winCodeSign/winCodeSign-2.6.0/rcedit-ia32.exe /home/aszswaz/document/notebook/code-example/webpack-electron-vue/dist/electron-builder/win-unpacked/hanna.exe --set-version-string FileDescription hanna --set-version-string ProductName hanna --set-version-string LegalCopyright aszswaz --set-file-version v1.0.0 --set-product-version 1.0.0.0 --set-version-string InternalName hanna --set-version-string OriginalFilename '' --set-version-string CompanyName aszswaz --set-icon /home/aszswaz/document/notebook/code-example/webpack-electron-vue/public/icon.ico
workingDir=
This is the config file used.
module.exports = {
appId: "cn.aszswaz.demo.webpack-electron-vue",
productName: "hanna",
copyright: "aszswaz",
asar: false,
files: [
"dist/app/*",
"!**/node_modules/vue/*",
"!**/node_modules/vue-router/*"
],
artifactName: "${productName}-${arch}-${version}.${ext}",
directories: {
app: "./",
output: "./dist/electron-builder"
},
win: {
target: "nsis",
icon: "public/icon.ico"
},
nsis: {
oneClick: false,
perMachine: true,
allowToChangeInstallationDirectory: true
},
npmRebuild: false,
buildVersion: "v1.0.0",
electronCompile: false,
electronDownload: {
version: "16.0.6",
platform: "win32",
arch: "x64",
cache: process.cwd() + "/cache"
},
electronVersion: "v16.0.6"
}
What is the reason for this error? How can I fix this error?

How to: 1 Webpack for all project with importing lib from node_modules

// Project Tree View: My idea about using Webpack.
+ Toolkit:
- D:/Toolkit/Webpack/webpack.config.js
+ Project:
- D:/Project/A/build/index.ts
- D:/Project/B/build/index.ts
- D:/Project/C/build/index.ts
// Toolkit: [webpack.config.js] file
const path = require('path');
module.exports = (env) => {
let project_root = env.path;
console.log(env);
console.log(__dirname);
return {
mode: env.mode,
entry: project_root+'/build/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [
path.resolve(project_root, 'build'),
path.resolve('./node_modules'),
]
}, {
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
}
]
},
output: {
publicPath: 'public',
filename: 'script.js',
path: path.resolve(project_root, 'assets/js')
},
resolve: {
modules: ['node_modules'],
},
}
}
Build command: yarn build --env=path=D:/Project/C
The command works without error, but when importing any library from the node_modules
Ex:
import {lib} from "example_lib";
import {lib} from "~example_lib";
import {lib} from "#example_lib";
import {lib} from "node_modules/example_lib";
import {lib} from "./node_modules/example_lib";
The Error
ERROR in ../A/build/index.ts 1:0-52
Module not found: Error: Can't resolve 'example_lib' in 'D:\Project\A'
resolve 'example_lib' in 'D:\Project\A'
Parsed request is a module
No description file found in D:\Project\A\build or above
resolve as module
D:\Project\A\build\node_modules doesn't exist or is not a directory
...
D:\node_modules doesn't exist or is not a directory
ERROR in D:\Project\A\build\index.ts
../A/build/index.ts 1:20-49
[tsl] ERROR in D:\Project\A\build\index.ts(1,21)
TS2792: Cannot find module 'example_lib'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?
webpack 5.26.2 compiled with 2 errors in 1939 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The Question is:
How to use ONLY 1 Webpack node_modules for all projects ?
Gulp can resolve this issue but how about Webpack ?
I do not want every project to have 1 node_modules or webpack, package,... inside (it trash my PC !)
The issue has been resolved !
The above code is correct.
Format ".js" works normally; however ".ts" need to add // #ts-ignore above every import external node_modules.
This is the answer !
// #ts-ignore
import {lib} from "example_lib";
NOTE: 7 days researching Webpack
This is my opinions:
Gulp is much more than Webpack even it has lower user
These are the Pros about Gulp that Webpack should have !
Less time for controlling the core.
User-friendly.
Clear and Clean Structure, less bracket.
Easy and Flexible for creating the custom config.
Easy to use, develop through time.
Not just for web field, on the backup data, auto,... as well.
1 node_modules for all external projects (Gulp less bug and coding line than Webpack).
Compile time are the same.
👉🏾 Gulp is the King 👑 !

Unable to implement webpack in project with node-red

I am trying to implement webpack in my project which contains node-red. However, I keep getting the following warning. Please suggest how to solve this error -
WARNING in ./node_modules/node-red/red/runtime/storage/localfilesystem/projects/git/node-red-ask-pass.sh 1:26
Module parse failed: Unexpected token (1:26)
You may need an appropriate loader to handle this file type.
> "$NODE_RED_GIT_NODE_PATH" "$NODE_RED_GIT_ASKPASS_PATH" "$NODE_RED_GIT_SOCK_PATH" $#
|
# ./node_modules/node-red/red/runtime/storage sync ^\.\/.*$ ./localfilesystem/projects/git/node-red-ask-pass.sh
# ./node_modules/node-red/red/runtime/storage/index.js
# ./node_modules/node-red/red/runtime/index.js
# ./app.js
My webpack.config.js is -
const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()],
entry: './app.js',
output: {
path: path.resolve(__dirname, './output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js','.json', '.sh'],
modules: [
'node_modules'
],
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
}
]
}
};
For Webpack, every file is a .js. In order to handle other extensions, like .css or .sh, you're supposed to use a loader, like you did with css-loader, that will tranform CSS rules into JS.
The issue you're facing is that you've got an import chain (./app.js -> .../index.js -> .../index.js -> .../node-red-ask-pass.sh), so Webpack will, at some point, will import a .sh file, but will throw an error because shell code is obviousouly invalid JavaScript. that is why you're seeing the error that you have.
By the way, I couldn't reproduce the issue you're facing:
npm init -y
npm i node-red
# ./node_modules/node-red/red is not a directory
So it was probably a node-red bug. Update the package to the latest version.

Loading dependencies outside of the Intern directory when running tests through Selenium

I have a project where Intern unit tests are supposed to be in a different directory tree than the source code under test. Somewhat like this:
projectRoot
projectRoot/src
projectRoot/tests
projectRoot/tests/intern.js
projectRoot/tests/node_modules/intern
projectRoot/tests/MyTestSuite.js
In the Intern configuration file, I define an AMD package that uses relative paths with ../ to reach src from the unit test suites. Here's an example configuration:
define({
environments: [ { browserName: 'chrome', platform: 'WINDOWS' }],
webdriver: { host: 'localhost', port: 4444 },
useSauceConnect: false,
loader: {
packages: [
{ name: 'testSuites', location: '.' },
{ name: 'externalDep', location: '../src' }
]
},
suites: [ 'testSuites/MyTestSuite' ]
});
And a matching unit test suite
define([ "intern!tdd", "intern/chai!assert","externalDep/ExternalDep"],
function(tdd, assert, ExternalDep) {
tdd.suite("Suite that has external dependency", function() {
tdd.test("Test if external dependency is loaded correctly", function() {
assert(ExternalDep === "hello");
});
});
}
);
This works fine when tested directly in the browser (client.html) or node (client.js). When fired off through a Selenium Server (with runner.js), however, the client.html running in the browser started by Selenium can't find the external dependencies. In the above example, it tries to request ExternalDep at http://localhost:9000/__intern/src/ExternalDep.js, which is a 404 because the src directory is not within intern.
I suppose that if I put intern.js at the highest common super-directory of both the tests and the source code, it would work. But our project is currently set up in a way which makes that impractical. Is there a way for configuring sources that live beyond the location of the Intern config file, or did I just make a silly mistake?
Thanks!
There is no problem putting the tests in a different directory from the rest of the code, but projectRoot needs to be the working directory from which you start the runner, and you need to change your loader configuration to match.
So, instead of right now where you are starting Intern from projectRoot/tests like this:
…/projectRoot/tests$ ./.bin/intern-runner config=intern
you need to start it from projectRoot:
…/projectRoot$ ./tests/.bin/intern-runner config=tests/intern
…and change your loader configuration:
loader: {
packages: [
{ name: 'testSuites', location: 'tests' },
{ name: 'externalDep', location: 'src' }
]
},

E2E Testing Angular with Karma - ng-scenario 'Module is not defined'

I've been trying to run some e2e tests with Karma.
It's not working for me at all.
Right now I'm getting the following error:
Firefox 28.0.0 (Windows 7) ERROR
ReferenceError: module is not defined
at C:/MYPATH/Test/node_modules/karma-ng-scenario/lib/ind
ex.js:12
Firefox 28.0.0 (Windows 7) ERROR
ReferenceError: browser is not defined
at C:/MYPATH/Test/e2e/scenarios.js:12
My config file looks like this:
module.exports = function(config){
config.set({
basePath : './',
frameworks: ['ng-scenario'],
files : [
'./node_modules/karma-ng-scenario/lib/*.js',
'./e2e/*.js'
],
autoWatch : true,
singleRun : true,
browsers : ['Firefox'],
plugins : [
'karma-ng-scenario',
'karma-chrome-launcher',
'karma-firefox-launcher'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
},
urlRoot : '/__karma/',
proxies : {
'/public/' : 'http://localhost:8080'
}
});
};
My scenarios file just tests to see if the base path redirects.
I've already done a lot of messing with npm to get to this point, most recently "npm install karma-ng-scenario --save-dev" but no luck unfortunately.
In files[] specify path to angular.js as a very first, then any other angular modules you use (angular-mocks.js, angular-resource.js, angular-cookies.js), then any library you use, then your own code.
In files:[...] array you have to specify all the files that contain the actual code to which you are writing tests, if your module is using other modules, then you should add files of all the modules on which your module depends.
suppose you are testing 'someModule' module you have to include the 'someModule' controllers, views, services, directives and other modules if your module depends on them
Note: Assuming your files are in their specific directories
files: [
... //angularjs, angular-mocks, karma, protractor and other files you need
...
'scripts/someModule/controllers/*.js',
'scripts/someModule/services/*.js',
'scripts/someModule/directives/*.js',
'views/someModule/*.html'
]
or simply
files: [
... //angularjs, angular-mocks, karma, protractor and other files you need
...
'scripts/someModule/**/*.js',
'views/someModule/*.html'
]
And make sure to install and include all the testing libraries you depend on (i.e, angularjs, angular-mocks, protrator, karma etc) in the files array
So the configuration I finally got my E2E tests to work with was this:
// Karma configuration
// Generated on Fri Apr 11 2014 02:35:20 GMT+0800 (China Standard Time)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '..',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.js',
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
//browsers: ['PhantomJS', 'Firefox', 'Chrome'],
browsers: ['Firefox', 'Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
proxies : {
"/": "http://localhost:8080"
},
urlRoot : "/__karma/"
});
};
It seems that a better solution for running end to end tests is to use protractor. NG-SCENARIO is depreciated and will cause warnings but this should still run. https://github.com/angular/protractor

Resources