How to use validateRequireJs method in Karma

Best JavaScript code snippet using karma

init.js

Source:init.js Github

copy

Full Screen

1'use strict'2const readline = require('readline')3const path = require('path')4const glob = require('glob')5const mm = require('minimatch')6const exec = require('child_process').exec7const helper = require('./helper')8const logger = require('./logger')9const log = logger.create('init')10const logQueue = require('./init/log-queue')11const StateMachine = require('./init/state_machine')12const COLOR_SCHEME = require('./init/color_schemes')13const formatters = require('./init/formatters')14// TODO(vojta): coverage15// TODO(vojta): html preprocessors16// TODO(vojta): SauceLabs17// TODO(vojta): BrowserStack18let NODE_MODULES_DIR = path.resolve(__dirname, '../..')19// Karma is not in node_modules, probably a symlink,20// use current working dir.21if (!/node_modules$/.test(NODE_MODULES_DIR)) {22 NODE_MODULES_DIR = path.resolve('node_modules')23}24function installPackage (pkgName) {25 // Do not install if already installed.26 try {27 require(NODE_MODULES_DIR + '/' + pkgName)28 return29 } catch (e) {}30 log.debug(`Missing plugin "${pkgName}". Installing...`)31 const options = {32 cwd: path.resolve(NODE_MODULES_DIR, '..')33 }34 exec(`npm install ${pkgName} --save-dev`, options, function (err, stdout, stderr) {35 // Put the logs into the queue and print them after answering current question.36 // Otherwise the log would clobber the interactive terminal.37 logQueue.push(function () {38 if (!err) {39 log.debug(`${pkgName} successfully installed.`)40 } else if (/is not in the npm registry/.test(stderr)) {41 log.warn(`Failed to install "${pkgName}". It is not in the NPM registry!\n Please install it manually.`)42 } else if (/Error: EACCES/.test(stderr)) {43 log.warn(`Failed to install "${pkgName}". No permissions to write in ${options.cwd}!\n Please install it manually.`)44 } else {45 log.warn(`Failed to install "${pkgName}"\n Please install it manually.`)46 }47 })48 })49}50function validatePattern (pattern) {51 if (!glob.sync(pattern).length) {52 log.warn('There is no file matching this pattern.\n')53 }54}55function validateBrowser (name) {56 // TODO(vojta): check if the path resolves to a binary57 installPackage('karma-' + name.toLowerCase().replace('headless', '').replace('canary', '') + '-launcher')58}59function validateFramework (name) {60 installPackage('karma-' + name)61}62function validateRequireJs (useRequire) {63 if (useRequire) {64 validateFramework('requirejs')65 }66}67var questions = [{68 id: 'framework',69 question: 'Which testing framework do you want to use ?',70 hint: 'Press tab to list possible options. Enter to move to the next question.',71 options: ['jasmine', 'mocha', 'qunit', 'nodeunit', 'nunit', ''],72 validate: validateFramework73}, {74 id: 'requirejs',75 question: 'Do you want to use Require.js ?',76 hint: 'This will add Require.js plugin.\nPress tab to list possible options. Enter to move to the next question.',77 options: ['no', 'yes'],78 validate: validateRequireJs,79 boolean: true80}, {81 id: 'browsers',82 question: 'Do you want to capture any browsers automatically ?',83 hint: 'Press tab to list possible options. Enter empty string to move to the next question.',84 options: ['Chrome', 'ChromeHeadless', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera', 'IE', ''],85 validate: validateBrowser,86 multiple: true87}, {88 id: 'files',89 question: 'What is the location of your source and test files ?',90 hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\nEnter empty string to move to the next question.',91 multiple: true,92 validate: validatePattern93}, {94 id: 'exclude',95 question: 'Should any of the files included by the previous patterns be excluded ?',96 hint: 'You can use glob patterns, eg. "**/*.swp".\nEnter empty string to move to the next question.',97 multiple: true,98 validate: validatePattern99}, {100 id: 'generateTestMain',101 question: 'Do you wanna generate a bootstrap file for RequireJS?',102 hint: 'This will generate test-main.js/coffee that configures RequireJS and starts the tests.',103 options: ['no', 'yes'],104 boolean: true,105 condition: (answers) => answers.requirejs106}, {107 id: 'includedFiles',108 question: `Which files do you want to include with <script> tag ?`,109 hint: 'This should be a script that bootstraps your test by configuring Require.js and ' +110 'kicking __karma__.start(), probably your test-main.js file.\n' +111 'Enter empty string to move to the next question.',112 multiple: true,113 validate: validatePattern,114 condition: (answers) => answers.requirejs && !answers.generateTestMain115}, {116 id: 'autoWatch',117 question: 'Do you want Karma to watch all the files and run the tests on change ?',118 hint: 'Press tab to list possible options.',119 options: ['yes', 'no'],120 boolean: true121}]122function getBasePath (configFilePath, cwd) {123 const configParts = path.dirname(configFilePath).split(path.sep)124 const cwdParts = cwd.split(path.sep)125 const base = []126 while (configParts.length && configParts[0] === cwdParts[0]) {127 configParts.shift()128 cwdParts.shift()129 }130 while (configParts.length) {131 const part = configParts.shift()132 if (part === '..') {133 base.unshift(cwdParts.pop())134 } else if (part !== '.') {135 base.unshift('..')136 }137 }138 return base.join(path.sep)139}140function processAnswers (answers, basePath, testMainFile) {141 const processedAnswers = {142 basePath: basePath,143 files: answers.files,144 onlyServedFiles: [],145 exclude: answers.exclude,146 autoWatch: answers.autoWatch,147 generateTestMain: answers.generateTestMain,148 browsers: answers.browsers,149 frameworks: [],150 preprocessors: {}151 }152 if (answers.framework) {153 processedAnswers.frameworks.push(answers.framework)154 }155 if (answers.requirejs) {156 processedAnswers.frameworks.push('requirejs')157 processedAnswers.files = answers.includedFiles || []158 processedAnswers.onlyServedFiles = answers.files159 if (answers.generateTestMain) {160 processedAnswers.files.push(testMainFile)161 }162 }163 const allPatterns = answers.files.concat(answers.includedFiles || [])164 if (allPatterns.some((pattern) => mm(pattern, '**/*.coffee'))) {165 installPackage('karma-coffee-preprocessor')166 processedAnswers.preprocessors['**/*.coffee'] = ['coffee']167 }168 return processedAnswers169}170exports.init = function (config) {171 logger.setupFromConfig(config)172 const colorScheme = !helper.isDefined(config.colors) || config.colors ? COLOR_SCHEME.ON : COLOR_SCHEME.OFF173 // need to be registered before creating readlineInterface174 process.stdin.on('keypress', function (s, key) {175 sm.onKeypress(key)176 })177 const rli = readline.createInterface(process.stdin, process.stdout)178 const sm = new StateMachine(rli, colorScheme)179 rli.on('line', sm.onLine.bind(sm))180 // clean colors181 rli.on('SIGINT', function () {182 sm.kill()183 process.exit(0)184 })185 sm.process(questions, function (answers) {186 const cwd = process.cwd()187 const configFile = config.configFile || 'karma.conf.js'188 const isCoffee = path.extname(configFile) === '.coffee'189 const testMainFile = isCoffee ? 'test-main.coffee' : 'test-main.js'190 const formatter = formatters.createForPath(configFile)191 const processedAnswers = processAnswers(answers, getBasePath(configFile, cwd), testMainFile)192 const configFilePath = path.resolve(cwd, configFile)193 const testMainFilePath = path.resolve(cwd, testMainFile)194 if (isCoffee) {195 installPackage('coffeescript')196 }197 if (processedAnswers.generateTestMain) {198 formatter.writeRequirejsConfigFile(testMainFilePath)199 console.log(colorScheme.success(`RequireJS bootstrap file generated at "${testMainFilePath}".`))200 }201 formatter.writeConfigFile(configFilePath, processedAnswers)202 console.log(colorScheme.success(`Config file generated at "${configFilePath}".`))203 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function() {2 it('should pass', function() {3 validateRequireJs();4 });5});6describe('test2', function() {7 it('should pass', function() {8 validateRequireJs();9 });10});11module.exports = function(config) {12 config.set({13 preprocessors: {14 },15 });16};17define(['myFile'], function(myFile){18 describe('test', function(){19 it('should pass', function(){20 expect(myFile.fn()).toBe('hello');21 });22 });23});24module.exports = function(config) {25 config.set({26 preprocessors: {27 },28 });29};30define(['my

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Validate RequireJS', function() {2 it('should be able to validate RequireJS', function() {3 expect(validateRequireJs()).toBe(true);4 });5});6function validateRequireJs() {7 var requireJs = document.querySelector('script[src*="require.js"]');8 return requireJs !== null;9}10module.exports = function(config) {11 config.set({

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Validate RequireJS', function() {2 it('should be able to validate RequireJS', function() {3 expect(validateRequireJs()).toBe(true);4 });5});6function validateRequireJs() {7 var requireJs = document.querySelector('script[src*="require.js"]');8 return requireJs !== null;9}10module.exports = function(config) {11 config.set({

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function() {2 it('should be true', function() {3 expect(validateRequireJs()).toBeTruthy();4 });5});6module.exports = function(config) {7 config.set({8 preprocessors: {9 },10 });11};12module.exports = function(config) {13 config.set({14 preprocessors: {15 },16 client: {17 validateRequireJs: function() {18 return true;19 }20 }21 });22};23describe('test', function() {24 it('should be true', function() {25 expect(validateRequireJs()).toBeTruthy();26 });27});28module.exports = function(config) {29 config.set({30 preprocessors: {31 },32 client: {33 validateRequireJs: function() {34 return true;35 }

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should validate requireJs de}endencies', function() {3 vaidateReqireJs();4 });5});6preprocessors:}{7);'app/**/*.js':['coverage'],8},9coverageReporter: {10},11requireJsConfig: {12 paths: {13 },14 shim: {15 'angular': {16 }17 'angular-mocks': {18 },19 'angular-route': {20 },21 'angularAMD': {22 },23 'ngload': {24 }25 },26}27v istanbul = require('browserify-istanbul');28var isparta = require('isparta');29odule.exports = function(config) {30 config.set({31 {pattern: 'app/**/*.js', included: false},32 {pattern: 'test/**/*.js', included: false}33 preprocessors: {34 },35describe('test', function() {36 it('should be true', function() {37 expect(validateRequireJs()).toBeTruthy();38 });39});40module.exports = function(config) {41 config.set({42 preprocessors: {43 },

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should validate requireJs dependencies', function() {3 validateRequireJs();4 });5});6preprocessors: {7},8coverageReporter: {9},10requireJsConfig: {11 paths: {12 },13 shim: {14 'angular': {15 },16 'angular-mocks': {17 },18 'angular-route': {19 },20 'angularAMD': {21 },22 'ngload': {23 }24 },25}26var istanbul = require('browserify-istanbul');27var isparta = require('isparta');28module.exports = function(config) {29 config.set({30 {pattern: 'app/**/*.js', included: false},31 {pattern: 'test/**/*.js', included: false}32 preprocessors: {33 },

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should pass', function() {3 expect(validateRequireJs()).toBe(true);4 });5});6beforeEach(function() {7 expect(validateRequireJs()).toBe(true);8});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Karma automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful