Karma unit test cases not getting executed - angularjs

Karma unit test cases not getting executed. There are no errors when I run the karma start my.conf.js command. There is nothing displayed in the DEBUG console. Can anyone tell what can be the issue?
Here is my controller file :
define('',['angular', 'moment', '../module'], function (ng, moment) {
'use strict';
ng
.module('PatientRecord.controllers')
.controller('PatientRecordController', ["$scope", "PatientRecordService", 'globalConfig',
function ($scope, PatientRecordService, globalConfig) {
$scope.addSubmitted = false;
$scope.updateSubmitted = false;
$scope.shareSubmitted = false;
$scope.deleteSubmitted = false;
$scope.patientRecords = [];
$scope.modalRecord = {};
$scope.sharedDoctors = [];
$scope.potentialDoctors = [];
$scope.medicalRecordsList = false;
$scope.disableShareButton = true;
$scope.validation = {
success:{
status:false,
message:""
},
error:{
status:false,
message:""
}
};
$scope.file = {};
var patientRecordService = new PatientRecordService();
$scope.getRecord = function () {
$scope.patientRecords.length = 0;
patientRecordService.getRecords().then(function (response) {
$scope.patientRecords = response;
if ($scope.patientRecords.length) {
$scope.medicalRecordsList = true;
}
});
$('body').tooltip({
selector: '.action-icon'
});
};
$scope.addPatientRecord = function ($event) {
$scope.addSubmitted =true;
$scope.patientRecord.shared = [];
$scope.patientRecord.file = $scope.addRecordFileUpload;
patientRecordService.addPatientrecorddata($scope.patientRecord)
.then(function (response) {
$scope.addSubmitted = false;
clearAddRecordFields();
$("#add-record").modal("hide");
$scope.getRecord();
if(response){
$scope.validation.success.status = true;
$scope.validation.success.message = "Record added successfully";
$scope.addForm.$setPristine();
$scope.addForm.addRecordFileUpload.$error.required = true;
$scope.patientRecord.medicalRecordTypeId ="";
$scope.addRecordFileUpload = "";
}else{
$scope.validation.error.status = true;
$scope.validation.error.message = "Confirmation is unsuccessful. Please try again";
}
});
};
$scope.closeAddDialog = function () {
clearAddRecordFields();
$("#add-record").modal("hide");
};
var clearAddRecordFields = function(){
$scope.patientRecord.name = "";
$scope.patientRecord.dateOfRecord = "";
$scope.patientRecord.comments = "";
$scope.patientRecord.medicalRecordType = "";
$scope.patientRecord.addRecordFileName = "";
$("#patientRecord_name").val("");
$("#dateOfRecord").val("");
$("#patientRecord_comments").val("");
$("#medicalRecordType").val("");
$("#addRecordFileName").html("");
}
var dispalyFileName = function (FileControlId, placeholderId) {
if ($scope.currntFileObject) {
$('#' + placeholderId).empty().html($scope.currntFileObject.name);
}
};
$scope.openupdateModal = function (record) {
$scope.modalRecord = _.clone(record);
var dateOfRecord = moment($scope.modalRecord.date_of_record).format("DD MMM, YYYY");
$scope.modalRecord.date_of_record = dateOfRecord;
$scope.disableShareButton = true;
$("#updateRecordFileName").html("");
//Get Shared Doctors Data
patientRecordService.getSharedDoctorsByRecordId(record.id).then(function (response) {
$scope.sharedDoctors = _.where(response, { isShared: true })
$scope.potentialDoctors = _.where(response, { isShared: false })
});
};
$scope.updatePatientrecord = function (index) {
$scope.updateSubmitted = true;
$scope.modalRecord.medicalRecordTypeId = $("#update_recordtype").val();
$scope.modalRecord.file = $scope.updateRecordFileUpload;
patientRecordService.updatePatientdata($scope.modalRecord)
.then(function (response) {
$scope.updateSubmitted = false;
$scope.getRecord();
});
};
angular.element("#selectDoctorToShare_foreditDialog").change(function () {
var selectedDoctorId = $("#selectDoctorToShare_foreditDialog").val();
$scope.$apply(function () {
if (selectedDoctorId != 0) {
$scope.disableShareButton = false;
} else {
$scope.disableShareButton = true;
}
});
});
$scope.closeUpdateDialog = function () {
$("#patientRecord_name").val("");
$("#datetimepicker1").val("");
$("#patientRecord_comments").val("");
$("#medicalRecordType").val("");
$("#addRecordFileName").html("");
$("#modify-record").modal("hide");
$scope.getRecord();
};
$scope.openShareDialog = function (data) {
$scope.modalRecord = data;
$scope.disableShareButton = true;
patientRecordService.getSharedDoctorsByRecordId(data.id)
.then(function (response) {
$scope.sharedDoctors = _.where(response, { isShared: true })
$scope.potentialDoctors = _.where(response, { isShared: false })
});
}
$scope.sharePatientRecord = function(doctorDropdownId,recordId){
$scope.shareSubmitted = true;
var selectedDoctorId = $("#"+doctorDropdownId).val();
patientRecordService.sharePatientData(recordId, selectedDoctorId).then(function(response){
$scope.shareSubmitted = false;
if(response){
if(doctorDropdownId == "selectDoctorToShare_forShareDialog") {
$("#share-record").modal("hide");
}
alert("Record shared successfully");
patientRecordService.getSharedDoctorsByRecordId($scope.modalRecord.id)
.then(function(response) {
$scope.sharedDoctors = _.where(response, {isShared: true})
$scope.potentialDoctors = _.where(response, {isShared: false})
});
$scope.disableShareButton = true;
} else {
alert("Something went wrong! Try again")
}
});
};
angular.element("#selectDoctorToShare_forShareDialog").change(function () {
var selectedDoctorId = $("#selectDoctorToShare_forShareDialog").val();
$scope.$apply(function () {
if (selectedDoctorId != 0) {
$scope.disableShareButton = false;
} else {
$scope.disableShareButton = true;
}
});
});
$scope.OpenDeleteModal = function (data, index) {
$scope.modalRecord = data;
$scope.index = index;
$("#delete-record-modal").modal("show");
}
$scope.deletePatientrecord = function (data, index) {
$scope.deleteSubmitted = true;
var patientRecordService = new PatientRecordService();
patientRecordService.deletePatientdata(data.id).then(function (response) {
$scope.deleteSubmitted = false;
$("#delete-record-modal").modal("hide");
$scope.getRecord();
if(response){
$scope.validation.success.status = true;
$scope.validation.success.message = "Record deleted successfully";
}else{
$scope.validation.error.status = true;
$scope.validation.error.message = "Record could not be deleted";
}
});
};
$scope.getRecord();
}
]);
});
Test file for controller:
// Testing PatientRecordController
define('',['angular', 'moment', '../module'], function (ng, moment) {
describe("Controller: PatientRecordController", function() {
// load the controller's module
beforeEach(module('PatientRecord.controllers'));
var PatientRecordController,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
PatientRecordController = $controller('PatientRecordController', {
'$scope': scope
});
}));
// Check if controller is defined
it("should have a PatientRecordController as controller", function() {
expect(PatientRecord.controllers.PatientRecordController).toBeDefined();
console.log('controllers defined');
});
});
});
my.conf.js file:
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine','requirejs'],
// list of files / patterns to load in the browser
files: [
'app/modules/PatientRecord/controllers/PatientRecordController.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress','coverage','html'],
htmlReporter: {
outputFile: 'tests/units.html'
},
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'src/**/*.js': ['coverage']
},
// optionally, configure the reporter
coverageReporter: {
type : 'html',
dir : 'coverage/',
file:'coverageds.txt'
},
// 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: ['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
});
};

The problem is in the files section of your karma configuration file. First, you need to include all your application's library dependencies (like Jquery, Angular, Bootstrap) if you are using any. Second, you need to include the files that you are testing. Include your application's initialization file (app.js) and submodules first. Last, you need to include that actual tests themselves. The order in which you include things does matter. A lot of people use RequireJS for this, but I don't think that's completely necessary unless you have a large and complex project.

Related

How to eliminate dead code elimination in React using only Gulp and Browserify?

I try to build my React project with gulpfile.js in production mode so the query developer tools show green color in browser tab. However, it still failed with dead code elimination error, which means development version is still detected in react developer tools.
I have already tried many ways to eliminate this error. One of the closest solution is to add 'unreachable-branch-transform' and gulpif argv in browserify part in gulpfile.js. Please check gulpfile.js content below.
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var clean = require('gulp-clean');
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var envify = require('envify/custom');
var replace = require('gulp-replace');
var gutil = require('gulp-util');
var uglifyCSS = require('gulp-uglifycss');
var uglifyJS = require('gulp-uglify');
var version_append = require('gulp-version-append');
var connect = require('gulp-connect');
var historyApiFallback = require('connect-history-api-fallback');
var workboxBuild = require('workbox-build');
var prefixer = require('autoprefixer');
var postcss = require('gulp-postcss');
var concat = require('gulp-concat');
var less = require('gulp-less');
var chalk = require("chalk");
var path = require('path');
var exec = require('child_process').exec;
var paths = {
public_view_src : "view/",
public_view_dest : "public/",
images: 'img/**/*',
css :
[
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/font-awesome/css/font-awesome.min.css",
"node_modules/animate.css/animate.min.css",
"node_modules/lato-font/css/lato-font.min.css"
],
js :
{
plugins: [
"node_modules/clientjs/dist/client.min.js",
"node_modules/jquery.payment/lib/jquery.payment.min.js"
],
vendor: [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
react : ["./src/app.js", "./src/**/*.js"],
app: "./script/*.js",
register_service_worker: 'service_worker/register_service_worker.js'
},
fonts : [
"node_modules/font-awesome/fonts/**/*",
"node_modules/bootstrap/dist/fonts/**/*"
],
less : ["less/style.less", "less/**/*.less", "node_modules/roboto-fontface-pre-css/css/roboto-fontface.less"],
service_worker: 'service_worker/service-worker.js'
};
function build_service_worker() {
console.info('Workbox libraries copying started.');
return workboxBuild.copyWorkboxLibraries(paths.public_view_dest).then((workboxDirectoryName) => {
console.info('Workbox libraries copied to: ' + workboxDirectoryName);
return workboxBuild.injectManifest({
swSrc: `${paths.service_worker}`,
swDest: `${paths.public_view_dest}/service-worker.js`,
maximumFileSizeToCacheInBytes: 50000000,
globDirectory: paths.public_view_dest,
globPatterns: ['**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'],
globIgnores: ['service-worker.js', 'manifest.json'].concat([`**/workbox*/*.js*`])
}).then((result) => {
result.warnings.forEach(console.warn);
console.info(`${result.count} files will be precached, totaling ${result.size} bytes.`);
console.info(`import ${paths.public_view_dest}${workboxDirectoryName}/workbox-sw.js to service-worker-script`);
gulp.src(`${paths.public_view_dest}/service-worker.js`)
.pipe(replace('#workbox-sw', `${workboxDirectoryName}/workbox-sw.js`))
.pipe(gulp.dest(paths.public_view_dest));
console.info('Service worker generation completed.');
});
}).catch((error) => {
console.warn('Workbox lbraries copying failed: ' + error);
});
}
// map error
function map_error(err) {
if (err.fileName) {
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(err.fileName.replace(__dirname, ''))
+ ': '
+ 'Line '
+ chalk.magenta(err.lineNumber)
+ ' & '
+ 'Column '
+ chalk.magenta(err.columnNumber || err.column)
+ ': '
+ chalk.blue(err.description));
} else {
var message = err.message.replace(__dirname + "/", "");
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(message));
}
this.emit('end');
}
function prevent_cache_assets(){
return function(){
return gulp.src(path.join(__dirname, paths.public_view_src + '*.html'))
.pipe(version_append(['html', 'js', 'css'],
{
appendType: 'timestamp',
versionFile: 'version.json'
}))
.pipe(gulp.dest(paths.public_view_dest));
};
}
function reactScript(watch) {
var bundler, rebundle;
bundler = browserify(paths.js.react[0], {
basedir: __dirname,
// debug: watch,
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: watch, // required to be true only for watchify
debug: argv.production ? false : true
});
if(watch) {
bundler = watchify(bundler);
}
bundler.transform('unreachable-branch-transform', {
global: true
});
bundler.transform(envify({
_: 'purge',
MODE: process.env.MODE
}));
bundler.transform(babelify.configure({
"plugins": ["object-assign"]
}));
rebundle = function() {
console.log("packing react");
var stream = bundler.bundle();
stream.on('error', map_error);
stream = stream.pipe(source('app.min.js'));
if(!watch) {
stream = stream.pipe(gulpif(argv.production, buffer()));
//stream = stream.pipe(uglifyJS());
}
return stream.pipe(gulp.dest('public/assets/dist'));
};
bundler.on('update', rebundle);
bundler.on('log', gutil.log);
return rebundle();
}
function es(){
return gulp.src('public/assets/dist/app.min.js')
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/dist'));
}
gulp.task('mini', es);
// task for stage or production
gulp.task('min', ['js', 'vendor', 'less', 'copyfonts', 'prevent_cache_assets']);
// init task
gulp.task('init', ['js', 'vendor', 'less', 'copyfonts', 'watch', 'prevent_cache_assets'], function () {
gulp.watch([paths.public_view_src + '**\/*', paths.service_worker, paths.public_view_dest + 'assets/**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'], ['build-service-worker']);
return build_service_worker();
});
// imagemin
gulp.task('clean-images-dest', function(){
return gulp.src('public/assets/img', {read: false})
.pipe(clean());
});
gulp.task('images', ['clean-images-dest'], function(){
return gulp.src(paths.images)
.pipe(imagemin())
.pipe(gulp.dest('public/assets/img'));
});
// react
gulp.task('react', function () {
return reactScript(false);
});
// copy fontawesome fonts task
gulp.task('copyfonts', function() {
return gulp.src(paths.fonts)
.on('error', map_error)
.pipe(gulp.dest('public/assets/css/fonts'));
});
// less task
gulp.task('less', ['images'], function(){
var l = less();
l.on('error', map_error);
return gulp.src(paths.less[0])
.pipe(l)
.pipe(postcss([prefixer({ browsers: ["> 0%"] })]))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css'));
});
// copy lato fonts
gulp.task('cp-myriad-font', function(){
return gulp.src(['./node_modules/myriad-font/fonts/myriad/myriad-set-pro_text.woff', './node_modules/myriad-font/fonts/myriad/myriad-set-pro_bold.woff'])
.pipe(gulp.dest('public/assets/css/fonts'));
});
// vendor task
gulp.task('vendor', ['cp-myriad-font'], function(){
return gulp.src(paths.css)
.on('error', map_error)
.pipe(concat('vendor.css'))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css/vendor'));
});
// prevent cache task
gulp.task('prevent_cache_assets', prevent_cache_assets());
// javascript task
gulp.task('js', ['js_vendor', 'js_plugins', 'js_register_service_worker'], function(){
return gulp.src(paths.js.app)
.on('error', map_error)
.pipe(concat('app.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_vendor', function(){
return gulp.src(paths.js.vendor)
.on('error', map_error)
.pipe(concat('vendor.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_plugins', function(){
return gulp.src(paths.js.plugins)
.on('error', map_error)
.pipe(concat('plugins.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_register_service_worker', function(){
return gulp.src(paths.js.register_service_worker)
.on('error', map_error)
.pipe(concat('register_service_worker.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
// task to run api
gulp.task('api', function(cb){
exec('cd ../mp-wallet-api && nodemon', function(err, stdout, stderr){
console.log(stdout);
console.log(stderr);
cb(err);
});
});
// watcher
gulp.task('watch', function(){
gulp.watch(paths.less, ['less']);
gulp.watch(paths.js.app, ['js']);
gulp.watch(paths.js.plugins, ['js']);
gulp.watch(paths.js.vendor, ['js']);
gulp.watch(paths.js.register_service_worker, ['js']);
gulp.watch(paths.css, ['vendor']);
gulp.watch(paths.fonts, ['copyfonts']);
gulp.watch(paths.public_view_src + '*.html', ['prevent_cache_assets']);
return reactScript(true);
});
gulp.task('connect', function() {
connect.server({
port: 3000,
root: [paths.public_view_dest],
middleware: function(connect, opt){
return [historyApiFallback({})];
},
fallback: 'index.html'
});
connect.serverClose();
});
gulp.task('set-production-env', function() {
return process.env.NODE_ENV = 'production';
});
gulp.task('default', ['set-production-env', 'init']);
gulp.task('serve', ['set-production-env', 'init', 'connect']);
gulp.task('with-api', ['set-production-env', 'api', 'init']);
gulp.task('build-service-worker', function () {
return build_service_worker();
});
My React project is only using gulp and browserify inside gulpfile.js, so this project doesn't use any build tools listed in documentation link below (grunt, webpack, browserify (standalone),rollup).
https://reactjs.org/docs/optimizing-performance.html
Do you have any suggestion how to eliminate dead code elimination, but only by using gulp and browserify inside it ? Thanks in advance.

Requried is not defined, after migrating from Gulp 3 to 4

I have a project which used Gulp 3 + Node 11 (The project is AngularJS with the basic webpack + babel etc ...).
The need arose to migrate to Gulp 4 + Node 12. I changed the syntax from Gulp 3 to 4, the command "gulp build" is running, the console appears that everything is ok.
But when I try to access the application it says that:
Uncaught ReferenceError: require is not defined
at eval (eval at globalEval (jquery.js:2)
This error is repeated with other libs as well.
Below a part of my gulp.js, the calls part, probably the error is here. I think I'm getting complicated in this business of having to force sync on gulp 4, which I didn't have on Gulp 3.
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var simplevars = require('postcss-simple-vars');
var nested = require('postcss-nested');
var mqPacker = require('css-mqpacker');
var cssnano = require('cssnano');
var cssimport = require('postcss-import');
var usemin = require('gulp-usemin');
var fs = require('graceful-fs');
var open = require('open');
var rename = require('gulp-rename');
var minifyCss = require('gulp-clean-css');
// var gulpsync = require('gulp-sync')(gulp);
var express = require('express');
var uglify = require('gulp-uglify');
// /* ES6 */
var replace = require('gulp-replace');
var gulpif = require('gulp-if');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');
var babelify = require('babelify');
var _ = require('lodash');
var through = require('through');
var livereload = require('gulp-livereload');
var fn = require('gulp-fn');
var notify = require('gulp-notify');
var templateCache = require('gulp-angular-templatecache');
function ErrorHandler() {
var args = Array.prototype.slice.call(arguments);
notify.onError({
title: "Compile Error",
message: "<%= error.message %>"
}).apply(this, args);
this.emit('end');
};
var envConfig = process.env.CONFIG || 'development';
var filename = envConfig + '.json';
var settings = JSON.parse(fs.readFileSync('./config/' + filename, 'utf8'));
var isMinify = !!settings.minify;
settings.buildVersion = new Date().getTime();
var PORT = process.env.PORT || 3000;
var PATH = {
js: {
src: 'src/**/*.js',
dest: 'build'
},
styles: {
src: 'src/core/styles/common.css',
srcWatch: 'src/**/*.css',
dest: 'build/core/styles/'
},
images: {
src: ['src/**/*.png', 'src/**/*.jpg', 'src/**/*.svg', 'src/**/*.pdf', 'src/**/*.ico'],
dest: 'build'
},
fonts: {
src: ['src/core/fonts/**/*.eot', 'src/core/fonts/**/*.ijmap', 'src/core/fonts/**/*.svg', 'src/core/fonts/**/*.ttf', 'src/core/fonts/**/*.woff', 'src/core/fonts/**/*.woff2'],
dest: 'build'
},
fontsAwesome: {
src: ['node_modules/font-awesome/fonts/*.*'],
dest: 'build/lib/fonts'
},
html: {
src: 'src/**/*.html',
dest: 'build'
},
usemin: {
src: 'src/index.tmpl',
dest: 'build'
},
windows: {
srcPaste: '../../../inetpub/wwwroot/app',
srcCopy: 'build/**/*.*',
srcWebConfig: 'web.config'
}
};
function replaceKeys() {
return replace(/(#{2}[A-z,0-9]+)/g, function (key) {
return settings[key.slice(2)];
});
}
async function compileTemplateIndex() {
gulp
.src(PATH.usemin.src)
.pipe(rename('index.html'))
.pipe(replaceKeys())
.pipe(usemin({
assetsDir: '.',
css: ['concat'],
js: ['concat']
}))
.pipe(gulp.dest(PATH.usemin.dest));
}
async function copyFonts() {
gulp
.src(PATH.fonts.src)
.pipe(gulp.dest(PATH.fonts.dest));
}
async function copyFontsAwesome() {
gulp
.src(PATH.fontsAwesome.src)
.pipe(gulp.dest(PATH.fontsAwesome.dest));
}
async function copyImages(done) {
gulp
.src(PATH.images.src)
.pipe(gulp.dest(PATH.images.dest));
done()
}
async function copyImagesUI() {
gulp
.src('bower_components/jquery-ui/themes/base/images/**/*')
.pipe(gulp.dest('build/lib/css/images'));
}
async function compileHtml() {
return gulp.src(PATH.html.src)
.pipe(replaceKeys())
.pipe(templateCache({
standalone: true
}))
.pipe(gulp.dest(PATH.html.dest));
}
async function compilePostCss() {
var processors = [
cssimport,
simplevars,
nested,
mqPacker,
autoprefixer
];
if ( isMinify ) processors.push(cssnano({
discardComments: {
removeAll: true
},
zindex: false
}));
return gulp
.src(PATH.styles.src)
.pipe(postcss(processors))
.pipe(gulp.dest(PATH.styles.dest));
}
function transformKeys(file) {
var data = '';
return through(write, end);
function write(buf) {
data += buf
}
function end() {
data = data.replace(/(#{2}[A-z,0-9]+)/g, function (key) {
return settings[key.slice(2)];
})
this.queue(data);
this.queue(null);
}
}
async function compileEs6() {
compileEs6_Bundle(false, './src/app.js', 'app.js');
// compileEs6_Bundle(false, './src/components/components.module.js', 'components.js');
// compileEs6_Bundle(false, './src/modules/modules.module.js', 'modules.js');
}
function compileEs6_watch() {
compileEs6_Bundle(true, './src/app.js', 'app.js');
// compileEs6_Bundle(true, './src/components/components.module.js', 'components.js');
// compileEs6_Bundle(true, './src/modules/modules.module.js', 'modules.js');
}
function compileEs6_Bundle(watch, src, dest) {
var bro;
var src = src || './src/app.js';
var dest = dest || 'app.js';
if (watch) {
livereload.listen();
bro = watchify(browserify(_.assign(watchify.args, {
entries: [src],
debug: true
})));
bro.on('update', function (file) {
console.log(file + ' changed');
rebundle(bro);
});
} else {
bro = browserify(src, {
debug: true
});
}
bro.transform(babelify.configure({
compact: false,
presets: ['#babel/env'],
}));
bro.transform(transformKeys);
function rebundle(bundler) {
return bundler.bundle()
.on('error', ErrorHandler)
.pipe(source(dest))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write())
.pipe(gulpif(isMinify,
uglify({
mangle: false
})
))
.pipe(gulp.dest('./build'))
.pipe(gulpif(watch, fn(
function () {
livereload.reload();
openServer();
}
)));
}
return rebundle(bro);
}
async function watch() {
livereload.listen();
function livereloadNotify(e) {
livereload.changed(e.path);
}
var onChanged = _.debounce(livereloadNotify, 600);
/* listen js files */
compileEs6_watch();
gulp.watch(PATH.images.src, gulp.series(['copy-images'])).on('change', onChanged);
gulp.watch(PATH.styles.srcWatch, gulp.series(['postcss'])).on('change', onChanged);
gulp.watch(PATH.html.src, gulp.series(['html'])).on('change', onChanged);
gulp.watch(PATH.usemin.src, gulp.series(['compile-template-index'])).on('change', onChanged);
}
async function webserver() {
var app = express();
app.use(express.static('build'));
var server = app.listen(PORT, function () {
console.log('Listening on port %d', PORT);
});
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/build/index.html');
});
}
function openServer() {
//open('http://localhost:'+ PORT +'/');
//openServer = function () {};
}
function copyFilesToBuildFolder() {
function rmDir(dirPath) {
try { var files = fs.readdirSync(dirPath); }
catch(e) { return; }
if (files.length > 0){
for (var i = 0; i < files.length; i++) {
var filePath = dirPath + '/' + files[i];
if (fs.statSync(filePath).isFile()){
fs.unlinkSync(filePath);
} else {
rmDir(filePath);
}
}
}
fs.rmdirSync(dirPath);
}
rmDir(PATH.windows.srcPaste);
gulp
.src(PATH.windows.srcCopy)
.pipe(gulp.dest(PATH.windows.srcPaste));
gulp
.src(PATH.windows.srcWebConfig)
.pipe(gulp.dest(PATH.windows.srcPaste));
}
gulp.task('compile-es6', compileEs6);
gulp.task('compile-template-index', compileTemplateIndex);
gulp.task('copy-images', copyImages);
gulp.task('copy-fonts', copyFonts);
gulp.task('copy-fonts-awesome', copyFontsAwesome);
gulp.task('copy-images-ui', copyImagesUI);
gulp.task('html', compileHtml);
gulp.task('postcss', compilePostCss);
gulp.task('watch', watch);
gulp.task('server', webserver);
gulp.task('copy-files-to-build-folder', copyFilesToBuildFolder);
gulp.task('build', gulp.series(['copy-fonts','copy-fonts-awesome','copy-images-ui','postcss','copy-images','compile-template-index','html','compile-es6']));
gulp.task('serve', gulp.series(['build','server','watch']));
// gulp.task('build-sv-windows', gulpsync.sync(['build', 'copy-files-to-build-folder']));

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

setting proxy or backend URL while doing gulp build:dist

We have some code in Angular JS which is build using gulp (babel).
We have necessity to redirect the api service calls to a different server.
Hence, which development we run gulp server and with that add the api-host server in the proxy argument while running gulp server, as follows:
gulp serve:dist --mock no --proxy http://<host-name>:8090
Now, after development, we build and distribute the same bundle to different host (not the same host where the api services are hosted). Now we are not able to connect to the api server. The command we use to build is
gulp build:dist --mock no
Even if we add the proxy argument here, it doesn't works.
gulp build:dist --mock no --proxy http://<host-name>:8090
We tried customizing the "gulpfile.babel.js" file. but no result.
The following is the "gulpfile.babel.js" used:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');
var _ = require('lodash');
var historyApiFallback = require('connect-history-api-fallback');
var path = require('path');
var args = require('yargs').argv;
var proxyMiddleware = require('http-proxy-middleware');
var merge = require('merge-stream');
// browserSync
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// config & testing
var config = require('./build/build.config.js');
var protractorConfig = require('./build/protractor.config.js');
var karmaConfig = require('./build/karma.config.js');
var KarmaServer = require('karma').Server;
var pkg = require('./package');
/* jshint camelcase:false*/
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);
// util functions
function sortModulesFirst(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a.path);
var bMod = module.test(b.path);
// inject *.module.js first
if (aMod === bMod) {
// either both modules or both non-modules, so just sort normally
if (a.path < b.path) {
return -1;
}
if (a.path > b.path) {
return 1;
}
return 0;
} else {
return (aMod ? -1 : 1);
}
}
// serve app in dev mode or prod mode
function serverOptions(logPrefix) {
var proxy = args.proxy;
var options = {
notify: false,
logPrefix: pkg.name,
server: {
baseDir: ['build', 'client']
}
};
// use a proxy server to serve '/api/**'' and '/auth' routes
if (proxy && args.mock === 'no') {
options.server.middleware = [
proxyMiddleware(['/auth', '/api'], {
target: proxy
}),
historyApiFallback()
];
} else {
// use Angular's $httpBackend as the server
options.server.middleware = [
historyApiFallback()
];
}
if (logPrefix) {
options.logPrefix = pkg.name;
}
return options;
}
// run unit tests and watch files
gulp.task('tdd', function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: false,
action: 'watch',
browsers: ['PhantomJS']
}), cb).start();
});
// run unit tests with travis CI
gulp.task('travis', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true,
browsers: ['PhantomJS']
}), cb).start();
});
// optimize images and put them in the dist folder
gulp.task('images', function() {
return gulp.src(config.images, {
base: config.base
})
.pipe($.imagemin({
progressive: true,
interlaced: true
}))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'images'
}));
});
//generate angular templates using html2js
gulp.task('templates', function() {
return gulp.src(config.tpl)
.pipe($.changed(config.tmp))
.pipe($.html2js({
outputModuleName: 'templates',
base: 'client',
useStrict: true
}))
.pipe($.concat('templates.js'))
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'templates'
}));
});
//generate css files from scss sources
gulp.task('sass', function() {
return gulp.src(config.mainScss)
.pipe($.sass())
.pipe($.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.on('error', $.sass.logError)
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'sass'
}));
});
//generate a minified css files, 2 js file, change theirs name to be unique, and generate sourcemaps
gulp.task('html', function() {
let useminConfig = {
path: '{build,client}',
css: [$.csso(), $.rev()],
vendorJs: [$.uglify({
mangle: false
}), $.rev()],
mainJs: [$.ngAnnotate(), $.uglify({
mangle: false
}), $.rev()]
};
if (args.mock === 'no') {
// Don't include mock vendor js
useminConfig.mockVendorJs = [];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe($.replace('<script src="assets/js/mock-vendor.js"></script>', ''))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
} else {
// Include mock vendor js
useminConfig.mockVendorJs = [$.uglify({
mangle: false
}), $.rev()];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
}
});
// clean up mock vendor js
gulp.task('clean:mock', function(cb) {
if (args.mock === 'no') {
let paths = [path.join(config.dist, 'assets/js/mock-vendor.js')];
del(paths).then(() => {
cb();
});
} else {
cb();
}
});
//copy assets in dist folder
gulp.task('copy:assets', function() {
return gulp.src(config.assets, {
dot: true,
base: config.base
})
//.pipe(gulp.dest(config.dist + '/assets'))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy:assets'
}));
});
//copy assets in dist folder
gulp.task('copy', function() {
return gulp.src([
config.base + '/*',
'!' + config.base + '/*.html',
'!' + config.base + '/src',
'!' + config.base + '/test',
'!' + config.base + '/bower_components'
])
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy'
}));
});
//clean temporary directories
gulp.task('clean', del.bind(null, [config.dist, config.tmp]));
//lint files
gulp.task('jshint', function() {
return gulp.src(config.js)
.pipe(reload({
stream: true,
once: true
}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// babel
gulp.task('transpile', function() {
return gulp.src(config.js)
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015']
}))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(
path.join(config.tmp, 'src')
));
});
// inject js
gulp.task('inject:js', () => {
var injectJs = args.mock === 'no' ?
config.injectJs :
config.injectJs.concat(config.mockJS);
return gulp.src(config.index)
.pipe($.inject(
gulp
.src(injectJs, {
read: false
})
.pipe($.sort(sortModulesFirst)), {
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<script src="' + filepath.replace('/client', 'tmp') + '"></script>'
}))
.pipe(gulp.dest(config.base));
});
/** ===================================
build tasks
======================================*/
//build files for development
gulp.task('build', ['clean'], function(cb) {
runSequence(['sass', 'templates', 'transpile', 'inject:js'], cb);
});
//build files for creating a dist release
gulp.task('build:dist', ['clean'], function(cb) {
//runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images', 'test:unit'], 'html', cb);
runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images'], 'html', 'clean:mock', cb);
});
// For aniden internal usage
// changed app root for labs server
gulp.task('labs:aniden', function() {
let base = `/hpe/mvno_portal/build/v${pkg.version}/`;
let html = gulp.src(config.dist + '/index.html', {
base: config.dist
})
.pipe($.replace('<base href="/">', `<base href="${base}">`))
.pipe(gulp.dest(config.dist));
let css = gulp.src(config.dist + '/**/*.css', {
base: config.dist
})
.pipe($.replace('url(/', `url(${base}`))
.pipe($.replace('url("/', `url("${base}`))
.pipe(gulp.dest(config.dist));
let js = gulp.src(config.dist + '/**/*.js', {
base: config.dist
})
.pipe($.replace('href="/"', `href="${base}"`))
.pipe(gulp.dest(config.dist));
return merge(html, css, js);
});
/** ===================================
tasks supposed to be public
======================================*/
//default task
gulp.task('default', ['serve']); //
//run unit tests and exit
gulp.task('test:unit', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true
}), cb).start();
});
// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
return gulp.src(protractorConfig.config.specs)
.pipe($.protractor.protractor({
configFile: 'build/protractor.config.js'
}))
.on('error', function(e) {
throw e;
});
});
//run the server, watch for file changes and redo tests.
gulp.task('serve:tdd', function(cb) {
runSequence(['serve', 'tdd'], cb);
});
//run the server after having built generated files, and watch for changes
gulp.task('serve', ['build'], function() {
browserSync(serverOptions());
gulp.watch(config.html, reload);
gulp.watch(config.scss, ['sass', reload]);
gulp.watch(config.js, ['jshint', 'transpile']);
gulp.watch(config.tpl, ['templates', reload]);
gulp.watch(config.assets, reload);
});
//run the app packed in the dist folder
gulp.task('serve:dist', ['build:dist'], function() {
browserSync(serverOptions());
});
You can use gulp-ng-config to add constant in you app module.
Or you a JSON as a config file inside your gulp:
//Gulp file
var fs = require('fs');
var settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
....
gulp.task('statics', g.serve({
port: settings.frontend.ports.development,
...
}));
gulp.task('production', g.serve({
port: settings.frontend.ports.production,
root: ['./dist'],
...
}));

