Best JavaScript code snippet using jest
marionette-mocha
Source:marionette-mocha
1#! /usr/bin/env node2'use strict';3var ArgumentParser = require('argparse').ArgumentParser;4var Runner = require('../lib/runner');5var assert = require('assert');6var fs = require('fs');7var fsPath = require('path');8var resolveModule = require('../lib/resolvemodule');9var requireResolve = require('../lib/require_resolve');10var OPTS_FILE = 'marionette-mocha.opts';11var argv = ['test/', 'tests/', '.'].reduce(function(argv, path) {12 var optsFile = fsPath.join(path, OPTS_FILE);13 if (!fs.existsSync(optsFile)) {14 return argv;15 }16 argv.splice.apply(17 argv,18 [2, 0].concat(require('../lib/optsfileparser')(optsFile))19 );20 return argv;21}, process.argv);22var requireReporter = require('../lib/require_reporter').bind(null, argv);23var parser = new ArgumentParser({24 version: require('../package').version,25 description: 'Marionette JS Runner',26 addHelp: false,27});28parser.addArgument(['--help'], {29 action: 'storeTrue',30 help: 'Output help',31 defaultValue: false32});33parser.addArgument(['--ui'], {34 type: 'string',35 help: 'Marionette specific mocha ui to use',36 defaultValue: fsPath.normalize(__dirname + '/../lib/ui'),37});38parser.addArgument(['--host'], {39 type: require,40 help: 'host module to use defaults to marionette-b2gdesktop-host',41 defaultValue: fsPath.normalize(__dirname + '/../host'),42});43parser.addArgument(['--reporter'], {44 type: requireReporter,45 help: 'Mocha reporter to use',46 defaultValue: 'dot'47});48parser.addArgument(['--verbose'], {49 help: 'Pipe console.* logs from child gecko processes to test process',50 action: 'storeTrue',51 defaultValue: false52});53parser.addArgument(['--profile-base'], {54 type: requireResolve,55 help: 'default profile options to use in all tests.',56 dest: 'profileBase'57});58parser.addArgument(['--profile-builder'], {59 type: requireResolve,60 help: 'profile generation module',61 dest: 'profileBuilder',62 defaultValue: 'marionette-profile-builder'63});64parser.addArgument(['--host-log'], {65 type: 'string',66 help: 'Location for gecko/host logs (<file>, stderr, stdout)',67 dest: 'hostLog',68 defaultValue: 'marionette-mocha-gecko.log'69});70parser.addArgument(['--mocha-flags'], {71 help: 'Show mocha specific help/arguments',72 dest: 'mochaFlags',73 action: 'storeTrue'74});75parser.addArgument(['--marionette-capabilities'], {76 type: importDesiredCapabilities,77 dest: 'desiredCapabilities',78 help: 'Path tp marionette desired capabilities file (*.json)'79});80function main(argv) {81 // Initial parser pass to pick up the hosts... This generally won't fail except82 // in the case of serious argument parsing errors.83 var initialArgs = parser.parseKnownArgs(argv);84 // Abort early if we just want to show the mocha options...85 if (initialArgs[0].mochaFlags) return showMochaHelp();86 // Capture the additional arguments from the host.87 var hostActions = extendParserWithModule(parser, initialArgs[0].host);88 // The second (and "real") parser pass which will include the output needed to89 // generate a better help message with the extensible options from the host.90 var args = parser.parseKnownArgs(argv);91 if (args[0].help) {92 parser.printHelp();93 process.exit(0);94 }95 // Options to pass on to mocha...96 var runner = new Runner({97 host: {98 module: args[0].host,99 options: extractOptionsFromModule(args[0], hostActions)100 },101 profileBuilder: {102 constructor: args[0].profileBuilder,103 // Reserved for future when we can allow extensible options like the host.104 options: {}105 },106 reporter: {107 constructor: args[0].reporter108 },109 profileBase: args[0].profileBase,110 desiredCapabilities: args[0].desiredCapabilities,111 hostLog: hostLogStream(args[0].hostLog),112 verbose: args[0].verbose113 });114 var mochaArgs = args[1].slice(2);115 // ui is required but only used by the child process...116 mochaArgs.push('--ui');117 mochaArgs.push(args[0].ui);118 runner.spawn(mochaArgs);119 var reporter = new args[0].reporter(runner.mochaRunnerProxy);120 runner.process.stdout.pipe(process.stdout);121 runner.process.stderr.pipe(process.stderr);122 runner.process.on('exit', process.exit);123 process.once('SIGINT', function() {124 // Let the child die whenever but we need to cleanup hosts in this125 // process...126 runner.process.removeListener('exit', process.exit);127 runner.destroy().catch(function(e) {128 process.nextTick(function() {129 // Throw any errors we can't deal with in the course of normal destroy.130 throw e;131 });132 });133 });134}135function showMochaHelp() {136 var mochaBin = resolveModule('mocha', 'bin', 'mocha');137 var proc = require('child_process').spawn(138 mochaBin, ['--help'], { stdio: 'inherit' }139 );140 proc.once('exit', process.exit);141}142/**143 * Helper to import the marionette desired capabilities144 */145function importDesiredCapabilities(path) {146 try {147 return require(path);148 } catch (e) {149 // Cannot parse marionette desired capabilities file.150 return;151 }152}153/**154Convert this host log argument into a stream (not done as a type to avoid155destructive operations when calling --help)156*/157function hostLogStream(value) {158 switch (value) {159 case 'stderr':160 case 'stdout':161 return process[value];162 default:163 return fs.createWriteStream(value);164 }165}166/**167@param {argparse.ArgumentParser} parser to extend.168@param {Object} module to use to extend parser.169@return {Array[argparse.Action]} list of actions.170*/171function extendParserWithModule(parser, module) {172 if (!module.help) return [];173 var help = module.help;174 assert(help.group, '.help must contain ".group"');175 assert(help.arguments, '.help must contain ".arguments"');176 var group = parser.addArgumentGroup(help.group);177 return Object.keys(help.arguments).map(function(arg) {178 return group.addArgument([arg], help.arguments[arg]);179 });180}181function extractOptionsFromModule(parsedArgs, actions) {182 return actions.reduce(function(result, action) {183 result[action.dest] = parsedArgs[action.dest];184 return result;185 }, {});186}187if (require.main === module) {188 main(argv);...
compiler.js
Source:compiler.js
...35 * and if that fails, attempts to load an npm module that exports a reporter36 * handler function, and if that fails, attempts to load the reporter relative37 * to the current working directory.38 */39function requireReporter(name) {40 const prefix = capitalize(camelcase(name));41 const locations = [`./reporters/${prefix}Reporter`, name, path.resolve(name)];42 let result = null;43 for (const location of locations) {44 try {45 // eslint-disable-next-line import/no-dynamic-require, global-require46 result = require(location);47 } catch (e) {48 // noop49 }50 if (result) {51 break;52 }53 }54 return result;55}56/**57 * Removes invalid webpack config properties leftover from applying flags58 */59function sanitize(config) {60 const configs = [].concat(config).map((conf) => {61 const result = merge({}, conf);62 delete result.progress;63 delete result.reporter;64 delete result.watchStdin;65 // TODO: remove the need for this66 for (const property of ['entry', 'output']) {67 const target = result[property];68 if (target && Object.keys(target).length === 0) {69 delete result[property];70 }71 }72 return result;73 });74 // if we always return an array, every compilation will be a MultiCompiler75 return configs.length > 1 ? configs : configs[0];76}77module.exports = (config) => {78 const log = weblog({ name: 'webpack', id: 'webpack-command' });79 const target = sanitize(config);80 const compiler = webpack(target);81 const { done, run } = compiler.hooks;82 const configs = [].concat(config);83 const [first] = configs;84 const { reporter: reporterName, watchOptions } = first;85 let ReporterClass = requireReporter(reporterName || 'stylish');86 if (!ReporterClass) {87 log.error(`The reporter specified (${reporterName}) could not be located`);88 ReporterClass = StylishReporter;89 }90 const reporter = new ReporterClass({ compiler, config });91 if (first.progress) {92 progress.apply(first, compiler, reporter);93 }94 run.tap('WebpackCommand', () => {95 log.info('Starting Build');96 });97 done.tap('WebpackCommand', () => {98 log.info('Build Finished');99 });...
SummaryReporter.test.js
Source:SummaryReporter.test.js
...13 rootDir: 'root',14 watch: false,15};16let results = [];17function requireReporter() {18 elric.isolateModules(() => {19 SummaryReporter = require('../SummaryReporter').default;20 });21}22beforeEach(() => {23 process.env.npm_lifecycle_event = 'test';24 process.env.npm_lifecycle_script = 'elric';25 process.stderr.write = result => results.push(result);26 Date.now = () => 10;27});28afterEach(() => {29 results = [];30 process.env = env;31 process.stderr.write = write;32 Date.now = now;33});34test('snapshots needs update with npm test', () => {35 const aggregatedResults = {36 numFailedTestSuites: 1,37 numFailedTests: 1,38 numPassedTestSuites: 0,39 numTotalTestSuites: 1,40 numTotalTests: 1,41 snapshot: {42 filesUnmatched: 1,43 total: 2,44 uncheckedKeysByFile: [],45 unmatched: 2,46 },47 startTime: 0,48 testResults: {},49 };50 process.env.npm_config_user_agent = 'npm';51 requireReporter();52 const testReporter = new SummaryReporter(globalConfig);53 testReporter.onRunComplete(new Set(), aggregatedResults);54 expect(results.join('')).toMatchSnapshot();55});56test('snapshots needs update with yarn test', () => {57 const aggregatedResults = {58 numFailedTestSuites: 1,59 numFailedTests: 1,60 numPassedTestSuites: 0,61 numTotalTestSuites: 1,62 numTotalTests: 1,63 snapshot: {64 filesRemovedList: [],65 filesUnmatched: 1,66 total: 2,67 uncheckedKeysByFile: [],68 unmatched: 2,69 },70 startTime: 0,71 testResults: {},72 };73 process.env.npm_config_user_agent = 'yarn';74 requireReporter();75 const testReporter = new SummaryReporter(globalConfig);76 testReporter.onRunComplete(new Set(), aggregatedResults);77 expect(results.join('')).toMatchSnapshot();78});79test('snapshots all have results (no update)', () => {80 const aggregatedResults = {81 numFailedTestSuites: 1,82 numFailedTests: 1,83 numPassedTestSuites: 0,84 numTotalTestSuites: 1,85 numTotalTests: 1,86 snapshot: {87 added: 1,88 didUpdate: false,89 filesAdded: 1,90 filesRemoved: 1,91 filesRemovedList: [],92 filesUnmatched: 1,93 filesUpdated: 1,94 matched: 2,95 total: 2,96 unchecked: 1,97 uncheckedKeysByFile: [98 {99 filePath: 'path/to/suite_one',100 keys: ['unchecked snapshot 1'],101 },102 ],103 unmatched: 1,104 updated: 1,105 },106 startTime: 0,107 testResults: {},108 };109 requireReporter();110 const testReporter = new SummaryReporter(globalConfig);111 testReporter.onRunComplete(new Set(), aggregatedResults);112 expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot();113});114test('snapshots all have results (after update)', () => {115 const aggregatedResults = {116 numFailedTestSuites: 1,117 numFailedTests: 1,118 numPassedTestSuites: 0,119 numTotalTestSuites: 1,120 numTotalTests: 1,121 snapshot: {122 added: 1,123 didUpdate: true,124 filesAdded: 1,125 filesRemoved: 1,126 filesRemovedList: [],127 filesUnmatched: 1,128 filesUpdated: 1,129 matched: 2,130 total: 2,131 unchecked: 1,132 uncheckedKeysByFile: [133 {134 filePath: 'path/to/suite_one',135 keys: ['unchecked snapshot 1'],136 },137 ],138 unmatched: 1,139 updated: 1,140 },141 startTime: 0,142 testResults: {},143 };144 requireReporter();145 const testReporter = new SummaryReporter(globalConfig);146 testReporter.onRunComplete(new Set(), aggregatedResults);147 expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot();...
summary_reporter.test.js
Source:summary_reporter.test.js
...13 rootDir: 'root',14 watch: false,15};16let results = [];17function requireReporter() {18 jest.isolateModules(() => {19 SummaryReporter = require('../summary_reporter').default;20 });21}22beforeEach(() => {23 process.env.npm_lifecycle_event = 'test';24 process.env.npm_lifecycle_script = 'jest';25 process.stderr.write = result => results.push(result);26 Date.now = () => 10;27});28afterEach(() => {29 results = [];30 process.env = env;31 process.stderr.write = write;32 Date.now = now;33});34test('snapshots needs update with npm test', () => {35 const aggregatedResults = {36 numFailedTestSuites: 1,37 numFailedTests: 1,38 numPassedTestSuites: 0,39 numTotalTestSuites: 1,40 numTotalTests: 1,41 snapshot: {42 filesUnmatched: 1,43 total: 2,44 uncheckedKeysByFile: [],45 unmatched: 2,46 },47 startTime: 0,48 testResults: {},49 };50 process.env.npm_config_user_agent = 'npm';51 requireReporter();52 const testReporter = new SummaryReporter(globalConfig);53 testReporter.onRunComplete(new Set(), aggregatedResults);54 expect(results.join('')).toMatchSnapshot();55});56test('snapshots needs update with yarn test', () => {57 const aggregatedResults = {58 numFailedTestSuites: 1,59 numFailedTests: 1,60 numPassedTestSuites: 0,61 numTotalTestSuites: 1,62 numTotalTests: 1,63 snapshot: {64 filesRemovedList: [],65 filesUnmatched: 1,66 total: 2,67 uncheckedKeysByFile: [],68 unmatched: 2,69 },70 startTime: 0,71 testResults: {},72 };73 process.env.npm_config_user_agent = 'yarn';74 requireReporter();75 const testReporter = new SummaryReporter(globalConfig);76 testReporter.onRunComplete(new Set(), aggregatedResults);77 expect(results.join('')).toMatchSnapshot();78});79test('snapshots all have results (no update)', () => {80 const aggregatedResults = {81 numFailedTestSuites: 1,82 numFailedTests: 1,83 numPassedTestSuites: 0,84 numTotalTestSuites: 1,85 numTotalTests: 1,86 snapshot: {87 added: 1,88 didUpdate: false,89 filesAdded: 1,90 filesRemoved: 1,91 filesRemovedList: [],92 filesUnmatched: 1,93 filesUpdated: 1,94 matched: 2,95 total: 2,96 unchecked: 1,97 uncheckedKeysByFile: [98 {99 filePath: 'path/to/suite_one',100 keys: ['unchecked snapshot 1'],101 },102 ],103 unmatched: 1,104 updated: 1,105 },106 startTime: 0,107 testResults: {},108 };109 requireReporter();110 const testReporter = new SummaryReporter(globalConfig);111 testReporter.onRunComplete(new Set(), aggregatedResults);112 expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot();113});114test('snapshots all have results (after update)', () => {115 const aggregatedResults = {116 numFailedTestSuites: 1,117 numFailedTests: 1,118 numPassedTestSuites: 0,119 numTotalTestSuites: 1,120 numTotalTests: 1,121 snapshot: {122 added: 1,123 didUpdate: true,124 filesAdded: 1,125 filesRemoved: 1,126 filesRemovedList: [],127 filesUnmatched: 1,128 filesUpdated: 1,129 matched: 2,130 total: 2,131 unchecked: 1,132 uncheckedKeysByFile: [133 {134 filePath: 'path/to/suite_one',135 keys: ['unchecked snapshot 1'],136 },137 ],138 unmatched: 1,139 updated: 1,140 },141 startTime: 0,142 testResults: {},143 };144 requireReporter();145 const testReporter = new SummaryReporter(globalConfig);146 testReporter.onRunComplete(new Set(), aggregatedResults);147 expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot();...
index.js
Source:index.js
...10 * @returns {Reporter} the resolved default reporter export11 * @throws {Error} when the reporter cannot be found, or if the default12 * export is not an instance of the base reporter class13 */14export function requireReporter(name) {15 let Reporter;16 if (typeof name === 'string') {17 let module = resolveLocal('reporter', name);18 Reporter = require(module).default;19 } else if (typeof name === 'function') {20 Reporter = name;21 name = Reporter.name;22 }23 if (!(Reporter && Reporter.prototype instanceof BaseReporter)) {24 throw new Error(`Invalid reporter "${name}"`);25 }26 return Reporter;27}28/**29 * Requires reporters and provides wrapper methods to invoke common30 * reporter methods.31 *32 * @private33 * @param {String[]} reporters - Reporters to require34 */35export default class ReporterManager {36 constructor(reporters, options = {}) {37 assign(this, {38 reporters: [].concat(reporters).map(module => {39 let Reporter = requireReporter(module);40 return new Reporter(options[Reporter.options]);41 })42 });43 }44 /**45 * Invokes the process method for all reporters46 *47 * @param {State} prev - The previous state instance48 * @param {State} next - The resulting state instance49 */50 process(prev, next) {51 for (let reporter of this.reporters) {52 reporter.process(prev, next);53 }...
require_reporter.js
Source:require_reporter.js
1'use strict';2/**3Helper to import the mocha reporters...4*/5module.exports = function requireReporter(argv, path) {6 var reporter;7 [8 argv.reporter,9 path,10 'mocha/lib/reporters/' + (path || 'dot')11 ].some(function(value) {12 try {13 reporter = require(value);14 return true;15 } catch (error) {16 return false;17 }18 });19 return reporter;...
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!