"TypeError: expect(...).to.have.been.calledWith is not a function" With Karma - sinon

I have the following Karma Conf...
var webpackConfig = require('./webpack.config.js');
webpackConfig.entry = {};
webpackConfig.plugins = [];
var globFlat = require('glob-flat');
// TODO: These are redundant with the webpack plugin...
var appFiles = globFlat.sync([
'./src/main/coffee/**/*.coffee'
]);
var styleFiles = globFlat.sync([
]);
var dependencyFiles = [
'test-main.js',
'./src/main/typescripts/**/*.ts',
'node_modules/angular-mocks/angular-mocks.js'
];
var testFiles = globFlat.sync([
'./test/main/webapp/**/*.coffee',
'./test/main/webapp/**/*.js'
]);
var files = dependencyFiles.concat(appFiles, styleFiles, testFiles);
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs', 'chai-spies', 'chai', 'sinon', 'sinon-chai'],
files: files,
exclude: [ ],
preprocessors: {
'./src/main/coffee/**/*.coffee': ['webpack'],
'./src/main/typescripts/**/*.ts': ['webpack'],
'./test/**/*.coffee': ['coffee']
},
webpack: webpackConfig,
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
};
But when I run a few of the tests break with...
TypeError: expect(...).to.have.been.calledWith is not a function
I don't understand because I am including sinon-chai

There were a couple problems here...
Order
My current order was ['mocha', 'requirejs', 'chai-spies', 'chai', 'sinon', 'sinon-chai']. This is read right to left not left to right. So I needed to change to ['mocha', 'requirejs', 'chai-spies', 'sinon-chai', 'chai', 'sinon']. This way sinon-chai is loaded after sinon and chai.
RequireJS doesn't work with 'sinon-chai' https://github.com/kmees/karma-sinon-chai/issues/11
My final ended up being...
['mocha', 'sinon-chai', 'chai', 'sinon']

Related

Gulp and Critical CSS - TypeError: Cannot read property 'content-type' of undefined

I'm running my build in Gulp and keep getting the following error in my terminal when it comes to generating my critical css files.
[08:47:29] -> Generating critical CSS: https://example.com/ -> ./templates/index_critical.min.css
[08:47:43] TypeError: Cannot read property 'content-type' of undefined
What does the error mean?
How do I solve the error?
If this is a syntax issue in my gulp file - is there way to find the line and reference to the issue either in the terminal when running the command or by using a validator?
Below is the gulp task for the critical css along with the tasks for processing the css and sass files which it references.
// scss - build the scss to the build folder, including the required paths, and writing out a sourcemap
gulp.task("scss", () => {
$.fancyLog("-> Compiling scss");
return gulp.src(pkg.paths.src.scss + pkg.vars.scssName)
.pipe($.plumber({errorHandler: onError}))
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.sass({
includePaths: pkg.paths.scss
})
.on("error", $.sass.logError))
.pipe($.cached("sass_compile"))
.pipe($.autoprefixer())
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.build.css));
});
// css task - combine & minimize any distribution CSS into the public css folder, and add our banner to it
gulp.task("css", ["scss"], () => {
$.fancyLog("-> Building css");
return gulp.src(pkg.globs.distCss)
//.pipe(purgecss({
// content: [pkg.paths.templates + '*.twig']
// }))
.pipe($.plumber({errorHandler: onError}))
.pipe($.newer({dest: pkg.paths.dist.css + pkg.vars.siteCssName}))
.pipe($.print())
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.concat(pkg.vars.siteCssName))
.pipe($.if(process.env.NODE_ENV === "production",
$.cssnano({
discardComments: {
removeAll: true
},
discardDuplicates: true,
discardEmpty: true,
minifyFontValues: true,
minifySelectors: true
})
))
.pipe($.header(banner, {pkg: pkg}))
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.dist.css))
.pipe($.filter("**/*.css"))
.pipe($.livereload());
});
// Process the critical path CSS one at a time
function processCriticalCSS(element, i, callback) {
const criticalSrc = pkg.urls.critical + element.url;
const criticalDest = pkg.paths.templates + element.template + "_critical.min.css";
let criticalWidth = 1200;
let criticalHeight = 1200;
if (element.template.indexOf("amp_") !== -1) {
criticalWidth = 600;
criticalHeight = 19200;
}
$.fancyLog("-> Generating critical CSS: " + $.chalk.cyan(criticalSrc) + " -> " + $.chalk.magenta(criticalDest));
$.critical.generate({
src: criticalSrc,
dest: criticalDest,
penthouse: {
blockJSRequests: false,
forceInclude: pkg.globs.criticalWhitelist
},
inline: false,
ignore: [],
css: [
pkg.paths.dist.css + pkg.vars.siteCssName,
],
minify: true,
width: criticalWidth,
height: criticalHeight
}, (err, output) => {
if (err) {
$.fancyLog($.chalk.magenta(err));
}
callback();
});
}
// critical css task
gulp.task("criticalcss", ["css"], (callback) => {
doSynchronousLoop(pkg.globs.critical, processCriticalCSS, () => {
// all done
callback();
});
});
// Lean Production build
gulp.task("leanbuild", ["set-prod-node-env", "static-assets-version", "criticalcss"]);
This happens if the src param you pass into critical is invalid, and returns no response.

