Best JavaScript code snippet using karma
process.spec.js
Source:process.spec.js
1const path = require('path')2const _ = require('lodash')3const BaseLauncher = require('../../../lib/launchers/base')4const RetryLauncher = require('../../../lib/launchers/retry')5const CaptureTimeoutLauncher = require('../../../lib/launchers/capture_timeout')6const ProcessLauncher = require('../../../lib/launchers/process')7const EventEmitter = require('../../../lib/events').EventEmitter8const createMockTimer = require('../mocks/timer')9describe('launchers/process.js', () => {10 let emitter11 let mockSpawn12 let mockTempDir13 let launcher14 const BROWSER_PATH = path.normalize('/usr/bin/browser')15 beforeEach(() => {16 emitter = new EventEmitter()17 launcher = new BaseLauncher('fake-id', emitter)18 mockSpawn = sinon.spy(function (cmd, args) {19 const process = new EventEmitter()20 process.stdout = new EventEmitter()21 process.stderr = new EventEmitter()22 process.kill = sinon.spy()23 process.exitCode = null24 mockSpawn._processes.push(process)25 return process26 })27 mockSpawn._processes = []28 mockTempDir = {29 getPath: (suffix) => `/temp${suffix}`,30 create: sinon.spy(),31 remove: sinon.spy()32 }33 })34 it('should create a temp directory', () => {35 ProcessLauncher.call(launcher, mockSpawn, mockTempDir)36 launcher._getCommand = () => null37 launcher.start('http://host:9988/')38 expect(launcher._tempDir).to.equal('/temp/karma-fake-id')39 expect(mockTempDir.create).to.have.been.calledWith('/temp/karma-fake-id')40 })41 it('should remove the temp directory', (done) => {42 ProcessLauncher.call(launcher, mockSpawn, mockTempDir)43 launcher._getCommand = () => null44 launcher.start('http://host:9988/')45 launcher.kill()46 _.defer(() => {47 expect(mockTempDir.remove).to.have.been.called48 expect(mockTempDir.remove.args[0][0]).to.equal('/temp/karma-fake-id')49 done()50 })51 })52 describe('_normalizeCommand', () => {53 it('should remove quotes from the cmd', () => {54 ProcessLauncher.call(launcher, null, mockTempDir)55 expect(launcher._normalizeCommand('"/bin/brow ser"')).to.equal(path.normalize('/bin/brow ser'))56 expect(launcher._normalizeCommand("'/bin/brow ser'")).to.equal57 path.normalize('/bin/brow ser')58 expect(launcher._normalizeCommand('`/bin/brow ser`')).to.equal(path.normalize('/bin/brow ser'))59 })60 })61 describe('with RetryLauncher', () => {62 it('should handle spawn ENOENT error and not even retry', (done) => {63 ProcessLauncher.call(launcher, mockSpawn, mockTempDir)64 RetryLauncher.call(launcher, 2)65 launcher._getCommand = () => BROWSER_PATH66 const failureSpy = sinon.spy()67 emitter.on('browser_process_failure', failureSpy)68 launcher.start('http://host:9876/')69 mockSpawn._processes[0].emit('error', {code: 'ENOENT'})70 mockSpawn._processes[0].emit('exit', 1)71 mockTempDir.remove.callArg(1)72 _.defer(() => {73 expect(launcher.state).to.equal(launcher.STATE_FINISHED)74 expect(failureSpy).to.have.been.called75 done()76 })77 })78 })79 // higher level tests with Retry and CaptureTimeout launchers80 describe('flow', () => {81 let failureSpy82 let mockTimer = failureSpy = null83 beforeEach(() => {84 mockTimer = createMockTimer()85 CaptureTimeoutLauncher.call(launcher, mockTimer, 100)86 ProcessLauncher.call(launcher, mockSpawn, mockTempDir, mockTimer)87 RetryLauncher.call(launcher, 2)88 launcher._getCommand = () => BROWSER_PATH89 failureSpy = sinon.spy()90 emitter.on('browser_process_failure', failureSpy)91 })92 // the most common scenario, when everything works fine93 it('start -> capture -> kill', (done) => {94 // start the browser95 launcher.start('http://localhost/')96 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])97 // mark captured98 launcher.markCaptured()99 // kill it100 const killingLauncher = launcher.kill()101 expect(launcher.state).to.equal(launcher.STATE_BEING_KILLED)102 expect(mockSpawn._processes[0].kill).to.have.been.called103 // process exits104 mockSpawn._processes[0].emit('exit', 0)105 mockTempDir.remove.callArg(1)106 killingLauncher.done(() => {107 expect(launcher.state).to.equal(launcher.STATE_FINISHED)108 done()109 })110 })111 // when the browser fails to get captured in default timeout, it should restart112 it('start -> timeout -> restart', (done) => {113 const stdOutSpy = sinon.spy(launcher, '_onStdout')114 const stdErrSpy = sinon.spy(launcher, '_onStderr')115 // start116 launcher.start('http://localhost/')117 // expect starting the process118 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])119 const browserProcess = mockSpawn._processes.shift()120 const expectedStdoutString = 'starting...'121 const expectedStderrString = 'Oops...there was a problem'122 browserProcess.stdout.emit('data', expectedStdoutString)123 browserProcess.stderr.emit('data', expectedStderrString)124 // timeout125 mockTimer.wind(101)126 // We must've caught some output127 expect(stdOutSpy).to.have.been.called128 expect(stdErrSpy).to.have.been.called129 stdOutSpy.calledWith(expectedStdoutString)130 // expect killing browser131 expect(browserProcess.kill).to.have.been.called132 browserProcess.emit('exit', 0)133 mockTempDir.remove.callArg(1)134 mockSpawn.resetHistory()135 _.defer(() => {136 // expect re-starting137 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])138 expect(failureSpy).not.to.have.been.called139 done()140 })141 })142 it('start -> timeout -> 3xrestart -> failure', (done) => {143 // start144 launcher.start('http://localhost/')145 // expect starting146 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])147 let browserProcess = mockSpawn._processes.shift()148 mockSpawn.resetHistory()149 // timeout - first time150 mockTimer.wind(101)151 // expect killing browser152 expect(browserProcess.kill).to.have.been.called153 browserProcess.emit('exit', 0)154 mockTempDir.remove.callArg(1)155 mockTempDir.remove.resetHistory()156 _.defer(() => {157 // expect re-starting158 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])159 browserProcess = mockSpawn._processes.shift()160 expect(failureSpy).not.to.have.been.called161 mockSpawn.resetHistory()162 // timeout - second time163 mockTimer.wind(101)164 // expect killing browser165 expect(browserProcess.kill).to.have.been.called166 browserProcess.emit('exit', 0)167 mockTempDir.remove.callArg(1)168 mockTempDir.remove.resetHistory()169 _.defer(() => {170 // expect re-starting171 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])172 browserProcess = mockSpawn._processes.shift()173 expect(failureSpy).not.to.have.been.called174 mockSpawn.resetHistory()175 // timeout - third time176 mockTimer.wind(201)177 // expect killing browser178 expect(browserProcess.kill).to.have.been.called179 browserProcess.emit('exit', 0)180 mockTempDir.remove.callArg(1)181 mockTempDir.remove.resetHistory()182 _.defer(() => {183 expect(mockSpawn).to.not.have.been.called184 expect(failureSpy).to.have.been.called185 done()186 })187 })188 })189 })190 // when the browser fails to start, it should restart191 it('start -> crash -> restart', (done) => {192 // start193 launcher.start('http://localhost/')194 // expect starting the process195 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])196 let browserProcess = mockSpawn._processes.shift()197 mockSpawn.resetHistory()198 // crash199 browserProcess.emit('exit', 1)200 mockTempDir.remove.callArg(1)201 mockTempDir.remove.resetHistory()202 _.defer(() => {203 // expect re-starting204 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])205 browserProcess = mockSpawn._processes.shift()206 expect(failureSpy).not.to.have.been.called207 done()208 })209 })210 })211 // higher level tests - process kill timeout212 describe('process-kill-timeout', () => {213 let failureSpy214 let mockTimer = null215 beforeEach(() => {216 mockTimer = createMockTimer()217 CaptureTimeoutLauncher.call(launcher, mockTimer, 100)218 ProcessLauncher.call(launcher, mockSpawn, mockTempDir, mockTimer, 300)219 RetryLauncher.call(launcher, 2)220 launcher._getCommand = () => BROWSER_PATH221 failureSpy = sinon.spy()222 emitter.on('browser_process_failure', failureSpy)223 })224 // when the browser fails to get captured in default timeout, it should restart225 it('start -> capture_timeout -> kill -> process_kill_timeout -> sigkill', () => {226 // start227 launcher.start('http://localhost/')228 // expect starting the process229 expect(mockSpawn).to.have.been.calledWith(BROWSER_PATH, ['http://localhost/?id=fake-id'])230 const browserProcess = mockSpawn._processes.shift()231 // timeout232 mockTimer.wind(101)233 // expect killing browser234 expect(browserProcess.kill).to.have.been.called235 // processKillTimeout not reached yet236 mockTimer.wind(299)237 // SIGKILL not called yet238 expect(browserProcess.kill.withArgs('SIGKILL')).not.to.have.been.called239 // processKillTimeout240 mockTimer.wind(301)241 // expect killing with SIGKILL242 expect(browserProcess.kill.withArgs('SIGKILL')).to.have.been.called243 browserProcess.emit('exit', 0)244 mockTempDir.remove.callArg(1)245 mockTempDir.remove.resetHistory()246 mockSpawn.resetHistory()247 })248 })...
processLauncher.js
Source:processLauncher.js
...12describe('ProcessWrapper', () => {13 let processLauncher;14 before(() => {15 sinon.stub(ProcessLauncher.prototype, '_subscribeToMessages');16 processLauncher = new ProcessLauncher({17 embark: embarkObj,18 logger: logger,19 modulePath: path.join(__dirname, 'test.js'),20 events21 });22 });23 describe('on', () => {24 beforeEach(() => {25 processLauncher.subscriptions = {};26 });27 it('should create an array for the key value', function () {28 processLauncher.on('test', 'value', 'myCallback');29 assert.deepEqual(processLauncher.subscriptions, {30 "test": [...
process.js
Source:process.js
1var path = require('path')2var log = require('../logger').create('launcher')3var env = process.env4var ProcessLauncher = function (spawn, tempDir, timer, processKillTimeout) {5 var self = this6 var onExitCallback7 var killTimeout = processKillTimeout || 20008 this._tempDir = tempDir.getPath('/karma-' + this.id.toString())9 this.on('start', function (url) {10 tempDir.create(self._tempDir)11 self._start(url)12 })13 this.on('kill', function (done) {14 if (!self._process) {15 return process.nextTick(done)16 }17 onExitCallback = done18 self._process.kill()19 self._killTimer = timer.setTimeout(self._onKillTimeout, killTimeout)20 })21 this._start = function (url) {22 self._execCommand(self._getCommand(), self._getOptions(url))23 }24 this._getCommand = function () {25 return env[self.ENV_CMD] || self.DEFAULT_CMD[process.platform]26 }27 this._getOptions = function (url) {28 return [url]29 }30 // Normalize the command, remove quotes (spawn does not like them).31 this._normalizeCommand = function (cmd) {32 if (cmd.charAt(0) === cmd.charAt(cmd.length - 1) && '\'`"'.indexOf(cmd.charAt(0)) !== -1) {33 cmd = cmd.substring(1, cmd.length - 1)34 log.warn('The path should not be quoted.\n Normalized the path to %s', cmd)35 }36 return path.normalize(cmd)37 }38 this._execCommand = function (cmd, args) {39 if (!cmd) {40 log.error('No binary for %s browser on your platform.\n ' +41 'Please, set "%s" env variable.', self.name, self.ENV_CMD)42 // disable restarting43 self._retryLimit = -144 return self._clearTempDirAndReportDone('no binary')45 }46 cmd = this._normalizeCommand(cmd)47 log.debug(cmd + ' ' + args.join(' '))48 self._process = spawn(cmd, args)49 var errorOutput = ''50 self._process.on('exit', function (code) {51 self._onProcessExit(code, errorOutput)52 })53 self._process.on('error', function (err) {54 if (err.code === 'ENOENT') {55 self._retryLimit = -156 errorOutput = 'Can not find the binary ' + cmd + '\n\t' +57 'Please set env variable ' + self.ENV_CMD58 } else {59 errorOutput += err.toString()60 }61 })62 }63 this._onProcessExit = function (code, errorOutput) {64 log.debug('Process %s exited with code %d', self.name, code)65 var error = null66 if (self.state === self.STATE_BEING_CAPTURED) {67 log.error('Cannot start %s\n\t%s', self.name, errorOutput)68 error = 'cannot start'69 }70 if (self.state === self.STATE_CAPTURED) {71 log.error('%s crashed.\n\t%s', self.name, errorOutput)72 error = 'crashed'73 }74 self._process = null75 if (self._killTimer) {76 timer.clearTimeout(self._killTimer)77 self._killTimer = null78 }79 self._clearTempDirAndReportDone(error)80 }81 this._clearTempDirAndReportDone = function (error) {82 tempDir.remove(self._tempDir, function () {83 self._done(error)84 if (onExitCallback) {85 onExitCallback()86 onExitCallback = null87 }88 })89 }90 this._onKillTimeout = function () {91 if (self.state !== self.STATE_BEING_KILLED && self.state !== self.STATE_BEING_FORCE_KILLED) {92 return93 }94 log.warn('%s was not killed in %d ms, sending SIGKILL.', self.name, killTimeout)95 self._process.kill('SIGKILL')96 // NOTE: https://github.com/karma-runner/karma/pull/118497 // NOTE: SIGKILL is just a signal. Processes should never ignore it, but they can.98 // If a process gets into a state where it doesn't respond in a reasonable amount of time99 // Karma should warn, and continue as though the kill succeeded.100 // This a certainly suboptimal, but it is better than having the test harness hang waiting101 // for a zombie child process to exit.102 self._killTimer = timer.setTimeout(function () {103 log.warn('%s was not killed by SIGKILL in %d ms, continuing.', self.name, killTimeout)104 self._onProcessExit(-1, '')105 }, killTimeout)106 }107}108ProcessLauncher.decoratorFactory = function (timer) {109 return function (launcher, processKillTimeout) {110 var spawn = require('child_process').spawn111 var spawnWithoutOutput = function () {112 var proc = spawn.apply(null, arguments)113 proc.stdout.resume()114 proc.stderr.resume()115 return proc116 }117 ProcessLauncher.call(launcher, spawnWithoutOutput, require('../temp_dir'), timer, processKillTimeout)118 }119}...
index.js
Source:index.js
1var config = require('./config');2var router = require('./routers/')(config);3var serverFactory = require('./servers/serverFactory')(config, router);4var server = serverFactory.create();5var processLauncher = require('./servers/processLauncher')(server, config);...
Using AI Code Generation
1var karma = require('karma').server;2karma.start({3}, function(exitCode) {4console.log('Karma has exited with ' + exitCode);5process.exit(exitCode);6});7module.exports = function(config) {8config.set({
Using AI Code Generation
1var karma = require('karma').server;2karma.start({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7module.exports = function(config) {8 config.set({
Using AI Code Generation
1var karma = require('karma').server;2karma.start({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5});6module.exports = function(config) {7 config.set({8 preprocessors: {9 },10 coverageReporter: {11 },12 });13};
Using AI Code Generation
1var processLauncher = require('karma').process;2processLauncher.start({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7module.exports = function(config) {8 config.set({9 preprocessors: {10 },11 })12}13PhantomJS 2.1.1 (Windows 8.0.0) ERROR14PhantomJS 2.1.1 (Windows 8.0.0) ERROR15var obj = {16};17describe('Object', function() {18 describe('#foo', function() {19 it('should return bar', function() {20 expect(obj.foo).to.equal('bar');21 });22 });23});24PhantomJS 2.1.1 (Windows 8.0.0) ERROR25 TypeError: 'undefined' is not a function (evaluating 'obj.foo()')
Using AI Code Generation
1var launcher = require('karma').launcher;2launcher.start({3}, function(exitCode) {4console.log('Karma has exited with ' + exitCode);5process.exit(exitCode);6});7module.exports = function(config) {8config.set({
Using AI Code Generation
1var Server = require('karma').Server;2var server = new Server({3});4server.start();5var launcher = require ( ' karma ' ). launcher ;6var launcher = require ( ' karma ' ). launcher ;7var Server = require ( ' karma ' ). Server ;8var server = new Server ({ 9 });
Using AI Code Generation
1var processLauncher = require('karma').process;2var Server = require('karma').Server;3var karma = new Server({4}, function(exitCode) {5 console.log('Karma has exited with ' + exitCode);6 process.exit(exitCode);7}).start();8processLauncher.launch({9}, function(exitCode) {10 console.log('Karma has exited with ' + exitCode);11 process.exit(exitCode);12});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!