Karma preprocessor not running - karma-runner

My karma.conf.js includes:
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'../../mypath/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
(I've tried without specifying any plugins, too.)
My devDependencies include:
"karma-ng-html2js-preprocessor": "^0.2.0"`
My tests include:
beforeEach(module('templates'));
These give the error:
Module 'templates' is not available!
Running karma with --log-level debug, I do not see any [preprocessor.html2js] entries. (I do get Loading plugin karma-ng-html2js-preprocessor.)
What am I doing wrong?

The issues were that the templates must be listed under files as well, and that the glob pattern in preprocessors must match. This is implied by the documentation.
files: [
'../../Scripts/angular-app/directives/*.html',
// .js files
],
preprocessors: {
'../../Scripts/angular-app/**/*.html': ['ng-html2js']
},
Note that **/*.html does not match parent directories of the basePath.
karma start --log-level debug will display DEBUG [preprocessor.html2js] entries when everything is correct.
I was also able to remove the plugins section.
To get the correct cache ID, I used:
ngHtml2JsPreprocessor: {
// Load this module in your tests of directives that have a templateUrl.
moduleName: 'templates',
cacheIdFromPath: function (filepath) {
return filepath.substring(filepath.indexOf('/Scripts/angular-app/'));
}
},
If a template references a custom filter, the filter must be loaded in files and the filter's module must be loaded in your directive tests.

Related

url-loader without webpack?

I have a component library that will be shipping with a few small assets (images). Those assets are imported into various components in the library.
The build script uses babel (without webpack) to transpile the js(x) to a build directory, and is currently dumping the images into build/assets/images.
This works when testing the build, but when using the component in another project (using webpack) the component tries to refer the node_modules folder:
Example component:
import myImage from './assets/images/myImage.png';
const MyComponent = () => (
<img src={myImage} />
);
export MyComponent;
Usage:
import MyComponent from 'myLibrary/MyComponent';
export default () => (
<MyComponent />
);
The error message:
myImage.png:1 GET http://localhost:9001/node_modules/myLibrary/assets/images/myImage.png 404 (Not Found)
As I understand the 'best' way to include assets is to use the url-loader so they're converted to data uri's. However, trying to use the url-loader without Webpack isn't working:
babel.config.js
...
plugins: [
[
"url-loader",
{
"extensions": ["png", "jpg", "jpeg", "gif", "svg", "pdf"],
"limit": 0
}
]
]
...
Error: Cannot find module 'babel-plugin-url-loader'
I found this and it works for PNG and SVG files - worked perfectly for what I needed!
https://www.npmjs.com/package/babel-plugin-inline-import-data-uri

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?
As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.
I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.
I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows
Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

How to correctly bundle a vscode extension using webpack

The problem that i am having is that when i run vsce package i still get the This extension consists of 3587 separate files. For performance reasons, you should bundle your extension: warning, i followed the Bundling Extension steps, debugging works as expected.
package.json
{
"main": "./out/extension",
"scripts": {
"vscode:prepublish": "webpack --mode production",
"webpack": "webpack --mode development",
"webpack-dev": "webpack --mode development --watch",
"compile": "npm run webpack",
"watch": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install"
},
}
The webpack config is an exact copy of the Bundling Extension example.
This sounds like you might've forgotten to add the source directories to .vscodeignore, so they're still being packaged into the release. The ignore file should probably contain at least the following, plus anything else not needed at runtime:
src/**
node_modules/**
If you are working with a Language Server extension which has both client and server folders, If you exclude the node_modules of the client and server from the bundle the extension would fail when installed and launch for the first time
.vscodeignore contains
.vscode
**/*.ts
**/*.map
out/**
node_modules/**
test_files/**
client/src/**
server/src/**
tsconfig.json
webpack.config.js
.gitignore
Also the documentation is a bit obsolete regarding the webpack.config.js, you have to wrap the 'use strict' into a function with all the settings.
The entry setting was changed according to my needs
//#ts-check
(function () {
'use strict';
const path = require('path');
/**#type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
entry: './client/src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
clean: true, //clean the dist folder for each time webpack is run
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]'
},
devtool: 'source-map',
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/
},
resolve: {
// support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
}
]
}
};
module.exports = config;
}());

Babel preset es2015 loose not working?

Is this "loose": true not working for the "es2015" preset or a mistake/misunderstanding on my part?
Input Code
I've tried with the REPL and on on the command line. I can't get babel to translate my loose javascript in looseWith.js:
var obj = {};
with (obj) {
}
.babelrc (attempt1):
{
"presets": [
[ "es2015", { "loose": true }]
]
}
.babelrc (attempt2 - as in REPL):
{
"presets": [
"es2015-loose"
]
}
I then try running either of these .babelrcs:
> babel looseWith.js
SyntaxError: looseWith.js: 'with' in strict mode (2:0)
1 | var obj = {};
> 2 | with (obj) {
| ^
3 | }
Seems to me that this is still in strict mode. The documentation on loose is quite scarce and just says:
Enable "loose" transformations for any plugins in this preset that allow them.
I'm trying to negate use strict :-) Is this my misunderstanding? What other meanings are there for "loose"?
I then tried adding "modules": "umd" to .babelrc to attempt1 above, and when fed with a proper strict .js file, it did produce umd output, so I think babel is picking up the .babelrcmodule just fine.
Background
I'm trying to be able to use ES6 in my underscore/lodash templates. The javascript output of e.g. _.template(script).source contains the "with" statement (by default). So I'm trying to use babel to translate ES6 - including the "with" statement - into ES5.
Environment
> node --version
v7.10.1
> cat package.json
{
"dependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-loose": "^8.0.0"
}
}

JSDoc output inconsistent between gulp-jsdoc & standard CLI

I'm trying to build docs for a simple set of JS code (given below). If I use gulp, the docs are created how I would expect them. If I use the CLI, the docs are incomplete.
Here's my JS code:
// BASE.js
/** #module BASE */
var BASE = {};
// MOD1.js
/** #class MOD1 - Test module */
BASE.MOD1 = Object.create({});
/**
* Just a test function
* #param {Object} var1 - A test variable
*/
BASE.MOD1.testFunction = function(var1){
alert('hi');
};
My gulp file:
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
outDir = './gulp-docs/',
docInfo = {},
docOptions = {},
docTemplate = {},
srcFiles = [
"BASE.js",
"MOD1.js"
];
gulp.task('default', function() {
return gulp.src(srcFiles)
.pipe(jsdoc.parser(docInfo))
.pipe(jsdoc.generator(outDir, docTemplate, docOptions))
});
And my command line:
C:\DocTest> jsdoc BASE.js MOD1.js --configure rawconf.json --destination raw-docs
rawconf.json:
{
"tags": {
"allowUnknownTags": true
},
"plugins": [],
"templates": {},
"opts": {
"package": "./rawpackage.json"
}
}
rawpackage.json:
{}
I run both gulp and the jsdoc command from the Node.js command prompt.
Output from gulp is the following files:
BASE.js.html
BASE.MOD1.html
index.html
MOD1.js.html
module-BASE.html
Output from the CLI is the following files:
BASE.js.html
index.html
MOD1.js.html
module-BASE.html
module-BASE-BASE.MOD1.html
There are some small differences which I can chalk up to the differences between the gulp-jsoc version of jsdoc (3.3.0-alpha5) and the current version (3.3.0-beta3).
But the biggest difference is that while in the gulp output, I can find information on testFunction, there is no information to be found at all regarding testFunction anywhere in the CLI output. I've even searched the HTML code--nothing.
So did I do something wrong? I'm just trying to achieve parity at this point, and I've exhausted any documentation I could find online.
If you look at the gulp-jsdoc github page here, there's a "Big Fat Warning" that this plugin isn't being kept up to date.
Try using the gulp-shell plugin. You can use exactly what you typed into the command line.