Best JavaScript code snippet using jest
install.integration.test.js
Source:install.integration.test.js
1const test = require('ava');2const {main} = require('../../src/install');3const {fakeStream, fakeSpawn, fakePkg, fakePrompt} = require('./utils');4const defaultMaxSize = 10000;5test('install just a single package and fail', async t => {6 const stream = fakeStream();7 const spawn = fakeSpawn();8 try {9 await main({10 argv: {_: ['lodash@4.12.0']},11 stream,12 spawn,13 defaultMaxSize,14 readPkg: fakePkg15 });16 throw new Error('Did not fail as spawned');17 } catch (err) {18 t.is(err.message, 'Install was canceled.');19 t.is(20 stream.getContent(),21 `â¹ Applying a size limit of 9.77KB from default22- Fetching stats for package lodash@4.12.023â Could not install for following reasons:24â lodash@4.12.0: size over threshold (63.65KB > 9.77KB)25â global constraint is respected26`27 );28 }29});30test('install just a single package and succeed', async t => {31 const stream = fakeStream();32 const spawn = fakeSpawn();33 //34 await main({35 argv: {_: ['bytes@3.0.0']},36 stream,37 spawn,38 defaultMaxSize,39 readPkg: fakePkg40 });41 t.is(42 stream.getContent(),43 `â¹ Applying a size limit of 9.77KB from default44- Fetching stats for package bytes@3.0.045â¹ Proceed to installation of package bytes@3.0.046`47 );48 t.is(spawn.invokedCmd, 'npm');49 t.deepEqual(spawn.invokedArgs, ['install', 'bytes@3.0.0']);50});51test('install just a single package and just warn', async t => {52 const stream = fakeStream();53 const spawn = fakeSpawn();54 await main({55 argv: {_: ['lodash@4.12.0'], w: true, warn: true, 'save-dev': true},56 stream,57 spawn,58 defaultMaxSize,59 readPkg: fakePkg60 });61 t.is(62 stream.getContent(),63 `â¹ Applying a size limit of 9.77KB from default64- Fetching stats for package lodash@4.12.065â Proceed to installation of packages lodash@4.12.0 despite following warnings:66â lodash@4.12.0: size over threshold (63.65KB > 9.77KB)67`68 );69 t.is(spawn.invokedCmd, 'npm');70 t.deepEqual(spawn.invokedArgs, ['install', 'lodash@4.12.0', '--save-dev']);71});72test('ask to install a package and accept', async t => {73 const stream = fakeStream();74 const spawn = fakeSpawn();75 const prompt = fakePrompt();76 await main({77 argv: {_: ['lodash@4.12.0'], i: true, interactive: true},78 stream,79 spawn,80 prompt,81 defaultMaxSize,82 readPkg: fakePkg83 });84 t.is(85 stream.getContent(),86 `â¹ Applying a size limit of 9.77KB from default87- Fetching stats for package lodash@4.12.088â Packages lodash@4.12.0 raised following warnings:89â lodash@4.12.0: size over threshold (63.65KB > 9.77KB)90â Proceeding with installation as you requested91`92 );93 t.is(spawn.invokedCmd, 'npm');94 t.deepEqual(spawn.invokedArgs, ['install', 'lodash@4.12.0']);95});96test('ask to install a package and deny', async t => {97 const stream = fakeStream();98 const spawn = fakeSpawn();99 const prompt = fakePrompt(false);100 await main({101 argv: {_: ['lodash@4.12.0'], i: true, interactive: true},102 stream,103 spawn,104 prompt,105 defaultMaxSize,106 readPkg: fakePkg107 });108 t.is(109 stream.getContent(),110 `â¹ Applying a size limit of 9.77KB from default111- Fetching stats for package lodash@4.12.0112â Packages lodash@4.12.0 raised following warnings:113â lodash@4.12.0: size over threshold (63.65KB > 9.77KB)114â Installation is canceled on your demand115`116 );117 t.is(spawn.invokedCmd, undefined);118});119test('try to install package that does not exist', async t => {120 const stream = fakeStream();121 const spawn = fakeSpawn();122 try {123 await main({124 argv: {_: ['no-sorry-but-i-do-not-exist']},125 stream,126 spawn,127 defaultMaxSize,128 readPkg: fakePkg129 });130 throw new Error('Exception was not triggered');131 } catch (err) {132 t.is(133 err.message,134 "no-sorry-but-i-do-not-exist: The package you were looking for doesn't exist."135 );136 }137});138test('install just a single package on empty package with global config and succeed', async t => {139 const stream = fakeStream();140 const spawn = fakeSpawn();141 await main({142 argv: {_: ['bytes@3.0.0']},143 stream,144 spawn,145 defaultMaxSize,146 readPkg: () => ({147 dependencies: {},148 'bundle-phobia': {149 'max-size': '20kB',150 'max-overall-size': '50kB'151 }152 })153 });154 t.is(155 stream.getContent(),156 `â¹ Applying a size limit of 20KB from package-config and overall size limit of 50KB from package-config157- Fetching stats for package bytes@3.0.0158â¹ Proceed to installation of package bytes@3.0.0159`160 );161 t.is(spawn.invokedCmd, 'npm');162 t.deepEqual(spawn.invokedArgs, ['install', 'bytes@3.0.0']);...
xclap.js
Source:xclap.js
...6const xclap = require("xclap");7const pkgFile = Path.resolve("package.json");8let pkgData;9require("electrode-archetype-njs-module-dev")(xclap);10function readPkg() {11 if (!pkgData) {12 pkgData = Fs.readFileSync(pkgFile);13 }14 return pkgData;15}16function replaceLine(file, oldLine, newLine) {17 const data = Fs.readFileSync(file, "utf8").split("\n");18 let found = 0;19 const newData = data.map(x => {20 if (x === oldLine) {21 found++;22 return newLine;23 }24 return x;25 });26 if (found !== 1) {27 throw new Error(`Replace file ${file} found ${found} old lines [${oldLine}]`);28 }29 Fs.writeFileSync(file, newData.join("\n"));30}31xclap.load("nvm", {32 prepack: {33 task: () => {34 const data = readPkg();35 const pkg = JSON.parse(data);36 pkg.scripts = { preinstall: pkg.scripts.preinstall };37 delete pkg.dependencies;38 delete pkg.nyc;39 delete pkg.devDependencies;40 mkdirp.sync(Path.resolve(".tmp"));41 Fs.writeFileSync(Path.resolve(".tmp/package.json"), data);42 Fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);43 }44 },45 postpack: {46 task: () => {47 Fs.writeFileSync(pkgFile, readPkg());48 }49 },50 ".prepare": [".clean-dist", "nvm/bundle", "~$git diff --quiet", "nvm/prepack"],51 release: {52 desc: "Release a new version to npm. package.json must be updated.",53 task: ["nvm/.prepare", "nvm/publish"],54 finally: ["nvm/postpack"]55 },56 ".clean-dist"() {57 const dist = Path.resolve("dist");58 rimraf.sync(dist);59 mkdirp.sync(dist);60 },61 bundle: "webpack",62 publish: "npm publish",63 version: {64 desc: "Bump version for release",65 dep: ["bundle", "~$git diff --quiet"],66 task() {67 const data = readPkg();68 const pkg = JSON.parse(data);69 const oldVer = `${pkg.version}`;70 let ver = oldVer.split(".").map(x => parseInt(x, 10));71 const bump = this.argv[1];72 switch (bump) {73 case "--major":74 ver[0]++;75 ver[1] = ver[2] = 0;76 break;77 case "--minor":78 ver[1]++;79 ver[2] = 0;80 break;81 case "--patch":...
test.js
Source:test.js
1/**2 * This program is free software; you can redistribute it and/or3 * modify it under the terms of the GNU General Public License4 * as published by the Free Software Foundation; under version 25 * of the License (non-upgradable).6 *7 * This program is distributed in the hope that it will be useful,8 * but WITHOUT ANY WARRANTY; without even the implied warranty of9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10 * GNU General Public License for more details.11 *12 * You should have received a copy of the GNU General Public License13 * along with this program; if not, write to the Free Software14 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.15 *16 * Copyright (c) 2020 Open Assessment Technologies SA;17 */18/**19 * Unit test the method updateVersion of module src/npmPackage.js20 */21const proxyquire = require('proxyquire');22const sinon = require('sinon');23const test = require('tape');24const folderName = 'folderName';25const version = '1.1.1';26const sandbox = sinon.sandbox.create();27const readPkg = sinon.stub().returns({});28const writePkg = sinon.stub();29const crossSpawn = () => ({30 on: (e, callback) => callback(0),31});32const npmPackage = proxyquire.noCallThru().load('../../../../src/npmPackage.js', {33 'cross-spawn': crossSpawn,34 'read-pkg': readPkg,35 'write-pkg': writePkg,36})();37test('should define updateVersion method on release instance', (t) => {38 t.plan(1);39 t.ok(typeof npmPackage.updateVersion === 'function', 'The release instance has updateVersion method');40 t.end();41});42test('should read package.sjon', async (t) => {43 t.plan(2);44 readPkg.reset();45 readPkg.returns({});46 await npmPackage.updateVersion(folderName);47 t.equal(readPkg.callCount, 1, 'read package.json');48 t.ok(readPkg.calledWith({ cwd: folderName }), 'read package.json');49 sandbox.restore();50 t.end();51});52test('should write package.sjon', async (t) => {53 t.plan(2);54 writePkg.reset();55 await npmPackage.updateVersion(folderName, version);56 t.equal(writePkg.callCount, 1, 'write package.json');57 t.ok(writePkg.calledWith(folderName, { version }), 'write package.json');58 sandbox.restore();59 t.end();...
npm-loader.js
Source:npm-loader.js
1"use strict";2const logger = require("../lib/logger");3const chalk = require("chalk");4const readPkgUp = require("read-pkg-up");5const myPkg = require("../package.json");6const config = require("./config");7const env = require("./env");8module.exports = (xrun, options) => {9 const readPkg = readPkgUp.sync();10 if (!readPkg) {11 return;12 }13 const Pkg = readPkg.packageJson;14 const pkgName = chalk.magenta(readPkg.path.replace(process.cwd(), "."));15 if (Pkg.scripts && options.npm !== false) {16 const scripts = {};17 for (const k in Pkg.scripts) {18 if (!k.startsWith("pre") && !k.startsWith("post")) {19 const pre = `pre${k}`;20 const post = `post${k}`;21 scripts[k] = xrun.serial(22 Pkg.scripts.hasOwnProperty(pre) && pre,23 xrun.exec(Pkg.scripts[k], "npm"),24 Pkg.scripts.hasOwnProperty(post) && post25 );26 } else {27 scripts[k] = xrun.exec(Pkg.scripts[k], "npm");28 }29 }30 xrun.load("npm", scripts);31 if (env.get(env.xrunPackagePath) !== readPkg.path) {32 logger.log(`Loaded npm scripts from ${pkgName} into namespace ${chalk.magenta("npm")}`);33 }34 env.set(env.xrunPackagePath, readPkg.path);35 }36 const pkgOptField = config.getPkgOpt(Pkg);37 const pkgConfig = pkgOptField && Pkg[pkgOptField];38 if (pkgConfig) {39 const tasks = Object.assign({}, pkgConfig.tasks);40 if (Object.keys(tasks).length > 0) {41 xrun.load("pkg", tasks);42 logger.log(43 `Loaded ${myPkg.name} tasks from ${pkgName} into namespace ${chalk.magenta("pkg")}`44 );45 }46 }...
read-pkg.js
Source:read-pkg.js
1declare module "read-pkg" {2 declare var npm$namespace$ReadPkg: {3 sync: typeof ReadPkg$sync4 };5 declare function ReadPkg$sync(6 path: string,7 options: ReadPkg$Options & {8 normalize: false9 }10 ): {11 [k: string]: any12 };13 declare function ReadPkg$sync(14 options: ReadPkg$Options & {15 normalize: false16 }17 ): {18 [k: string]: any19 };20 declare function ReadPkg$sync(options?: ReadPkg$Options): normalize.Package;21 declare function ReadPkg$sync(22 path?: string,23 options?: ReadPkg$Options24 ): normalize.Package;25 declare interface ReadPkg$Options {26 /**27 * [Normalize](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) the package data.28 * @default true29 */30 normalize?: boolean;31 }32 declare type ReadPkg$Package = normalize.Package;33 declare function ReadPkg(34 path: string,35 options: ReadPkg$Options & {36 normalize: false37 }38 ): Promise<{39 [k: string]: any40 }>;41 declare function ReadPkg(42 options: ReadPkg$Options & {43 normalize: false44 }45 ): Promise<{46 [k: string]: any47 }>;48 declare function ReadPkg(49 options?: ReadPkg$Options50 ): Promise<normalize.Package>;51 declare function ReadPkg(52 path?: string,53 options?: ReadPkg$Options54 ): Promise<normalize.Package>;55 declare export default typeof ReadPkg;...
pkg_event.js
Source:pkg_event.js
1var browserify = require('../');2var path = require('path');3var vm = require('vm');4var test = require('tap').test;5var expected = [6 readpkg('pkg_event'),7 readpkg('pkg_event/node_modules/aaa'),8 readpkg('pkg_event/node_modules/aaa/lib')9];10test('package event', function (t) {11 t.plan(2 + expected.length);12 13 var b = browserify(__dirname + '/pkg_event/main.js');14 b.on('package', function (pkg) {15 t.deepEqual(pkg, expected.shift());16 });17 18 b.bundle(function (err, src) {19 t.ifError(err);20 vm.runInNewContext(src, { console: { log: log } });21 function log (msg) { t.equal(msg, 555) }22 });23});24function readpkg (dir) {25 var pkg = require(path.join(__dirname, dir, 'package.json'));26 pkg.__dirname = path.join(__dirname, dir);27 return pkg;...
prepare-pkg.js
Source:prepare-pkg.js
1const fs = require('fs')2function readPkg(path) {3 return JSON.parse(fs.readFileSync(path + '/package.json'))4}5const root = readPkg('.')6// normally, npm prevents publishing private packages. but we are only private so7// we can use yarn workspaces. so remove this flag during packing.8delete root.private9// also delete workspaces, YAGNI10delete root.workspaces11// the server's dependencies are the only runtime dependencies12const server = readPkg('./server')13if (!root.dependencies) root.dependencies = {}14Object.assign(root.dependencies, server.dependencies)15fs.copyFileSync('./package.json', './package.json.bak')...
index.js
Source:index.js
...5 return findUp('package.json', opts).then(fp => {6 if (!fp) {7 return {};8 }9 return readPkg(fp, opts).then(pkg => ({pkg, path: fp}));10 });11};12module.exports.sync = opts => {13 const fp = findUp.sync('package.json', opts);14 if (!fp) {15 return {};16 }17 return {18 pkg: readPkg.sync(fp, opts),19 path: fp20 };...
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!!