Karma test won't run - karma-runner

Please help. I am new to testing with karma. When I run "karma start karma.local.conf.js" the Chrome browser window comes up but the test doesn't run. I think my app.js and my test.js are ok and I suspect that the issue is incorrect versions of the packages I'm loading in my package.json. I know I also need to include mocha and chai:
{
"devDependencies": {
"browserify": "10.2.3",
"gulp": "3.8.11",
"gulp-browserify": "0.5.1",
"karma": "0.12.16",
"karma-chai": "0.1.0",
"karma-chrome-launcher": "0.1.4",
"karma-mocha": "0.1.4",
"http-status": "0.1.8",
"underscore": "1.5.2"
}
}
Here is my karma.local.conf.js file:
module.exports = function(config) {
config.set({
files: [
'http://code.jquery.com/jquery-1.11.3.js',
'https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js',
// For ngMockE2E
'https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-mocks.js',
'./app.js',
'./test.js'
],
frameworks: ['mocha', 'chai'],
browsers: ['Chrome'],
proxies : {
'/': 'http://localhost:3000'
}
});
};
I can also post the app.js and the test.js if need be, but I think they are ok. I think the issue is in the package.json and getting the right versions of the npm packages I need.
Here is my app.js:
var app = angular.module('myApp', ['ng']);
app.directive('userMenu', function() {
return {
controller: 'MyHttpController',
template: '<div class="user" ng-show="user">' +
' Current User: {{user.profile.username}}' +
'</div>' +
'<div ng-show="!user">' +
' <a href="/auth/facebook">' +
' Log In' +
' </a>' +
'</div>'
}
});
app.controller('MyHttpController', function($scope, $http) {
$http.get('/api/v1/me').success(function(data) {
$scope.user = data.user;
});
});
Here is my test.js:
describe('Nav Bar', function() {
var injector;
var element;
var scope;
var compiler;
var httpBackend;
beforeEach(function() {
injector = angular.injector(['myApp', 'ngMockE2E']);
intercepts = {};
injector.invoke(function($rootScope, $compile, $httpBackend) {
scope = $rootScope.$new();
compiler = $compile;
httpBackend = $httpBackend;
});
});
it('shows logged in users name', function(done) {
httpBackend.expectGET('/api/v1/me').respond({
user: { profile: { username: 'John' } }
});
element = compiler('<user-menu></user-menu>')(scope);
scope.$apply();
httpBackend.flush();
assert.notEqual(element.find('.user').css('display'), 'none');
assert.equal(element.find('.user').text().trim(), 'Current User: John');
done();
});
});
Thanks in advance,
William

