So, I have 1 error in my GULP when I use the following:
node ./node_modules/gulp/bin/gulp.js test
Here's the error I'm getting when I run: node ./node_modules/gulp/bin/gulp.js test
PS C:\Users\myuser\repos\wwwroot\acqustn-aem-global-comps\ui.apps> node
./node_modules/gulp/bin/gulp.js test
[09:41:14] Using gulpfile ~\repos\wwwroot\global-comps\ui.apps\gulpfile.js
[09:41:14] Starting 'test'...
[09:41:14] 'test' errored after 4.45 ms
[09:41:14] TypeError: Cannot read property 'start' of undefined
at C:\Users\myuser\repos\wwwroot\global-comps\ui.apps\gulpfile.js:12:11
at test (C:\Users\myuser\repos\wwwroot\global-comps\ui.apps\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:426:14)
at runBound (domain.js:439:12)
at asyncRunner (C:\Users\myuser\repos\wwwroot\global-comps\ui.apps\node_modules\async-done\index.js:55:18)
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Here is my karma.conf.js file that's formatted in the following manner. I'm adding more text here because I have to as I cannot post unless I describe more information
module.exports = function (config) {
const process = require('process');
process.env.CHROME_BIN = require('puppeteer').executablePath();
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine-jquery', 'jasmine'],
plugins: [
require('jquery'),
require('karma-junit-reporter'),
require('karma-coverage'),
require('karma-jasmine-jquery-2'),
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-phantomjs-launcher'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma'),
require('karma-sonarqube-unit-reporter')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/global-comps'),
reports: ['lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
// list of files / patterns to load in the browser
files: [
'./src/main/content/jcr_root/etc/designs/global-components/footer/**/*.js',
'./src/main/content/jcr_root/etc/designs/global-components/header/**/*.js',
'./src/main/content/jcr_root/etc/designs/global-components/action/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./test/navigationClientLibs/js/header.spec.js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['junit', 'progress', 'kjhtml', 'coverage-istanbul', 'sonarqubeUnit', 'coverage'],
sonarQubeUnitReporter: {
sonarQubeVersion: 'LATEST',
outputFile: 'reports/ut_report.xml',
overrideTestDescription: true,
testPaths: ['./test/navigationClientLibs/'],
testFilePattern: '.js',
useBrowserName: false
},
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
junitReporter: {
outputFile: 'reports/junit/TESTS-xunit.xml'
},
coverageReporter: {
type: 'lcov',
dir: 'reports',
subdir: 'coverage'
}
})
}
Now my GULP FILE which is failing with karma.start() whenever I run the following node ./node_modules/gulp/bin/gulp.js test at the command prompt in VS Code Terminal
var gulp = require('gulp');
var karma = require('karma').server;
var replace = require('gulp-replace');
var postprocessLCOV = function() {
return gulp.src('reports/coverage/lcov.info')
.pipe(replace('SF:.', 'SF:frontend-project'))
.pipe(gulp.dest('reports/coverage'));
};
gulp.task('test', function () {
karma.start({
configFile: __dirname + '/src/test/js/karma.conf.ci.js'
}, postprocessLCOV);
});
Of Note: My karma.conf.js and .ci.js are exactly the same so I don't have to post both files here.
Finally, my package.json which shows everything I'm using. Whenever I added an new library, I have to delete the package.lock.json, after the new library is installed then re-run npm install.
{
"name": "global-comps",
"version": "1.0.0",
"description": "This is for the Navigator",
"main": "qunit.js",
"scripts": {
"lint": "eslint '**/*.js'",
"test": "qunit",
"compodoc": "npx compodoc -p tsconfig.doc.json",
"ng": "ng",
"clean": "rm -rf node*",
"ng-cli": "npm install --no-optional #angular/cli",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"prod": "node --max_old_space_size=8192 node_modules/#angular/cli/bin/ng build --prod --output-hashing none && npm run test && npm run clean",
"e2e": "ng e2e",
"sonar": "sonar-scanner"
},
"repository": {
"type": "git",
"url": "somerepo.git"
},
"author": "Some Author",
"license": "MIT",
"dependencies": {
"#angular/common": "~9.0.2",
"#angular/compiler": "~9.0.2",
"#angular/core": "~9.0.2",
"#angular/platform-browser": "~9.0.2",
"#angular/platform-browser-dynamic": "~9.0.2",
"#angular/router": "~9.0.2",
"#types/mocha": "^9.0.0",
"JSONPath": "^0.11.2",
"browserify": "^17.0.0",
"common-js": "^0.3.8",
"eslint-plugin-qunit": "^6.1.1",
"jquery": "^3.4.1",
"jquery-browserify": "^1.8.1",
"jsdom": "^16.5.3",
"junit": "^1.4.9",
"karma-junit-reporter": "^2.0.1",
"ng-mocks": "^11.10.1",
"node": "^15.12.0",
"npm-check-updates": "^11.5.13",
"phantomjs": "^2.1.7",
"qunit-reporter-junit": "^1.1.1",
"qunit-reporter-lcov": "^1.0.2",
"require": "^2.4.20",
"rxjs": "~6.5.4",
"tslib": "^1.10.0"
},
"devDependencies": {
"#angular-devkit/build-angular": "^12.1.3",
"#angular-devkit/build-webpack": "^0.1201.3",
"#angular/compiler-cli": "~9.0.2",
"#types/jasmine": "~3.5.0",
"#types/jasminewd2": "~2.0.3",
"#types/jsdom": "^16.2.13",
"#types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"grunt": "^1.3.0",
"grunt-contrib-connect": "^3.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-contrib-qunit": "^4.0.0",
"grunt-git-authors": "^3.2.0",
"grunt-search": "^0.1.8",
"gulp": "^4.0.2",
"gulp-replace": "^1.1.3",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^6.3.2",
"karma-chrome-launcher": "^3.1.0",
"karma-coverage": "^2.0.3",
"karma-coverage-istanbul-reporter": "^3.0.3",
"karma-jasmine": "^4.0.1",
"karma-jasmine-html-reporter": "^1.7.0",
"karma-jasmine-jquery-2": "^0.1.1",
"karma-mocha-reporter": "^2.2.5",
"karma-phantomjs-launcher": "^1.0.4",
"karma-qunit": "^4.1.2",
"karma-sonarqube-unit-reporter": "0.0.23",
"karma-webpack": "^5.0.0",
"protractor": "~5.4.3",
"puppeteer": "^1.20.0",
"sonar-scanner": "^3.1.0",
"sonarqube-scanner": "~2.7.0",
"ts-node": "~8.3.0",
"typescript": "~3.7.5"
},
"global": "window"
}
So, that's where I'm at.
UPDATE!
So, I've abandoned GULP and got Karma to work.
But in SONARQUBE, what I'm getting is 0% coverage because Karma is NOT creating the lcov.info file even though it's creating the coverage directory and subsequent files.
OF NOTE: I can run my tests in the browser in QUNIT and see them succeed or fail in either case.
BUT I need KARMA to create the lcov.info file with the tests I've created in my .js file. Since this is not Angular but just pure JavaScript, that's where I'm stuck.
Here's a screen shot of my SONARQUBE Coverage to show you what I'm getting.
I'd really like some help here.
Again, here are the Two SIMPLE test files that I'm running using QUNIT that work but are NOT when I run them in KARMA.
Thank you everyone for your continued support.
describe('A Suite for a simple test', () => {
var a;
it('and so it is a spec', () => {
a = true;
expect(a).toBe(true);
});
it('2 plus 2 should be 4', () => {
const result = add(2, 2);
expect(result).toBe(4);
});
});
describe('Test case 1', () => {
var zipcodevalue = '';
const test1 = sendToTest1;
console.log('Test 1 is: ', test1);
beforeEach(function () {
zipToTestCase.call(this, {
assert: assert,
zipcodevalue: '98237',
expected: "Success"
});
});
function zipToTestCase() {
if (isNaN(zipcodevalue === false)) {
expect(zipcodevalue, '98237', 'string value and hard code value are NOT equal', function (callback) {
callback(zipcodevalue);
});
} else {
expect(zipcodevalue, '98237', 'string value and hard code value are equal', function (callback) {
callback(zipcodevalue);
});
}
}
it('test for Valid ZipCode', () => {
expect(zipcodevalue).toBeTruthy();
})
it('test for INValid ZipCode', () => {
expect(zipcodevalue).toBeFalsy();
})
});
I found the answer here with this article!
https://sourcedcode.com/blog/aem/how-to-write-javascript-unit-tests-for-aem-client-libraries-with-jest
This is EXACTLY what I needed and the results are PERFECT!
Related
I have a Rails 6 app with Webpacker.
Everything works well in development but I get an error trying to resolve the entry path when I try pushing to Heroku.
Error: Can't resolve '/application.js' in '/tmp/build_7eddbca060f445328dcebb3128a5bc19'
As a result, I modified the context and entry function in webpack.config.js to the following:
context: path.resolve(__dirname, '../../app/javascript/packs'),
entry: {
application: 'application.js',
},
This however gives me the following error, even though that is the location of my application.js file
ERROR in Entry module not found: Error: Can't resolve 'application.js' in '/app/javascript/packs'
remote: error Command failed with exit code 2.
Does anyone know the reason?
webpack.config.js
const path = require('path');
module.exports = env => {
let prod = env !== undefined && env.production === true;
return {
devtool: prod ? 'source-map' : 'eval-cheap-module-source-map',
context: path.resolve(__dirname, '../../app/javascript/packs'),
entry: {
application: 'application.js',
},
resolve: {
extensions: ['.js', '.jsx']
},
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000
},
output: {
path: path.resolve(__dirname, '../../dist/'),
filename: prod ? "[name].bundle.js" : "[name].js"
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
}
}
package.json
{
"private": true,
"scripts": {
"webpack": "webpack",
"start": "webpack-dev-server --open",
"dev": "webpack --mode=development",
"build": "webpack --mode=production --env.production"
},
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"autoprefixer": "^9.7.5",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^4.0.4",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"postcss-font-magician": "^2.3.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"url-loader": "^4.0.0",
"webpack": "^4.42.1",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"#fortawesome/fontawesome-free": "^5.11.2",
"#popperjs/core": "^2.3.3",
"#rails/actioncable": "^6.0.0",
"#rails/actiontext": "6.0.2-1",
"#rails/activestorage": "^6.0.0",
"#rails/ujs": "^6.0.0",
"#rails/webpacker": "4.2.2",
"ahoy.js": "^0.3.5",
"bootstrap": "^4.4.1",
"chart.js": "^2.9.3",
"chartkick": "^3.2.0",
"expose-loader": "^0.7.5",
"imports-loader": "^0.8.0",
"jquery": "^3.5.1",
"jquery-ujs": "^1.2.2",
"local-time": "^2.1.0",
"popper.js": "^1.14.1",
"quill": "^1.3.6",
"rails-erb-loader": "^5.5.2",
"trix": "1.0.0",
"turbolinks": "^5.2.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"version": "0.1.0"
}
webpacker.yml
# Note: You must restart bin/webpack-dev-server for changes to take effect
default: &default
source_path: app/javascript
source_entry_path: packs
public_root_path: public
public_output_path: packs
cache_path: tmp/cache/webpacker
webpack_compile_output: true
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
resolved_paths: ['app/assets']
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
# Extract and emit a css file
extract_css: false
static_assets_extensions:
- .jpg
- .jpeg
- .png
- .gif
- .tiff
- .ico
- .svg
- .eot
- .otf
- .ttf
- .woff
- .woff2
extensions:
- .erb
- .mjs
- .js
- .sass
- .scss
- .css
- .module.sass
- .module.scss
- .module.css
- .png
- .svg
- .gif
- .jpeg
- .jpg
production:
<<: *default
# Production depends on precompilation of packs prior to booting for performance.
compile: false
# Extract and emit a css file
extract_css: true
# Cache manifest.json for performance
cache_manifest: true
# Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
check_yarn_integrity: false
Fixed it by removing context and instead setting the entry path explicitly
entry: './app/javascript/packs/application.js',
I am trying to develop a custom reporter for mocha output that will be used with protractor. I have developed a good deal of the reporter and if I use the "--reporter" command line argument it works fine. However if I try to specify it in mocharc, or more importantly reporterOptions within the protractor configuration file it can't seem to find the package. Is the command line reporter flag the only way to specify a local/custom reporter? If not, how are you supposed to specify it outside of the command line?
.babelrc:
require:
- '#babel/polyfill'
- '#babel/register'
reporter: './mocha-reporter'
spec: '_src/js/tests/unit/**/*.spec.js'
package.json:
{
"name": "box",
"version": "1.0.0",
"description": "boom!",
"main": "index.js",
"scripts": {
"mocha": "mocha",
"mocha-custom": "mocha -O outputDir=_src/js/tests/reports,testDir=_src/js/tests/unit --reporter mocha-reporter",
"mochawesonme": "mocha --reporter mochawesome --reporter-options reportDir=_src/js/tests/reports,reportFilename=PCMS_unit_test_results",
"check-types": "tsc",
"clean-selenium": "webdriver-manager clean",
"update-selenium": "webdriver-manager update --standalone --versions.standalone=3.8.0",
"start-selenium": "webdriver-manager start --versions.standalone=3.8.0",
"integration-tests": "protractor protractor.conf.js"
},
"devDependencies": {
"#babel/cli": "~7.4.3",
"#babel/core": "~7.4.3",
"#babel/plugin-proposal-class-properties": "7.4.0",
"#babel/plugin-proposal-object-rest-spread": "~7.4.3",
"#babel/plugin-transform-destructuring": "~7.4.3",
"#babel/polyfill": "~7.4.3",
"#babel/preset-env": "~7.4.3",
"#babel/preset-typescript": "~7.3.3",
"#babel/register": "~7.4.0",
"#fortawesome/fontawesome-free": "5.8.1",
"#types/bluebird": "3.5.26",
"#types/jquery": "3.3.29",
"#types/knockout": "~3.4.65",
"#typescript-eslint/eslint-plugin": "~1.7.0",
"#typescript-eslint/parser": "~1.7.0",
"appcache-webpack-plugin": "~1.4.0",
"autoprefixer": "~9.5.1",
"babel-loader": "~8.0.5",
"chai": "~4.2.0",
"chai-as-promised": "7.1.1",
"copy-webpack-plugin": "~5.0.3",
"css-loader": "~2.1.1",
"eslint": "~5.16.0",
"eslint-config-airbnb-base": "~13.1.0",
"eslint-config-airbnb-typescript": "~3.0.0",
"eslint-plugin-import": "~2.17.2",
"file-loader": "~3.0.1",
"html-loader": "~0.5.5",
"html-webpack-plugin": "3.2.0",
"js-yaml": "~3.13.1",
"json-loader": "~0.5.7",
"jszip": "~3.2.1",
"karma": "~4.1.0",
"karma-chai": "~0.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-firefox-launcher": "~1.1.0",
"karma-mocha": "~1.3.0",
"karma-sinon": "~1.0.5",
"karma-webpack": "~3.0.5",
"mini-css-extract-plugin": "~0.6.0",
"mocha": "~6.1.4",
"mocha-reporter": "file:mocha-reporter",
"mochawesome": "~3.1.2",
"mochawesome-report-generator": "3.1.5",
"mochawesome-screenshots": "1.6.0",
"node-sass": "^4.12.0",
"popper.js": "~1.15.0",
"postcss-loader": "~3.0.0",
"protractor": "5.4.2",
"protractor-image-comparison": "3.1.0",
"sass-loader": "~7.1.0",
"sinon": "~7.3.2",
"style-loader": "~0.23.1",
"typescript": "~3.4.5",
"url-loader": "~1.1.2",
"webpack": "~4.30.0",
"webpack-cli": "~3.3.1",
"webpack-dev-server": "~3.3.1"
},
"dependencies": {
"bluebird": "~3.5.4",
"bootstrap": "3.3.7",
"d3": "~5.9.2",
"isomorphic-fetch": "2.2.1",
"jquery": "^3.4.0",
"jquery-ui": "~1.12.1",
"knockout": "~3.5.0",
"knockout-mapping": "~2.6.0",
"lodash": "~4.17.11",
"numeral": "~2.0.6",
"page": "~1.11.4"
}
}
index.js:
import mochaBaseReporter from 'mocha/lib/reporters/base';
import { takeScreenShot } from './javascript/screenShots';
import { populateTestResults } from './javascript/testTree';
import {
getFileContents,
writeToOutputFile,
} from './javascript/fileSystemAccess';
import {
getTemplate,
parseTestsIntoOutput,
addValuesToTemplate,
} from './javascript/templating';
import {
SUCCESS,
FAILURE,
FINISHED,
} from './constants';
const addStyle = template => getFileContents('styles.css')
.then(styles => addValuesToTemplate(template, { styles }))
.catch(error => console.log('file read of styles.css failed', error));
const createReport = (outputDirectory, fileName, data) => getTemplate('report')
.then(template => addValuesToTemplate(template, { 'test-suites': data }))
.then(template => writeToOutputFile(outputDirectory, `${fileName}.html`, template))
.catch(error => console.log('file read of template.html failed', error));
function mochaReporter(runner, environment) {
const tests = {};
const fileName = 'testfile';
const { outputDir, testDir, takeScreenShotOnFailure } = environment.reporterOptions || {};
const outputDirectory = outputDir && `${process.cwd()}/${outputDir}`;
const accumulateTestResults = (test, image) => populateTestResults(test, testDir, tests, image);
mochaBaseReporter.call(this, runner);
runner.on(SUCCESS, accumulateTestResults);
runner.on(FAILURE, test => (
takeScreenShotOnFailure && window
? takeScreenShot()
: Promise.resolve()
).then(image => accumulateTestResults(test, image)));
runner.on(FINISHED, () => {
parseTestsIntoOutput(tests)
.then(addStyle)
.then(template => addValuesToTemplate(template, runner.stats))
.then(html => createReport(outputDirectory, fileName, html))
.then(() => writeToOutputFile(
`${outputDirectory}/history`,
`test-run-${Date.now()}.json`,
JSON.stringify(tests),
));
});
return runner;
}
module.exports = mochaReporter;
protractor.conf:
/* eslint-disable global-require */
/* eslint-disable #typescript-eslint/no-var-requires */
const protractor = require('protractor');
const { join } = require('path');
const testDirectory = '_src/js/tests';
const baseDirectory = `${testDirectory}/integration/`;
// specifies whether tests will be run in parralel or not
const shardTestFiles = true;
// specifies how many browsers/drivers may be run in parralel
const maxInstances = 4;
function onPrepare() {
// register typescript file extensions with the babel compiler
require('#babel/register')({ extensions: ['.js', '.ts'] });
require('#babel/polyfill');
// don't wait for angular (since our app is currently not angular)
protractor.browser.waitForAngularEnabled(false);
// hot fix for protractor strange map behavior
// found here: https://github.com/angular/protractor/issues/2227#issuecomment-337249891
protractor.ElementArrayFinder.prototype.map = function mapHotFix(mapFn) {
return this.reduce((arr, el) => arr.concat(mapFn(el, arr.length)), []);
};
}
exports.config = {
// mocha configuration
framework: 'mocha',
mochaOpts: {
reporter: './mocha-reporter',
reporterOptions: {
outputDir: `${testDirectory}/reports`,
testDir: `${baseDirectory}/endToEnd`,
takeScreenShotOnFailure: true,
},
timeout: 600000,
slow: 3000,
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// turn off promise management in favor of async/await
SELENIUM_PROMISE_MANAGER: false,
// spec config
specs: [`${baseDirectory}/endToEnd/**/*.spec.js`],
// browser configuration
timeout: 100000,
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles,
maxInstances,
chromeOptions: {
args: [
// 'show-fps-counter=true',
'--headless',
// '--disable-gpu',
'--window-size=1300,1000',
],
},
},
{
browserName: 'firefox',
shardTestFiles,
maxInstances,
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
],
onPrepare,
plugins: [
{
package: 'protractor-image-comparison',
options: {
baselineFolder: join(process.cwd(), `${baseDirectory}/screenshots/baseline/`),
screenshotPath: join(process.cwd(), `${baseDirectory}/screenshots/tmp/`),
formatImageName: '{tag}-{logName}-{width}x{height}',
savePerInstance: true,
autoSaveBaseline: true,
},
},
],
};
I could not find a way to load the local file directly, however I gave it a package.json and installed it directly to node_modules with npm. To be specific I ran
npm install ./mocha-reporter --save-dev
on my project directory after creating a package.json within the project folder. After some debugging I was able to solve my issue since the package was now a part of node's named packages.
I have been building normal js apps using frameworks like ember/angular. They already have everything built in for compilation and testing.
I started building an app in vanilla js. I wrote code in es6.
I started with tests using karma/jasmine. I got stuck with the configuration. I went through couple of articles and got a little success but again got stuck in relative error from browserify in karma. ERROR [framework.browserify]: Error: Cannot find module
How can I write tests with karma/jasmine. What to use? webpack/browserify?
My app structure is:
app/js/**/*.js app/tests/**/*.js app/css/**.css app/index.html app/Gruntfile.js app/karma.conf.js app/package.json app/server.js
This is my gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
browserify: {
development: {
src: [
"./js/application.js",
],
dest: './js/common.js',
options: {
browserifyOptions: {
debug: true
},
transform: [
["babelify", {
"presets": ["es2015"]
}]
]
}
}
},
watch: {
scripts: {
files: ["./js/**/*.js"],
tasks: ["browserify"]
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
};
This is karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
browsers: ['Chrome'],
files: [
'js/**/*.js',
'tests/**/*.js'
],
exclude: [],
preprocessors: {
'js/**/*.js': ['browserify'],
'tests/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify']
},
reporters: ['progress', 'html'],
// the default configuration
htmlReporter: {
outputDir: 'karma_html', // where to put the reports
templatePath: null, // set if you moved jasmine_template.html
focusOnFailures: true, // reports show failures on start
namedFiles: false, // name files instead of creating sub-directories
pageTitle: null, // page title for reports; browser info by default
urlFriendlyName: false, // simply replaces spaces with _ for files/dirs
reportName: 'report-summary-filename', // report summary filename; browser info by default
// experimental
preserveDescribeNesting: false, // folded suites stay folded
foldAll: false, // reports start folded (only with preserveDescribeNesting)
}
});
};
This is my package.json
{
"author": "Yomn",
"name": "myapp",
"version": "0.0.0",
"scripts": {
"start": "node server.js",
"tests": "karma start"
},
"devDependencies": {
"babel-core": "^5.0.0",
"babel-loader": "^5.0.0",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^14.4.0",
"grunt": "^1.0.1",
"grunt-browserify": "^5.1.0",
"grunt-contrib-watch": "^1.0.0",
"jasmine": "^2.2.1",
"jasmine-core": "^2.2.0",
"karma": "^0.13.2",
"karma-browserify": "~3.0.2",
"karma-chrome-launcher": "^2.2.0",
"karma-html-reporter": "^0.2.7",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^1.0.4",
"karma-webpack": "^1.6.0",
"phantomjs-prebuilt": "^2.1.15",
"webpack": "^1.8.4"
}
}
I tried to run project with your configuration, but since you did not provide examples of the files, I sketched out my example that works. I hope it will be useful.
js\Circle.js:
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}
exports.Circle = Circle;
tests\Circle.js:
var Circle = require('../js/Circle');
describe('Circle', () => {
describe(`constructor`, () => {
it(`should initialize properties correctly`, () => {
const circle = new Circle.Circle(1, 2, 3);
expect(circle.x).toBe(1);
});
});
});
Karma start command: "node_modules\.bin\karma" start --no-single-run
I'm using the default source mapping built into Brunch. I see the files fine, but I cannot hit breakpoints within the source mapped files. Using the Javascript access to the debugger via debugger; works, which leads me to believe it's something wrong with the Brunch side of things.
Here is my brunch-config.js:
module.exports = {
files: {
javascripts: {
joinTo: {
'js/vendor.js': /^(?!source\/)/,
'js/app.js': /^source\//
},
entryPoints: {
'source/scripts/app.jsx': 'js/app.js'
},
order: {
before: /^(?!source)/
}
},
stylesheets: {joinTo: 'css/core.css'},
},
paths: {
watched: ['source']
},
modules: {
autoRequire: {
'js/app.js': ['source/scripts/app']
}
},
plugins: {
babel: {presets: ['latest', 'react']},
assetsmanager: {
copyTo: {
'assets': ['source/resources/*']
}
},
static: {
processors: [
require('html-brunch-static')({
processors: [
require('pug-brunch-static')({
fileMatch: 'source/views/home.pug',
fileTransform: (filename) => {
filename = filename.replace(/\.pug$/, '.html');
filename = filename.replace('views/', '');
return filename;
}
})
]
})
]
}
},
server: {
run: true,
port: 9005
}
};
I have tried setting the sourceMaps property of config to 'old' and 'absoluteUrl' and 'inline' (see Brunch config documentation) but still I do not hit breakpoints.
I run the command brunch watch --server and I am using Chrome. Same behavior in Chrome Canary. I hit the breakpoints in Firefox, no problem there.
It's interesting to note that the sourced map files have a base 64 string seemingly for their definition, something like:
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpb...
The mapping appears to be working, but why can't I hit breakpoints in Chrome devtools?
MVCE available. Follow these instructions:
Clone this example repository
npm install
brunch build (make sure it is installed globally with npm install brunch -g)
Open in Chrome devtools and set a breakpoint
Reload the app in attempt to hit the breakpoint
For additional information, here's my package.json:
{
"version": "0.0.1",
"devDependencies": {
"assetsmanager-brunch": "^1.8.1",
"babel-brunch": "^6.1.1",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-rewire": "^1.0.0-rc-5",
"babel-plugin-transform-es2015-modules-commonjs": "^6.10.3",
"babel-plugin-transform-object-rest-spread": "^6.8.0",
"babel-preset-react": "^6.3.13",
"babel-register": "^6.11.6",
"browser-sync-brunch": "^0.0.9",
"brunch": "^2.10.9",
"brunch-static": "^1.2.1",
"chai": "^3.5.0",
"es6-promise": "^3.2.1",
"eslint-plugin-react": "^5.1.1",
"expect": "^1.20.2",
"html-brunch-static": "^1.3.2",
"jquery": "~2.1.4",
"jquery-mousewheel": "^3.1.13",
"mocha": "^3.0.0",
"nib": "^1.1.0",
"nock": "^8.0.0",
"oboe": "~2.1.2",
"paper": "0.9.25",
"path": "^0.12.7",
"pug": "^2.0.0-beta10",
"pug-brunch-static": "^2.0.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-redux": "^4.4.5",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-mock-store": "^1.1.2",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",
"reselect": "^2.5.3",
"spectrum-colorpicker": "~1.8.0",
"stylus-brunch": "^2.10.0",
"uglify-js-brunch": "^2.10.0",
"unibabel": "~2.1.0",
"when": "~3.4.5"
},
"dependencies": {
"jwt-decode": "^2.1.0",
"lodash": "^4.17.4",
"postal": "^2.0.5",
"rc-tree": "^1.3.9"
},
"scripts": {
"test": "mocha --compilers js:babel-register"
}
}
Issue created on brunch's Github.
UPDATE
Solved by fixing my brunch config as specified in the #JohannesFilter's answer to this question.
This was a byproduct of a valid but conflicting Brunch configuration. See the answer to this question from #JohannesFilter.
In essence, it seems that files.joinTo and files.entryPoints are mutually exclusive in that files.entryPoints will override the output of files.joinTo if they overlap. The solution is to choose one or the other, or make sure that they do not overlap on the files they are dealing with. For example, both of these are working configurations:
entryPoints: {
'source/scripts/app.jsx': {
'js/vendor.js': /^(?!source\/)/,
'js/app.js': /^source\//
},
}
or
joinTo: {
'js/lib.js': /^(?!source\/)/
},
entryPoints: {
'source/scripts/app.jsx': {
'js/app.js': /^source\//
},
}
Trying to set up some test system via this article. It's all more or less understandable, but I've got an error which I currently can't resolve.
My karma.entry.js:
require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
const browserTesting = require('#angular/platform-browser-dynamic/testing');
const coreTesting = require('#angular/core/testing');
coreTesting.setBaseTestProviders(
browserTesting.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
browserTesting.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS
);
const context = require.context('..\\srs\\', true, /\.spec\.ts$/);
context.keys().forEach(context);
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
Running "npm test" results in error:
Uncaught TypeError: coreTesting.setBaseTestProviders is not a function
at webpack:///karma/karma.entry.js:15:0 <- karma.entry.js:61
As far as I can guess, require('#angular/core/testing'); doesn't return an object I need. I've seen the similar topics here but so far nothing works.
I understand, that somewhere the dependency is missing but can't pinpoint where exactly.
My karma.conf.js:
'use strict';
module.exports = (config) => {
config.set({
autoWatch: true,
browsers: ['Chrome'],
files: [
'../node_modules/es6-shim/es6-shim.min.js',
'karma.entry.js'
],
frameworks: ['jasmine'],
logLevel: config.LOG_INFO,
phantomJsLauncher: {
exitOnResourceError: true
},
preprocessors: {
'karma.entry.js': ['webpack', 'sourcemap']
},
reporters: ['dots'],
singleRun: false,
webpack: require('..\\webpack\\webpack.test'),
webpackServer: {
noInfo: true
}
});
};
My package.json seems to have all necessary dependencies:
{
...
"dependencies": {
"#angular/common": "^2.2.4",
"#angular/compiler": "^2.2.4",
"#angular/core": "^2.2.4",
"#angular/forms": "^2.2.4",
"#angular/http": "^2.2.4",
"#angular/platform-browser": "^2.2.4",
"#angular/platform-browser-dynamic": "^2.2.4",
"#angular/router": "^3.2.4",
"es6-shim": "^0.35.1",
"reflect-metadata": "^0.1.8",
"rxjs": "^5.0.0-beta.12",
"zone.js": "^0.6.12"
},
"devDependencies": {
"#types/core-js": "^0.9.35",
"html-webpack-plugin": "^2.24.1",
"jasmine-core": "^2.5.2",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-jasmine": "^1.0.2",
"karma-phantomjs-launcher": "^1.0.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^1.8.0",
"phantomjs-prebuilt": "^2.1.13",
"raw-loader": "^0.5.1",
"ts-loader": "^1.2.2",
"tslint": "^4.0.2",
"tslint-loader": "^3.2.1",
"typescript": "^2.0.10",
"typings": "^2.0.0",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
Could someone please kindly inform me where exactly I have misconfigured the whole thing?
The testing API changed multiple times. The current version of the testing entry file is available in the repository linked from this article.
Basically, what you should now do is to use the exposed TestBed class from the core/testing module, rather than directly calling the now removed setBaseTestProviders method.
...
coreTesting.TestBed.resetTestEnvironment();
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting()
);
The TestBed is a class that deals with requirements of the testing environment. You can learn more about it in the Angular's documentation.
Indeed, I have used a deprecated method.