Cordova/Ionic httpd server plugin - url not visible

i have a problem with Angular controller in my Ionic/Cordova project.
Can someone explain me why url which i get in line 25: $scope.serverURL=url;
isn't visible in line 63 alert($scope.serverURL); (it return null)?
Here is my controller:
var app = angular.module('iremotee');
app.controller('StreamingController', function(ConnectSdkService, $scope, $rootScope, $state, Camera) {
var options = {
quality: 100,
destinationType: 0,
sourceType: 0,
mediaType: 2
};
$scope.currentFile = null;
$scope.httpd = null;
$scope.serverURL = null;
alert($scope.serverURL + "!!!");
$scope.createHttpd = function() {
$scope.httpd = (cordova && cordova.plugins && cordova.plugins.CorHttpd) ? cordova.plugins.CorHttpd : null;
};
$scope.startMediaServer = function() {
if ($scope.httpd) {
// before start, check whether its up or not
$scope.httpd.getURL(function(url) {
if (url.length > 0) {
$scope.serverURL = url;
alert($scope.serverURL);
} else {
$scope.httpd.startServer({
'www_root': '/',
'port': 8080,
'localhost_only': false
}, function(url) {
$scope.serverURL = url;
alert($scope.serverURL);
}, function(error) {});
}
});
} else {}
};
$scope.stopServer = function() {
if ($scope.httpd) {
$scope.httpd.stopServer(function() {}, function(error) {});
}
};
$scope.getMedia = function() {
$state.go('mainmenu');
};
ionic.Platform.ready(function() {
$scope.createHttpd();
$scope.startMediaServer();
});
$scope.getFile = function() {
alert($scope.serverURL);
Camera.getFromMemory(options).then(function(URI) {
if (URI.indexOf("file://") == -1) {
URI = "file://" + URI;
}
window.resolveLocalFileSystemURL(URI, function(fileEntry) {
var URI = fileEntry.toURL();
var str = URI;
str = str.replace("file:///storage/emulated/0/", "/sdcard/");
str = str.replace("file:///storage/emulated/0/", "/sdcard1/");
str = str.replace("file:///storage", "");
Camera.currentURI = str;
alert(Camera.currentURI);
$scope.currentFile = Camera.currentURI;
}); //resolveLocalFileSystemURL-END
}, function(err) {
alert(err);
}); //getFromMemory-END
}; //getFile-END
$scope.$on('$destroy', function() {
$scope.stopServer();
});
});

Resources