I'm trying to use Karma + Mocha for the first time - phantomjs

I'm trying to use Karma + Mocha for the first time.
The main condition is to run the unit tests in a Docker container without any GUI. I don't have any browser, and my only choice is to use PhantomJS.
I have configured all necessary plugins, configs etc., but I received the following error:
ReferenceError: Can't find variable: exports
Before the test run, I built the JavaScript source code with Babel to the 'build' directory and then started Karma from there.
What could be causing this problem?
Here is my karma.conf.js:
// Karma configuration
// Generated on Mon Apr 25 2016 13:04:28 GMT+0300 (RTZ 2 (зима))
const path = require('path');
const webpack = require('webpack');
module.exports = function(config) {
var confBuilder = require('./webpack.config');
confBuilder.module.loaders.push({
test: /\.jsx$/,
loader: 'isparta',
include: path.resolve('src'),
});
confBuilder.devtool = 'inline-source-map';
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: ['mocha', 'chai'/*'jasmine' /*, 'requirejs'*/],
// list of files / patterns to load in the browser
files: [
{pattern: 'build/utils/*.js', load: false}
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap'],
'build/utils/*.js': ['babel']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'coverage', 'jenkins'],
plugins: [
require('karma-webpack'),
require('karma-mocha'),
require('karma-chai'),
require('karma-mocha-reporter'),
require('karma-jenkins-reporter'),
require('karma-chrome-launcher'),
require('karma-sourcemap-loader'),
require('karma-coverage'),
require('karma-phantomjs-launcher'),
require('karma-requirejs'),
require('karma-babel-preprocessor')
],
webpack: confBuilder,
webpackServer: {
noInfo: true,
},
coverageReporter: {
check: {
global: {
statements: 86,
branches: 80,
functions: 95,
lines: 40,
},
},
},
// 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,
autoWatch: true,
})
}

Related

Workbox webpack plugin is not loading assets (.js) from cache after installed

I am trying to set up a PWA for an app in Laravel (5.8) with vuejs (2.5).
This is the configuration I have in mix.js:
...
mix.js('resources/js/app.js', 'public/js')
.generateSW({
// Define runtime caching rules.
runtimeCaching: [{
// Match any request that ends with .png, .jpg, .jpeg or .svg.
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
// Apply a cache-first strategy.
handler: 'CacheFirst',
options: {
// Use a custom cache name.
cacheName: 'images',
// Only cache 10 images.
expiration: {
maxEntries: 10,
},
},
}],
skipWaiting: true
})
.vue()
.copy('node_modules/lodash/lodash.min.js', 'public/js')
.copy('./resources/manifest.json', 'public/dist/manifest.json')
.copy('./resources/icons', 'public/dist/')
.extract(['vue'])
.webpackConfig({
output: {
filename: '[name].js',
chunkFilename: `[name].chunk.[contenthash:8].js`,
path: path.join(__dirname, 'public/dist'),
publicPath: '/dist/'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js',
'variables': path.resolve('resources/sass/_variables.scss')
}
},
plugins: [
new webpack.ContextReplacementPlugin(
/moment[\/\\]locale$/,
/(en|es)$/
),
]
})
.options({
processCssUrls: false,
});
...
The service worker was installed correctly and the first time it loads it caches my assets.
But the next calls I make (reload the page) don't use that cache and reload the assets from the network.
However, what I am looking for is a quick initial load after the PWA is installed and this is not happening.
I have done this before with Angular and the PWA module and the assets are loaded from cache, and if there are changes, they are updated later, which makes the initial load of the application very fast.
Can someone help me with this?
In the end I ended up using workbox-cli with this setup:
// workbox.config.js
module.exports = {
"globDirectory": "public/",
"globPatterns": [
"**/*.{js,css,ico,woff2,webmanifest}",
"**/images/icons/*",
"**/images/*",
],
// 15mb max file size
maximumFileSizeToCacheInBytes: 15 * 1024 * 1024,
globIgnores: [
'**/mix-manifest.json',
'**/js/{manifest,vendor}.js',
'**/js/chunks/*',
],
"swDest": "public/service-worker.js",
"swSrc": "resources/sw-offline.js"
};
And running this at the end of my npm run prod
workbox injectManifest workbox.config.js
All credit to this repository:
https://github.com/aleksandertabor/flashcards

PhantomJS 2.1.1 Error

I can't run my test with karma and phantomJS because of this error:
PhantomJS 2.1.1 (Windows 7.0.0) ERROR
SyntaxError: Use of reserved word 'class'
Here is my config karma.conf.js:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-phantomjs-launcher'),
require('#angular/cli/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['#angular/cli']
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
I updated angular to v5 and it's happening since then... I read to use karma webpack preprocessor but I'm not using webpack and why was it running before ? No clue.
Thanks a lot if you have a tips or a response :)
I am also facing the same problem after upgrading the angular8 to angular9.
After up-gradation to angular9 when I am trying to run ng test with PhantomJS it is showing
PhantomJS 2.1.1 (Windows 8.0.0) ERROR
SyntaxError: Unexpected token ')'
but if I am trying with ng test --browsers=Chrome --codeCoverage=true it is working fine.
It runs fine with all ES6 keywords, syntax etc.,
PhantomJS requires polyfills so install core-js, and import it before importing zone.
import 'core-js/es6';

Run protractor e2e tests in TFS build