Webpack - Bundle only required CSS files for production

I have a Vue app that has 3 different css themes depending on what the 'brand' is set to. Right now it is working in development. I run an npm run dev command and pass in the brand, then set the brand variable to be globally accessible, and then in my main.js file I set the required css dynamically based on what the brand variable is.
var brand = window.__BRAND__;
require('../static/' + brand + '/css/typography.css')
require('../static/' + brand + '/css/header.css')
require('../static/' + brand + '/css/main.css')
require('../static/' + brand + '/css/footer.css')
file structure:
static
foo
css
bar
css
So if I run 'npm --brand=bar run dev' it will require '..static/bar/typography.css' etc.
This works great in my local environment; each has it's own distinct look. The issue I'm having now is with building the app for production. Webpack is somehow compiling ALL of the css files into one and I end up with a hybrid app that has some styling from each. Instead, I need it to compile the CSS with ONLY the files that are required. Here is my webpack.prod.conf file:
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : 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 webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
comparisons: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
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'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// 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
)
}
}),
// 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',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
]),
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
})
if (config.build.productionGzip) {
var 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) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
and my config/index.js file:
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://localhost:3001',
changeOrigin: true
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

How to update css theme file in WordPress

I am confused on where to edit WordPress themes. I am new to WordPress and have a custom theme which main style.css file just imports the style for this theme like this:
#import url('assets/stylesheets/app.css');
I read that it is recommended to make a new child theme, but I don't see the need for that in my case, since I would like to almost completely change the css of the theme, so there is no need to keep the original theme files. Since, I tried to modify the file 'assets/stylesheets/app.css' I couldn't see any changes in the browser. Can I edit the styles there, or I need to do it in the WP admin dashboard somewhere?
I would like to build my scripts with gulp, which I set up like this:
var gulp = require('gulp');
var sass = require('gulp-sass');
var include = require('gulp-include');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var sourcemaps = require('gulp-sourcemaps');
var prefix = require('gulp-autoprefixer');
var connect = require('gulp-connect');
var browserify = require('gulp-browserify');
var livereload = require('gulp-livereload');
var browsersync = require('browser-sync');
var config = {
srcDir: './assets',
styles: {
src: '/scss/app.scss',
dest: '/stylesheets',
includePaths: [
'node_modules/foundation-sites/scss'
],
prefix: ["last 2 versions", "> 1%", "ie 9"]
},
scripts: {
src: '/js/app.js',
dest: '/js'
},
img: {
src: '/images/**/*',
dest: '/images'
}
};
var srcDir = './src',
destDir = './build';
gulp.task('styles', function() {
return gulp.src(config.srcDir + config.styles.src)
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: config.styles.includePaths,
sourceMap: true,
outFile: config.srcDir + config.styles.dest + '/app.css',
outputStyle: 'compressed'
}))
.pipe(prefix(config.styles.prefix))
.pipe(sourcemaps.write())
.on('error', sass.logError)
.pipe(gulp.dest(config.srcDir + config.styles.dest))
.pipe(browsersync.reload({ stream: true }));
});
gulp.task('scripts', function() {
gulp.src(config.srcDir + config.scripts.src)
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(gulp.dest(config.srcDir + config.scripts.dest))
});
gulp.task('include', function() {
return gulp.src(config.srcDir + config.img.src)
.pipe(gulp.dest(config.srcDir + config.img.dest));
});
gulp.task('watch', function () {
// Watch .scss files
gulp.watch(config.srcDir + config.styles.src, ['styles']);
// Watch .js files
gulp.watch(config.srcDir + config.scripts.src, ['scripts']);
});
gulp.task('default', ['styles', 'scripts', 'watch']);
So, not sure how can I do it utilizing gulp. Where can I change the theme without creating the child theme?
Where does the import of "app.css" happen - at the beginning or at the end of the "style.css" file? If it's at the beginning, the changed rules in "app.css" might be overwritten by the following "style.css" rules.

e2e browser opens and close immedietly

