Karma setup don't see the .ts files - karma-jasmine

I have a big old project on Angular2, which I didn't start, and now I need to add tests there. I setup jasmine and karma, but, unfortunately, when I start "npm test", it don't see the .ts files, so I see the result only in .js-tests.
Here are the setup code:
system.config.js
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'src',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
karma.conf.js
// #docregion
module.exports = function(config) {
var appBase = 'src/'; // transpiled app JS and map files
var appSrcBase = 'src/'; // app source TS files
var appAssets = '/base/src/'; // component assets fetched by Angular's compiler
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'), // click "Debug" in browser to see it
require('karma-htmlfile-reporter') // crashing w/ strange socket error
],
customLaunchers: {
// From the CLI. Not used here but interesting
// chrome setup for travis CI using chromium
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [
// System.js for module loading
'node_modules/systemjs/dist/system.src.js',
// Polyfills
'node_modules/core-js/client/shim.js',
'node_modules/reflect-metadata/Reflect.js',
// zone.js
'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/proxy.js',
'node_modules/zone.js/dist/sync-test.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
// RxJs
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
// Paths loaded via module imports:
// Angular itself
{pattern: 'node_modules/#angular/**/*.js', included: false, watched: false},
{pattern: 'node_modules/#angular/**/*.js.map', included: false, watched: false},
{pattern: 'systemjs.config.js', included: false, watched: false},
'karma-test-shim.js',
// transpiled application & spec code paths loaded via module imports
{pattern: appBase + '**/*.js', included: false, watched: true},
{pattern: appBase + '**/*.ts', included: false, watched: true},
// Asset (HTML & CSS) paths loaded via Angular's component compiler
// (these paths need to be rewritten, see proxies section)
{pattern: appBase + '**/*.html', included: false, watched: true},
{pattern: appBase + '**/*.css', included: false, watched: true},
// Paths for debugging with source maps in dev tools
{pattern: appSrcBase + '**/*.ts', included: false, watched: false},
// {pattern: appBase + '**/*.js.map', included: false, watched: false}
],
// Proxied base paths for loading assets
proxies: {
// required for component assets fetched by Angular's compiler
"/src/": appAssets
},
exclude: [],
preprocessors: {},
// disabled HtmlReporter; suddenly crashing w/ strange socket error
reporters: ['progress', 'kjhtml'],//'html'],
// HtmlReporter configuration
htmlReporter: {
// Open this file to see results in browser
outputFile: '_test-output/tests.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: __dirname
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
karma-test-shim.js
// #docregion
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
var builtPath = '/base/src/';
__karma__.loaded = function () { };
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
function isBuiltFile(path) {
return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: '/base',
// Extend usual application package list with test folder
packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },
// Assume npm: is set in `paths` in systemjs.config
// Map the angular testing umd bundles
map: {
'#angular/core/testing': 'npm:#angular/core/bundles/core-testing.umd.js',
'#angular/common/testing': 'npm:#angular/common/bundles/common-testing.umd.js',
'#angular/compiler/testing': 'npm:#angular/compiler/bundles/compiler-testing.umd.js',
'#angular/platform-browser/testing': 'npm:#angular/platform-browser/bundles/platform-browser-testing.umd.js',
'#angular/platform-browser-dynamic/testing': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'#angular/http/testing': 'npm:#angular/http/bundles/http-testing.umd.js',
'#angular/router/testing': 'npm:#angular/router/bundles/router-testing.umd.js',
'#angular/forms/testing': 'npm:#angular/forms/bundles/forms-testing.umd.js',
},
});
System.import('systemjs.config.js')
.then(initTestBed)
.then(initTesting);
function initTestBed(){
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
}
// Import all spec files and start karma
function initTesting () {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
})
)
.then(__karma__.start, __karma__.error);
}
I know, that it is simplier to use solutions of angular-seed or angular-CLI, but it's really hard to migrate this huge project to new platform, so please help! )
What should I do to my "npm test" finally see the .spec.ts files?

This function is capturing only .js files:
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
To fix that, change to an expression that will include .ts files, such as:
function isSpecFile(path) {
return /\.spec\.(.*\.)?[jt]s$/.test(path);
}
Similar issue with:
function isJsFile(path) {
return path.slice(-3) == '.js';
}
...which could be changed to:
function isJsFile(path) {
return path.slice(-3) == '.js' || path.slice(-3) == '.ts';
}
I'd probably change the name isJsFile to isJsOrTsFile too, but you'd have to replace all instances.