How I should configure my TFS build to make it possible run protractor e2e test in browserstack, and return me some html report which test are failed? I am new in TFS. I can do it manually from my machine, but not sure have I can do it in TFS.
This is how my protractor config looks like:
var project = 'testProject',
build = 'build_4',
acceptSslCerts = 'true';
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest: './html-report/',
filename: 'my-report.html',
reportOnlyFailedSpecs: false,
captureOnlyFailedSpecs: true,
showSummary: true,
});
module.exports.config = {
framework: 'jasmine2',
seleniumAddress: 'http://hub.browserstack.com/wd/hub', /* 'http://localhost:4444/wd/hub', */
allScriptsTimeout: 40000,
specs: [ 'test-spec.js' ],
capabilities: {
browserName: 'chrome',
loggingPrefs: { driver: 'ALL', server: 'ALL', browser: 'ALL' },
'build' : 'version3',
'project' : 'newintropage',
'browserstack.user': 'browserstack.user',
'browserstack.key': 'browserstack.key',
'browser': 'Edge',
'browser_version': '13.0',
'os': 'Windows',
'os_version': '10',
'resolution': '1024x768',
'acceptSslCerts': acceptSslCerts
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 40000
},
// Setup the report before any tests start
beforeLaunch: function () {
return new Promise(function (resolve) {
reporter.beforeLaunch(resolve);
});
},
onPrepare: function () {
jasmine.getEnv().addReporter(reporter);
},
// Close the report after all tests finish
afterLaunch: function (exitCode) {
return new Promise(function (resolve) {
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
};
And that's how my tfs build looks like:
According to the screenshot, you are using vNext build, and you have chosen a default "Visual Studio" build template.
TFS vNext build system is task based, which is flexible. I'm not familiar with protractor e2e tests, but based on the description of Protractor, at least, you'll need to use npm to install two command line tools, protractor and webdriver-manager, so the default "Visual Studio" build template won't meet your requirement.
You need to customize your own build template by specifying your build steps. For example, you need to add npm step to install protractor and webdriver-manager, and add Command Line step to run protractor conf.js command.

Karma, empty test suite

First of all I know there are similar questions, but none of it works for me.
I have an Angular app, and I would like to test it with Karma, Jasmin, and RequireJs.
I have installed everything I need, and configured everything as it is written here: http://karma-runner.github.io/0.13/plus/requirejs.html
Below is how my files look like
karma.conf.js
module.exports = function(config) {
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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'src/test/Tests/*.js',
'src/test/Tests/directives/*.js',
//source code
{pattern: 'src/main/webapp/app/*.js', included: false},
{pattern: 'src/main/webapp/app/**/*.js', included: false},
{pattern: 'src/test/test-main.js', included: true}
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/Tests/*.js': 'coverage'
},
coverageReporter:{
type:'html',
dir:'../coverage/'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// 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
// 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: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
test-main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
//dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
The output is in IntelliJ IDEA 14.1.5
Empty test suite.
Process finished with exit code 0
The server starts correctly. I have also tried with command line. $ karma start, and $ karma run, which also does nothing. There is no error message at all. The path is correct, there is no 404 error.
Do you have any guess what could be the problem?
Delete the module names from test files.
In my case, this was the solution.
According to RequireJS documentation (http://requirejs.org/docs/api.html#modulename) you can include a name for the module as you can see below:
//Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);
But for me, Karma only executes the tests if I delete the "foo/title" name.

Protractor pointing to Sauce Labs Selenium Server

I'm trying to integrate Protractor with Sauce Labs from Travis. I can get the sauce_connect server running correctly but am unable to get Travis to point to that particular remote server.
Travis will get to the point where it initiates sauce_connect but when I run "protractor:analytics" it doesn't point to the correct server and fails.
Travis.yml:
language: python
python:
- 3.2_with_system_site_packages
branches:
only:
- develop
before_install:
- sudo apt-get update -qq
- sudo apt-get install python-numpy
install:
- cd lib && python setup.py install
- cd .. && pip install -r requirements/travis_requirements.txt
- npm install
script:
- grunt karma:single
- grunt protractor:analytics
env:
global:
- secure: <string>
- secure: <string>
sauce_connect: true
Gruntfile:
protractor: {
options: {
configFile: './webapp/static/test/e2e/protractor.conf.js',
keepAlive: true
},
singlerun: {},
analytics: {
options: {
//debug : true,
args:{
specs: ['./webapp/static/test/e2e/analytics_spec.js']
}
}
},
},
Protractor Conf:
exports.config = {
chromeOnly: false,
seleniumArgs: [],
// If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
// The tests will be run remotely using SauceLabs.
sauceUser: process.env.SAUCE_USER,
sauceKey: process.env.SAUCE_KEY,
baseUrl: 'http://localhost:8000',
specs: [
'./*_spec.js',
],
// Patterns to exclude.
exclude: [],
multiCapabilities: [],
// ----- More information for your tests ----
//
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
baseUrl: process.env.SN_BASE_URL,
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
// A callback function called once protractor is ready and available, and
// before the specs are executed
// You can specify a file containing code to run by setting onPrepare to
// the filename string.
onPrepare: function() {
// At this point, global 'protractor' object will be set up, and jasmine
// will be available. For example, you can add a Jasmine reporter with:
// jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(
// 'outputdir/', true, true));
},
// The params object will be passed directly to the protractor instance,
// and can be accessed from your test. It is an arbitrary object and can
// contain anything you may need in your test.
// This can be changed via the command line as:
// --params.login.user 'Joe'
params: {
login: {
user: process.env.SN_TEST_USERNAME,
password: process.env.SN_TEST_PASSWORD
}
},
framework: 'jasmine',
// ----- Options to be passed to minijasminenode -----
//
// See the full list at https://github.com/juliemr/minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: false,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
},
onCleanUp: function() {}
};
If I did understand well : Sauce connect tool is not used by protractor/selenium when running a test suite.
Well I had this problem, travis requires sauce credentials and protractor requires those credentials and a tunnel id:
.travis.yml:
addons:
sauce_connect:
username: xxx
access_key: xxx
protractor.conf.js:
exports.config = {
...
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: {
...
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
}
}