Here is what I did to get my tests to run:
1. Run "npm install <package name> without a version number for each package in my package.json file
2. Run "karma init" to create a new config file. By default this command creates karma.conf.js
3. Modify karma.conf.js with the information from karma.local.conf.js
4. Run "karma start". By default this command looks for a file named karma.conf.js (I had already run "npm install -g karma-cli" so I was able to run "karma start" without specifying a path
5. Next I will run "npm ls" to see what package versions were installed and create a new version of package.json for future projects.
Another solution might be to run "npm install" and then run "ncu -u" to update all the packages to the latest versions. That might work but I haven't tested it.

Related

How can I copy JSON files in Ionic 5

I have JSON files (es.json, en.json, ch.json) in "src\app\submodules\submodule1_src\assets\i18n".
I need that when doing "ionic build", these JSON files are copied to "src\assets\i18n\submodule1_src" automatically. In Ionic 3 this was done with #ionic/app-scripts, but it is discontinued.
I solved the problem as follows:
Add in 'ionic.config.json':
"hooks": {
"build:before": "./scripts/build-before.js"
},
And the content of 'build-before.js':
var fs = require('fs');
module.exports = function() {
fs.copyFile(
'src/app/submodules/submodule1/assets/i18n/es.json',
'src/assets/i18n/submodule1/es.json',
(err) => {});
}

Trying to write a vuepress plugin

(The doc on writing a plugin is pretty sparse...)
THE GOAL
Create a plugin to add headers to a page.
THE ATTEMPT
Created a plugin following guidelines and an example plugin (that presumably works...) to do something similar.
THE ISSUE
Plugin won't load.
config.js
plugins: [
[
'vuepress-plugin-headertags',
{ headerTags: ["<script src='https://cdn.jsdelivr.net/npm/netlify-identity-widget#1.5.2/build/netlify-identity-widget.min.js'></script>"]}
]
],
(the <script> tag is what I'm trying to insert, in this instance.
PLUGIN index.js
const { path } = require('path')
// was: const { path } = require('#vuepress/shared-utils')
// dunno. No documentation on this...
// got the current version from the 'default-theme' code
module.exports = (options) => ({
define () {
return {
headerTags: options.headerTags || []
}
},
enhanceAppFiles () {
return [path.resolve(__dirname, 'enhanceAppFile.js')]
},
globalUIComponents: ['HeaderTags']
})
PLUGIN INSTALLATION
I published it to npm as vuepress-plugin-headertags, and then installed it with:
yarn add -D vuepress-plugin-headertags
Here's the relevant package.json content:
{
"name": "vuepress-netlifycms",
"version": "0.0.0",
"scripts": {
"dev": "vuepress dev",
"build": "vuepress build",
"debug": "node --nolazy --inspect=9229 /home/rickb/.yarn/bin/vuepress build"
},
"devDependencies": {
"vuepress": "^0.14.8",
"vuepress-plugin-headertags": "^1.0.3"
},
"dependencies": {}
}
VUEPRESS INSTALLATION
I cloned the vuepress repo from git and did a yarn link, which makes it globally available. With that, I can trace it in the debugger via the 'debug' script.
TRACING
I've followed the VP source code in the debugger and get to resolvePathPackage() in moduleResolver.js. The incoming path is not correct:
/home/(...)/VuePress-NetlifyCMS/vuepress-plugin-headertags
It should be:
/home/(...)/VuePress-NetlifyCMS/node_modules/vuepress-plugin-headertags
At any rate, it doesn't resolve, even after the 'normalization' process.
MORE EYES
I need more eyes on this to help me figure it out. The project is already up on github as 'rickbsgu/VuePress-NetlifyCMS.git'. If you do an install, the plugin will be in the project directory under 'node_modules/vuepress-plugin-headertags'
Any thoughts appreciated
And it works, now. Two problems:
Version I was running/debugging was not the same as the version in package.json. There is the vuepress executable and the vuepress libraries the plugin requires. The library was always the older version at runtime.
I needed to change the path import in index.html from const { path } = require('path') to const { path } = require('#vuepress/shared-utils'). That's my doc issue - I don't see that documented anywhere.
Thanks #Sun Haoran for getting me to look in the right place.

electron-builder cannot find git repository although specifying

package.json
{
//some other config
"repository": "git#gitintsrv.domain.com/UserName/RepoName",
"scripts": {
"build": "build --win",
"ship": "build --win -p always"
}
}
electron-builder.yml
appId: com.xorchat.app.windows
publish:
provider: github
token: some_token
electron.js
const { app, BrowserWindow, ipcMain } = require('electron');
const { autoUpdater } = require("electron-updater");
let win; // this will store the window object
// creates the default window
function createDefaultWindow() {
win = new BrowserWindow({ width: 900, height: 680 });
win.loadURL(`file://${__dirname}/src/index.html`);
win.on('closed', () => app.quit());
return win;
}
// when the app is loaded create a BrowserWindow and check for updates
app.on('ready', function() {
createDefaultWindow()
autoUpdater.checkForUpdates();
});
// when the update has been downloaded and is ready to be installed, notify the BrowserWindow
autoUpdater.on('update-downloaded', (info) => {
win.webContents.send('updateReady')
});
// when receiving a quitAndInstall signal, quit and install the new version ;)
ipcMain.on("quitAndInstall", (event, arg) => {
autoUpdater.quitAndInstall();
})
When i am running npm run build i am receiving this error.
Error: Cannot detect repository by .git/config. Please specify "repository" in the package.json (https://docs.npmjs.com/files/package.json#repository).
Please see https://electron.build/configuration/publish
Where is the error?
I know it's probably too late, but in case you end up here as I did, here's how I solved it:
Add this to your package.json
"build": {
"publish": [{
"provider": "github",
"host": "github.<<DOMAIN>>.com",
"owner": "<<USER>>",
"repo": "<<NAME OF YOUR REPO (ONLY THE NAME)>>",
"token": "<<ACCESS TOKEN>>"
}]
}
I think the issue is that electron cannot parse corporate github urls, or something.
*********** EDIT:
Make a electron-builder.yml in the root folder, with the following content
appId: com.corporate.AppName
publish:
provider: github
token: <<ACCESS TOKEN>>
host: github.corporate.com
owner: <<User/ Org>>
repo: <<repo name>>
Don't forget to include this file on your .gitignore
This use to be a specific issue with Electron Builder 19x, and it has since been fixed:
https://github.com/electron-userland/electron-builder/issues/2785

access browserify -r params in karma

I call browserify with npm from the package.json scripts block. Here's an abbreviated version of the script.
"build:js": "browserify -r ./config.js:config -e -d src/index.js > build/index.js"
Everything works great. Inside index.js, I just refer to this parameter using: require('config') and browserify does the rest.
Now I'm trying to set up karma with browserify for testing, and karma-browserify can't find that variable. I've looked around and haven't found much, but tried to add require: ['./src/app/config/config-dev.js'] to my karma.conf.js inside the browserify object, like so:
browserify: {
debug: true,
require: ['./src/app/config/config-dev.js']
}
But karma doesn't make the connection between the require statement in the index to the parameter file, if nothing else, then because it isn't named. What I need to know is the syntax for karma when I use browserify CLI to add a param.
Any pointers to documentation explaining this or ideas about what I could try here would be super helpful. Thanks!
Try adding your require resolution to your package.json under the "browser" field.
E.g.:
"browser": {
"config": "./config"
}
If you’re trying to have a different config based on your environment then you could do:
./config.js:
if (process.env.NODE_ENV === 'production') {
module.exports = { /* production config */ };
} else if (process.env.NODE_ENV === 'development') {
module.exports = { /* development config */ };
} else if (process.env.NODE_ENV === 'test') {
module.exports = { /* test config */ };
}
then in your package.json you would have something like:
"scripts": {
"build:js": "NODE_ENV=production browserify -d -e src/index.js",
"test": "NODE_ENV=test karma"
},
"browserify": {
"transform": [
"envify"
]
}
envify being a crucial part which allows you to replace environment variables with their string directly in the code. e.g.: process.env.NODE_ENV === 'development' might become simply 'development' === 'development'. Such things can then be removed with a minification tool like uglifyjs.

Ionic serve: how to rerun gulp task

I'm kinda new to ionic and gulp.
I was able to configure the ionic.project file in order to run the gulp tasks when I first run ionic serve.
But now when I change files I want that the gulp task will run again.. But this doesn't happen.. Is there a way to do that?
This is my ionic.project file:
{
"name": "test",
"app_id": "",
"gulpStartupTasks": [
"default"
],
"watchPatterns": [
"src/**/*",
"src/*",
"www/**/*",
"!www/lib/**/*"
]
}
I expected that when some file changes that match the wtachPatterns
it will invoke the gulp watch task, but this doesnt happen (I see that ionic see that the file has changed but nothing happen.)
this the the gulp watch task:
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
gulp.watch(paths.script, ['script']);
});
Basically the task is minifying all the JS files and all the sass/scss files
and the index.html is looking on the minified files. so if the gulp task isn't invoked there are no changes in the minified file and I need to run ionic serve all over again.. Is there a proper way to do that?
UPDATE:
This is the complete gulpfile
var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
require('require-dir')('./gulp/tasks');
var paths = {
sass: ['./scss/**/*.scss'],
style: ['./src/**/*.scss'],
script: ['./src/app.js'],
html:['./src/*.html']
};
gulp.task('default', ['sass', 'script','watch', 'html', 'style']);
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
gulp.watch(paths.script, ['script']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git- scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
And this is an example of one of the files who have the actual task:
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var stringify = require('stringify');
var paths = ['./src/app.js'];
gulp.task('script', function() {
return browserify(paths, {debug: true})
.transform(stringify(['.html']))
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('./www/js'));
});
Well So the problem was with paths I watched.
I removed the ./ and now its working
First thing first, you misunderstand the watchPatterns is for livereload, which means, the web will refresh if there is any file changed on watch. It's definitely not having any relation to gulp.
Read more at: http://ionicframework.com/docs/cli/test.html
To watch for file changes with watch, update your watch task, which is
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']); <-- any file in paths.sass changed will trigger `gulp sass`
gulp.watch(paths.script, ['script']); <-- any file in paths.script changed will trigger `gulp script`
});
So if you want to watch more files to be processed by Gulp, just add tasks and watch them in gulp watch.
Oh hey, you are watching only files in ./scss/**/*.scss and ./src/app.js. Add more if you wish.