I am trying to test my app and followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/ i merged my app with firebase. Everything worked good, but when i run npm run e2e browser opens and close immediately in my terminal pops an error.
I followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/
Actually my issue is that i could not able to see any action takes place in my e2e browser could some on help me
protractorconfig.js
exports.config = {
baseUrl: 'http://192.168.1.2:8100/',
specs: [
'../app/pages/home/home.e2e.ts',
'../app/pages/Admin/admin.e2e.ts',
//'../app/pages/Listing/lisitngPage.e2e.ts'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
chromeOnly: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-web-security']
}
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = false;
},
useAllAngular2AppRoots: true
};
gulpfile.ts
import { join } from 'path';
const config: any = {
gulp: require('gulp'),
appDir: 'app',
testDir: 'test',
testDest: 'www/build/test',
typingsDir: 'typings',
};
const imports: any = {
gulp: require('gulp'),
runSequence: require('run-sequence'),
ionicGulpfile: require(join(process.cwd(), 'gulpfile.js')),
};
const gulp: any = imports.gulp;
const runSequence: any = imports.runSequence;
// just a hook into ionic's build
gulp.task('build-app', (done: Function) => {
runSequence(
'build',
(<any>done)
);
});
// compile E2E typescript into individual files, project directoy structure is replicated under www/build/test
gulp.task('build-e2e', ['clean-test'], () => {
let typescript: any = require('gulp-typescript');
let tsProject: any = typescript.createProject('tsconfig.json');
let src: Array<any> = [
join(config.typingsDir, '/index.d.ts'),
join(config.appDir, '**/*e2e.ts'),
];
let result: any = gulp.src(src)
.pipe(typescript(tsProject));
return result.js
.pipe(gulp.dest(config.testDest));
});
// delete everything used in our test cycle here
gulp.task('clean-test', () => {
let del: any = require('del');
// You can use multiple globbing patterns as you would with `gulp.src`
return del([config.testDest]).then((paths: Array<any>) => {
console.log('Deleted', paths && paths.join(', ') || '-');
});
});
// run jasmine unit tests using karma with PhantomJS2 in single run mode
gulp.task('karma', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: true,
};
new karma.Server(karmaOpts, done).start();
});
// run jasmine unit tests using karma with Chrome, Karma will be left open in Chrome for debug
gulp.task('karma-debug', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: false,
browsers: ['Chrome'],
reporters: ['mocha'],
};
new karma.Server(karmaOpts, done).start();
});
// run tslint against all typescript
gulp.task('lint', () => {
let tslint: any = require('gulp-tslint');
return gulp.src(join(config.appDir, '**/*.ts'))
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// build unit tests, run unit tests, remap and report coverage
gulp.task('unit-test', (done: Function) => {
runSequence(
['lint', 'html'],
'karma',
(<any>done)
);
});

Grunt change target based on input

My Gruntfile is as follows:
module.exports = function(grunt) {
'use strict';
var dictionary = {
'all' : '**',
'html5' : 'some/path'
};
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
grunt.initConfig({
eslint : {
options : {
config : '.eslintrc'
},
target : ['hello/world/js/<HERE>/**.js']
}
});
grunt.registerTask('test', 'Lint a set of files', function(set) {
set = set || 'all';
var path = dictionary[set];
grunt.task.run('eslint');
});
};
Notice the <HERE> in the code. That is where I want the path variable to be inserted. I just have no idea how to do this.
If I type grunt test:html5, the path variable is set to the correct path, so I got that working, now I just need to tell ESLint where to lint. But how?
Edit:
According to the accepted answer, I now have this, which works! I want to share it in case someone else might want to take a look.
module.exports = function(grunt) {
'use strict';
var dictionary = {
'webroot' : 'app/webroot/**',
'html5' : 'app/webroot/js/some/path'
};
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
grunt.initConfig({
eslint : {
options : {
config : '.eslintrc'
},
target : ['<%= path %>']
}
});
grunt.registerTask('test', 'Lint a set of files', function(pathKey) {
pathKey = pathKey || 'webroot';
var path = (dictionary[pathKey] || pathKey) + '/*.js';
console.log('Parsed path as', path);
grunt.config.set('path', path);
grunt.task.run('eslint');
});
};
Save the value of your given path in the grunt config and refer to it:
module.exports = function(grunt) {
'use strict';
var dictionary = {
'all' : '**',
'html5' : 'some/path'
};
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
grunt.initConfig({
eslint : {
options : {
config : '.eslintrc'
},
target : ['hello/world/js/<%= dir %>/**.js']
}
});
grunt.registerTask('test', 'Lint a set of files', function(pathKey) {
var dir = dictionary[pathKey]
grunt.config.set('dir', dir );
grunt.task.run('eslint');
});
};
You can use grunt.option to pass arguments to the Gruntfile.
in the Gruntfile:
grunt.initConfig({
eslint : {
options : {
config : '.eslintrc'
},
target : ['hello/world/js/<%= grunt.option('path') %>/**.js']
}
});
from the CLI: grunt test --path=foo to get 'hello/world/js/foo/**.js'.

Resources