Related

Uncaught ReferenceError: webpackJsonp in Vue Js

I have suddenly started hitting Uncaught ReferenceError: webpackJsonp in Vue Js. I am fairly new to Js and have just started with Vue applications. I tried the various solutions that were mentioned in the Git and stackoverflow but they have not worked. Can someone help me out.
To give some context, the issue suddenly appeared without having made much of a change. The code is working when it was in the state earlier but making any change in the components even modifying the css has started causing the issue.
Based on what I read about the issue, it is supposed to be controlled by the webpack.prod.conf.js (Attached mine below). Incase any other info is needed please let me know.
"use strict";
const path = require("path");
const utils = require("./utils");
const webpack = require("webpack");
const config = require("../config");
const merge = require("webpack-merge");
const baseWebpackConfig = require("./webpack.base.conf");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCSSPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const env = require("../config/prod.env");
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath("js/[name].[chunkhash].js"),
chunkFilename: utils.assetsPath("js/[id].[chunkhash].js")
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
"process.env": env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath("css/[name].[contenthash].css"),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ?
{ safe: true, map: { inline: false } } :
{ safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: "index.html",
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: "dependency"
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
async: false,
minChunks(module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, "../node_modules")) === 0
);
// return module.context && module.context.includes("node_modules");
}
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: "app",
async: "vendor-async",
children: true,
minChunks: 3
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: "manifest",
async: false,
minChunks: Infinity
}),
// copy custom static assets
new CopyWebpackPlugin([{
from: path.resolve(__dirname, "../static"),
to: config.build.assetsSubDirectory,
ignore: [".*"]
}])
]
});
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require("compression-webpack-plugin");
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: new RegExp(
"\\.(" + config.build.productionGzipExtensions.join("|") + ")$"
),
threshold: 10240,
minRatio: 0.8
})
);
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = webpackConfig;
The entry points are missing in the configuration, i.e. you are not informing webpack from where the application should start.
Also this issue is happening because you have mentioned vendor
please refer this link

How to enable dotenv variables for a file inside the /public folder in a Vue project?

I have very little experience with configuring Webpack, and I'am a bit overwhelmed by this issue.
I've been working on a Vue2 project built on top of this boilerplate. The project has a folder called public which contains the entry point file index.html. Inside that index.html file I can normally access .env environment variables (e.g. process.env.VUE_APP_PAGE_TITLE).
I've included an HTML fragment inside the public folder, navbar.html, because I want it to be available for other applications via https://example.com/public/navbar.html. However, I cannot seem to get my environment variables working inside ./public/navbar.html even though they work just fine in ./public/index.html. I assume this is a problem with my webpack config.
I know I can edit my Webpack config by editing a file in my project root called vue.config.js. This file contains a configureWebpack object, but I have no idea how to make it enable environment variables inside ./public/navbar.html. Any help would be appreciated.
EDIT:
Here's my vue.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
function resolveClientEnv() {
const env = {};
Object.keys(process.env).forEach((key) => {
env[key] = process.env[key];
});
env.BASE_URL = '/';
return env;
}
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin({
// This is the generated file from the build, which ends up in public/navbar.html
filename: 'navbar.html',
// This is the source file you edit.
template: 'public/navbar.html',
templateParameters: (compilation, assets, pluginOptions) => {
let stats;
return Object.assign({
// make stats lazy as it is expensive
get webpack() {
return stats || (stats = compilation.getStats().toJson());
},
compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: pluginOptions,
},
}, resolveClientEnv());
},
}),
],
},
};
This is what my custom HTMLWebpackPlugin adds to the configuration according to vue inspect:
{
options: {
template: 'public/navbar.html',
templateContent: false,
templateParameters: function () { /* omitted long function */ },
filename: 'navbar.html',
hash: false,
inject: true,
compile: true,
favicon: false,
minify: 'auto',
cache: true,
showErrors: true,
chunks: 'all',
excludeChunks: [],
chunksSortMode: 'auto',
meta: {},
base: false,
title: 'Webpack App',
xhtml: false
},
childCompilerHash: undefined,
childCompilationOutputName: undefined,
assetJson: undefined,
hash: undefined,
version: 4
}
Use this standard plugin to generate navbar.html. https://github.com/jantimon/html-webpack-plugin.
If you read the docs, the templateParameters option is what you pass env variables to. Those variables will be available in navbar.html.
This is the same plugin that vue-cli uses for index.html. If you run the vue inspect command, you can see what options they provide to the plugin. You'll need to read the source code for resolveClientEnv() to see how it works.
Example:
/* config.plugin('html-portal') */
new HtmlWebpackPlugin(
{
templateParameters: (compilation, assets, pluginOptions) => {
// enhance html-webpack-plugin's built in template params
let stats
return Object.assign({
// make stats lazy as it is expensive
get webpack () {
return stats || (stats = compilation.getStats().toJson())
},
compilation: compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: pluginOptions
}
}, resolveClientEnv(options, true /* raw */))
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
collapseBooleanAttributes: true,
removeScriptTypeAttributes: true
},
chunks: [
'chunk-vendors',
'chunk-common',
'portal'
],
template: 'C:\\Users\\Eric\\workspace\\arc-core\\portal\\client\\templates\\portal.html',
filename: 'portal.html',
title: 'Arc Portal'
}
),
That's a bit much, a minimal example would be:
new HtmlWebpackPlugin({
// This is the generated file from the build, which ends up in public/navbar.html
filename: 'navbar.html',
// This is the source file you edit.
template: 'templates/navbar.html',
templateParameters: {
MY_VAR: 'myVar'
}
}),

