Karma setup for Angular 2. - karma-jasmine

I am trying to setup Karma with Jasmine for testing my Angular2 app. Karma fails to append extensions for imports in spec files. For example my spec file has import {TileComponent} from './tiles.component';
When I run Karma I get the following error: http://localhost:9876/base/wwwroot/app/tiles/tiles.component 404 (Not Found)
If I try to go to this link and manually apend js at the end it will load my file.
karma.conf.js:
module.exports = function (config) {
var appBase = 'wwwroot/app/';
var appAssets = '/base/app/';
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-htmlfile-reporter')
],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [ 'node_modules/systemjs/dist/system.src.js',
'node_modules/core-js/client/shim.js',
'node_modules/reflect-metadata/Reflect.js',
'node_modules/zone.js/dist/zone.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 },
{ 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 },
//{ pattern: 'karma-test-shim.js', included: false, watched: false },
//'systemjs.config.js',
'karma-test-shim.js',
{ pattern: appBase + '**/*.js', included: false, watched: true },
{ pattern: appBase + '**/*.html', included: false, watched: true },
{ pattern: 'wwwroot/styles/**/*.css', included: false, watched: true },
{ pattern: 'app/**/*.ts', included: false, watched: false },
{ pattern: appBase + '**/*.js.map', included: false, watched: false }
],
proxies: {
"/app/": appAssets
},
exclude: [],
preprocessors: {},
reporters: ['progress', 'html'],
htmlReporter: {
outputFile: '_test-output/tests.html',
pageTitle: 'Unit Tests',
subPageTitle: __dirname
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
karma-test-shim.js
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
__karma__.loaded = function () {
};
function isJsFile(path) {
return path.slice(-3) === '.js';
}
function isSpecFile(path) {
return /\.spec\.js$/.test(path);
}
function isBuiltFile(path) {
var builtPath = '/base/wwwroot/';
return isJsFile(path) && (path.substr(0, builtPath.length) === builtPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: '/base',
packageWithIndex: true, // sadly, we can't use umd packages (yet?)
map: {
'http://localhost:9876/base/wwwroot/app/app.component': 'http://localhost:9876/base/wwwroot/app/app.component.js'
}
});
System.import('systemjs.config.js')
.then(function () {
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
})
.then(function (providers) {
var testing = providers[0];
var testingBrowser = providers[1];
testing.setBaseTestProviders(
testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
})
.then(function () {
// Finally, load all spec files.
// This will run the tests directly.
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
}));
})
.then(__karma__.start, __karma__.error);

The problem was that I was importing system.config.js twice. I removed import from karma.conf.js file.
I also did some minor path changes.

Related

i18next not working with languageDetector and i18next-http-backend

i18next not working when passing multiple modules like i18next-http-backend and react-i18next and #os-team/i18next-react-native-language-detector
here is the sample code
i18n
.use(RNLanguageDetector)
.use(initReactI18next)
.use(Backend)
.init(
{
compatibilityJSON: 'v3',
fallbackLng: 'en',
supportedLngs: ['en', 'ar'],
load: 'languageOnly',
// ns: ['translations'],
// defaultNS: 'translations',
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
},
react: {
useSuspense: true,
},
backend: {
crossDomain: false,
withCredentials: false,
overrideMimeType: false,
// loadPath: '${SERVER_APTH}/{{lng}}.json',
request: function (options, url, payload, callback) {
console.log('Request here to get from API');
},
reloadInterval: false,
allowMultiLoading: true,
},
initImmediate: false,
},
(error, t) => {
console.log('loading complete');
console.log('Error', error);
},
);
i18n.languages = ['en', 'ar'];
i18n.on('languageChanged', nextLng => {
console.log('Changed', nextLng);
});
Also tried with custom language detector
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => {
console.log('Tagging here');
cb('en');
},
init: () => {},
cacheUserLanguage: () => {},
};
custom language detector work when i comment backend: { ... } section.
I need to store changed language and get translations according to it.
for changing i'm using
i18n.changeLanguage(nextLocale);
Where nextLocale will be "en" or "ar"

Terser Plugin doesnt run with Vue CLI 5 on vue build