Run nuxt on https locally – problem with nuxt.config.js

I am trying to run nuxt locally with https to test some geolocation stuff.
(https://nuxtjs.org/, https://nuxtjs.org/api/nuxt)
I was following this tutorial:
https://www.mattshull.com/blog/https-on-localhost
And then I found this:
https://github.com/nuxt/nuxt.js/issues/146
Both links seem to describe pretty nicely how to run nuxt with server.js programmatically.
The thing is that in my nuxt.config.js I seem to have some problems.
I get the following error when runnung yarn dev:
/Users/USER/Documents/github/mynuxtrepo/nuxt.config.js:2
import { module } from 'npmmodule'
> SyntaxError: Unexpected token {
In my nuxt config I import a custom helper to generate localized routes. Not really important what it does but obviously it can't handle the import syntax.
I assume that the node version does not understand.
So how can I get it to run? Do I have to require everything instead of importing?
Or is my assumption wrong and the cause lies somewhere totally different?
Thank you for your help
Cheers.
------
Edit 1:
My nuxt config looks like this:
// eslint-disable-next-line prettier/prettier
import { generateLocalizedRoutes, generateRoutesFromData } from 'vuecid-helpers'
import config from './config'
// TODO: Add your post types
const postTypes = [{ type: 'pages' }, { type: 'posts', paginated: true }]
// TODO: Add your site title
const siteTitle = 'Title'
const shortTitle = 'short title'
const siteDescription = 'Page demonstrated with a wonderful example'
const themeColor = '#ffffff'
// TODO: Replace favicon source file in /static/icon.png (512px x 512px)
// eslint-disable-next-line prettier/prettier
const iconSizes = [32, 57, 60, 72, 76, 144, 120, 144, 152, 167, 180, 192, 512]
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: 'Loading…',
htmlAttrs: {
lang: config.env.DEFAULTLANG,
dir: 'ltr' // define directionality of text globally
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
// TODO: Check this info
{ name: 'author', content: 'Author' },
{ name: 'theme-color', content: themeColor },
// TODO: Add or remove google-site-verification
{
name: 'google-site-verification',
content: '...W1GdU'
}
],
link: []
},
/*
** env: lets you create environment variables that will be shared for the client and server-side.
*/
env: config.env,
/*
** Customize the progress-bar color
** TODO: Set your desired loading bar color
*/
loading: { color: '#0000ff' },
/*
** CSS
*/
css: ['#/assets/css/main.scss'],
/*
** Plugins
*/
plugins: [
{ src: '~/plugins/global.js' },
{ src: '~/plugins/throwNuxtError.js' },
{ src: '~/plugins/axios' },
{ src: '~/plugins/whatinput.js', ssr: false },
{ src: '~/plugins/i18n.js', injectAs: 'i18n' },
{ src: '~/plugins/vuex-router-sync' },
{ src: '~/plugins/vue-bows' },
{ src: '~/plugins/vue-breakpoint-component', ssr: false }
],
/*
** Modules
*/
modules: [
'#nuxtjs/axios',
'#nuxtjs/sitemap',
[
'#nuxtjs/pwa',
{
icon: {
sizes: iconSizes
},
// Override certain meta tags
meta: {
viewport: 'width=device-width, initial-scale=1',
favicon: true // Generates only apple-touch-icon
},
manifest: {
name: siteTitle,
lang: config.env.DEFAULTLANG,
dir: 'ltr',
short_name: shortTitle,
theme_color: themeColor,
start_url: '/',
display: 'standalone',
background_color: '#fff',
description: siteDescription
}
}
]
],
/*
** Workbox config
*/
workbox: {
config: {
debug: false,
cacheId: siteTitle
}
},
/*
** Axios config
*/
axios: {
baseURL: '/'
},
/*
** Generate
*/
generate: {
subFolders: true,
routes: [
...generateRoutesFromData({
langs: config.env.LANGS,
postTypes: postTypes,
dataPath: '../../../../../static/data',
bundle: 'basic',
homeSlug: config.env.HOMESLUG,
errorPrefix: config.env.ERROR_PREFIX
})
]
},
/*
** Build configuration
*/
build: {
extend(config, { isDev, isClient }) {
/*
** Run ESLINT on save
*/
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
/*
** Router
*/
router: {
linkActiveClass: 'is-active',
linkExactActiveClass: 'is-active-exact',
middleware: ['i18n'],
extendRoutes(routes) {
// extends basic routes (based on your files/folders in pages directory) with i18n locales (from our config.js)
const newRoutes = generateLocalizedRoutes({
baseRoutes: routes,
defaultLang: config.env.DEFAULTLANG,
langs: config.env.LANGS,
routesAliases: config.routesAliases
})
// Clear array
routes.splice(0, routes.length)
// Push newly created routes
routes.push(...newRoutes)
}
},
/*
** Sitemap Configuration
*/
sitemap: {
path: '/sitemap.xml',
hostname: config.env.FRONTENDURLPRODUCTION,
cacheTime: 1000 * 60 * 15,
generate: true,
routes: [
...generateRoutesFromData({
langs: config.env.LANGS,
postTypes: postTypes,
dataPath: '../../../../../static/data',
bundle: 'basic',
homeSlug: config.env.HOMESLUG,
errorPrefix: config.env.ERROR_PREFIX
})
]
}
}
You can see that the generateLocalizedRoutes and the generateRoutesFromData methods are used to generate localized routes and is also taking post json files to generate routes from data (:slug).
--------- Edit 2:
I got it to run eventually.
I had to require all parts within the nuxt.config.js instead of importing them. I also resolved issues with the certificates. So I thought it was all cool 🚀.
BUT!!! 🚧:
Then I found out that I had my config file used within my post template.
So I thought I would also require the file within my template:
Like const config = require('~/config').
But then I would get this error:
[nuxt] Error while initializing app TypeError: ""exports" is read-only"
After some research, I found that is probably a thing when using common.js require and module.exports together with ES6 import/export within my project. (Probably linked to: https://github.com/FranckFreiburger/vue-pdf/issues/1).
So how could I still use my config.js when running nuxt programmatically (with require) and then also within my app?
I am glad to hear any ideas on this...
Cheers
Well, just to close this:
My problem resulted from running nuxt as a node app, which does not understand ES6 import statements, which appeared in my nuxt config.
So I had to rewrite things to work with commons.js (require).
This works for now.
(I also tried to run babel-node when starting the server.js, but had no success. Does not mean this did not work, I just wasn't keen on trying harder).
Thanks for the comments.
cheers

Karma angular 2 error cannot read foreach of undefined at _normalizeProvider

I have some issue when I trying to test angular 2 with karma runner and got this error:
http://prntscr.com/awsmor
I don't know what it this (got some errors when I update karma/node/grunt-karma). First got error with undefined character in headers (karma socket) after that about undefined forEach at _normalize.
I don't have any idea how I can fix it and where to looking. Maybe someone can help me?
My Karma.conf
// Karma configuration
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-coverage',
],
colors: true,
autoWatch: true,
// don't shut down phantom instance for 1 minute
// because should be able to reuse the instance
// in one testrun. E.g. run unit tests against
// sources and minified artifacts
browserNoActivityTimeout: 60000,
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
logLevel: config.LOG_ERROR,
preprocessors: {
'built/production/**/!(*spec).js': ['coverage']
},
files: [{
pattern: 'node_modules/angular2/bundles/angular2-polyfills.js',
included: true,
watched: true
}, {
pattern: 'node_modules/systemjs/dist/system.src.js',
included: true,
watched: true
}, {
pattern: 'node_modules/rxjs/bundles/Rx.js',
included: true,
watched: true
}, {
pattern: 'node_modules/angular2/bundles/angular2.dev.js',
included: true,
watched: true
},
{
pattern: 'node_modules/angular2/bundles/http.dev.js',
included: true,
watched: true
},
{
pattern: 'node_modules/angular2/bundles/router.dev.js',
included: true,
watched: true
}, {
pattern: 'node_modules/angular2/bundles/testing.dev.js',
included: true,
watched: true
}, {
pattern: 'karma-test-shim.js',
included: true,
watched: true
}, {
pattern: 'src/**/*.ts',
included: false,
watched: false
}, {
pattern: 'built/production/**/*.js',
included: false,
watched: true
}, {
pattern: 'built/production/**/*.js.map',
included: false,
watched: false
}],
proxies: {
// required for component assests fetched by Angular's compiler
'/src/': './src/'
},
port: 9876,
// singleRun: true,
reporters: ['progress', 'dots', 'coverage'],
coverageReporter: {
reporters: [{
type: 'html'
}]
},
});
};
Karma test.shim
// Tun on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
packages: {
'built': {
defaultExtension: false,
format: 'register',
map: Object.keys(window.__karma__.files).
filter(onlyAppFiles).
reduce(function createPathRecords(pathsMapping, appPath) {
// creates local module name mapping to global path with karma's fingerprint in path, e.g.:
// './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
var moduleName = appPath.replace(/^\/built\//, './').replace(/\.js$/, '');
pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
return pathsMapping;
}, {})
}
}
});
System.import('angular2/testing').then(function(testing) {
return System.import('angular2/src/platform/browser/browser_adapter').then(function(providers) {
testing.setBaseTestProviders(providers.TEST_BROWSER_PLATFORM_PROVIDERS,
providers.TEST_BROWSER_APPLICATION_PROVIDERS);
});
}).then(function() {
return Promise.all(
Object.keys(window.__karma__.files) // All files served by Karma.
.filter(onlySpecFiles)
// .map(filePath2moduleName) // Normalize paths to module names.
.map(function(moduleName) {
// loads all spec files via their global module names (e.g. 'base/src/app/hero.service.spec')
return System.import(moduleName);
}));
})
.then(function() {
__karma__.start();
}, function(error) {
__karma__.error(error.stack || error);
});
function filePath2moduleName(filePath) {
return filePath.
replace(/^\//, ''). // remove / prefix
replace(/\.\w+$/, ''); // remove suffix
}
function onlyAppFiles(filePath) {
return /^\/built\/.*\.js$/.test(filePath)
}
function onlySpecFiles(path) {
return /.spec\.js$/.test(path);
}
testing.setBaseTestProviders(
browser.TEST_BROWSER_PLATFORM_P‌​ROVIDERS, browser.TEST_BROWSER_APPLICATION_PROVIDERS);
rc1 deprecated TEST_BROWSER_PLATFORM_PROVIDERS I believe so commenting
it out helped

Require and import finds module, but proxyquireify does not?

As the question states, the requiring/importing of the module works fine in these cases:
const Session = require('../session.js').default;
or
import Session from '../session.js');
But I want to replace a module that is required inside session.js, so I tried to do that in a test with Proxyquireify:
const proxyquire = require('proxyquireify')(require);
const someStub = () => { return {}; };
someStub['#noCallThru'] = true;
const Session = proxyquire('../session.js', {
'some': someStub
}).default;
Then I get an error stating that the module '../session.js' cannot be found.
PhantomJS 1.9.8 (Linux 0.0.0) ERROR
Error: Cannot find module '../session.js'
My karma config is this:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'spec/**/*Spec.js'
],
exclude: [
'spec/**/PlayerSpec.js'
],
preprocessors: {
'spec/**/*Spec.js': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify']
},
reporters: ['progress', 'dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
};
What could be wrong? Do you need any more information?
Just stumbled onto the same issue.
Noticed that proxyquireify did not inject require calls next to proxyquire ones for some reason, so I just ended up simply doing it myself, at least for now.
Try using something like this:
require('../session.js');
const Session = proxyquire('../session.js', ...);