I am trying to create a production build with the following configureWebpack but Terser doesnt run during build.
Code is not minimized or uglified. Ialso tried hidden-source-map
Using "terser-webpack-plugin": "^5.3.3" with #vue/cli#5.0.7
isProd is correctly set to true.
const TerserPlugin = require('terser-webpack-plugin');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
publicPath: '/',
devServer: {
host: 'staging-beta.myDomain.com',
port: 9000,
allowedHosts: 'all',
},
transpileDependencies: ['vuetify'],
chainWebpack: (config) => {
// reducted code
},
configureWebpack: {
devtool: 'source-map',
optimization: {
minimize: isProd,
minimizer: isProd
? [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
terserOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
},
},
}),
]
: [],
},
},
};
The correct setup is:
module.exports = defineConfig({
terser: {
minify: 'uglifyJs',
terserOptions: {
compress: {
drop_console: true,
},
},
},
})
You also need to npm install uglify-js
comments under output is deprecated.

Nuxt.js Oauth sometimes crashes whole webpage

I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!

karma+webpack+typescript+mocha require is not defined

I try to configure my environment to run tests on node.
This my my webpack.config.test.js
const serverConfig = {
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader' }
]
},
target: 'node',
externals:[nodeExternals()],
resolve: {
extensions: ['.ts', '.tsx', '.js']
}
};
module.exports = serverConfig;
karma.config.js
// Karma configuration
// Generated on Tue Jun 27 2017 07:20:43 GMT-0500 (Hora est. Pacífico, Sudamérica)
const webpackConfig=require('./config/webpack/webpack.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha','es6-shim'],
plugins:[
require("karma-es6-shim"),
'karma-webpack',
'karma-jsdom-launcher',
'karma-mocha',
'karma-spec-reporter',
'karma-jsdom-launcher',
'karma-coverage',
'karma-chrome-launcher',
"karma-phantomjs-launcher",
'karma-htmlfile-reporter'
],
files: [
'test/**/*.spec.ts'
],
coverageReporter: {
webpackMiddleware: {
stats: "errors-only"
},
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
// list of files to exclude
exclude: [
],
preprocessors: {
'test/**/*.spec.ts':["webpack","coverage"]
},
webpack:webpackConfig,
reporters: ['spec','progress','html'],
htmlReporter: {
outputFile: 'tests/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9876,
colors: true,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}
test1
import { DBCONFIG } from './../src/config/db.config';
import { CONEXION } from './../src/config/database/mongo';
import { expect } from 'chai';
describe("#DATABASE",()=>{
it("Esta conectado",()=>{
CONEXION("hola",DBCONFIG.MONGO_URL_LOCAL)
.then(()=>{
expect(1).to.be("1");
})
.catch((e)=>{
expect(1).to.be(e);
})
})
});
test2
import { expect } from 'chai';
describe("#User",()=>{
it("use2r",()=>{
expect(1).to.equal("1");
})
})
When I run mocha + webpack with mocha-webpack, there is no problem the tests are running.
package.json
"test-server": "mocha-webpack --timeout 1000 --webpack-config config/webpack/webpack.test.js test/**/*.spec.ts",
"test":"karma start"
When I do it from karma depending on which browser I use to display the messages I throw similar errors, when I throw it with jsdom or PhantomJS I throw the following
require is not defined o Cannot find
Looking in git, the only answer that solved the problem, is to put in the processors of karma the following.
'test/**/*.spec.ts':["webpack","coverage"]
It is the same way and I have varied, but the error continues.

karma config with browserify/babel

I have a karma conf that I try to make work with babel/browserify. It looks like this:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/**/*.js': ['babel', 'browserify'],
'unit/*.spec.js': ['babel', 'browserify']
},
files: [
'../src/**/*.js',
'unit/*.spec.js'
],
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
}
});
};
Every time I run this configuration through gulp babel preprocessor returns the following error:
ERROR [preprocessor.babel]: Cannot read property 'bundleFile' of undefined
Try adding 'browserify' to 'frameworks', like this:
frameworks: ['browserify', 'jasmine']
I had the same error, fixed by doing this. Here's my working karma config
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['browserify', 'mocha'],
reporters: ['dots'],
files: ['./*test.js'],
preprocessors: {
'*.js': ['browserify']
},
logLevel: 'LOG_DEBUG',
browserify: {
debug: true,
transform: [ ['babelify', {presets: ['es2015', "react"]} ] ]
}
});
};
The fixed config file:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine', 'browserify'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/js/app.js': ['browserify'],
'../src/js/login/login-ctrl.js': ['browserify'],
'./unit/*.spec.js': ['browserify']
},
files: [
'../../node_modules/angular/angular.js',
'../../node_modules/angular-mocks/angular-mocks.js',
'../src/js/app.js',
'../dist/js/partials/templates-all.js',
'../src/js/login/login-ctrl.js',
'unit/*.spec.js'
],
browserify: {
debug: true,
transform: [
['babelify']
]
},
singleRun: false,
reporters: ['progress'],
colors: true
});
};