How to use readPkg method in Jest

Best JavaScript code snippet using jest

install.integration.test.js

Source: install.integration.test.js Github

copy

Full Screen

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']);...

Full Screen

Full Screen

xclap.js

Source: xclap.js Github

copy

Full Screen

...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":...

Full Screen

Full Screen

test.js

Source: test.js Github

copy

Full Screen

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();...

Full Screen

Full Screen

npm-loader.js

Source: npm-loader.js Github

copy

Full Screen

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 }...

Full Screen

Full Screen

read-pkg.js

Source: read-pkg.js Github

copy

Full Screen

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;...

Full Screen

Full Screen

pkg_event.js

Source: pkg_event.js Github

copy

Full Screen

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;...

Full Screen

Full Screen

prepare-pkg.js

Source: prepare-pkg.js Github

copy

Full Screen

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')...

Full Screen

Full Screen

index.js

Source: index.js Github

copy

Full Screen

...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 };...

Full Screen

Full Screen

StackOverFlow community discussions

Questions
Discussion

How to test if a method returns an array of a class in Jest

How do node_modules packages read config files in the project root?

Jest: how to mock console when it is used by a third-party-library?

ERESOLVE unable to resolve dependency tree while installing a pacakge

Testing arguments with toBeCalledWith() in Jest

Is there assertCountEqual equivalent in javascript unittests jest library?

NodeJS: NOT able to set PERCY_TOKEN via package script with start-server-and-test

Jest: How to consume result of jest.genMockFromModule

How To Reset Manual Mocks In Jest

How to move &#39;__mocks__&#39; folder in Jest to /test?

Since Jest tests are runtime tests, they only have access to runtime information. You're trying to use a type, which is compile-time information. TypeScript should already be doing the type aspect of this for you. (More on that in a moment.)

The fact the tests only have access to runtime information has a couple of ramifications:

  • If it's valid for getAll to return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have had Entity elements in it if it hadn't been empty. All it can tell you is it got an array.

  • In the non-empty case, you have to check every element of the array to see if it's an Entity. You've said Entity is a class, not just a type, so that's possible. I'm not a user of Jest (I should be), but it doesn't seem to have a test specifically for this; it does have toBeTruthy, though, and we can use every to tell us if every element is an Entity:

    it('should return an array of Entity class', async () => {
         const all = await service.getAll()
         expect(all.every(e => e instanceof Entity)).toBeTruthy();
    });
    

    Beware, though, that all calls to every on an empty array return true, so again, that empty array issue raises its head.

If your Jest tests are written in TypeScript, you can improve on that by ensuring TypeScript tests the compile-time type of getAll's return value:

it('should return an array of Entity class', async () => {
    const all: Entity[] = await service.getAll()
    //       ^^^^^^^^^^
    expect(all.every(e => e instanceof Entity)).toBeTruthy();
});

TypeScript will complain about that assignment at compile time if it's not valid, and Jest will complain at runtime if it sees an array containing a non-Entity object.


But jonrsharpe has a good point: This test may not be useful vs. testing for specific values that should be there.

https://stackoverflow.com/questions/71717652/how-to-test-if-a-method-returns-an-array-of-a-class-in-jest

Blogs

Check out the latest blogs from LambdaTest on this topic:

19 Best Practices For Automation testing With Node.js

Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.

A Comprehensive Guide To Storybook Testing

Storybook offers a clean-room setting for isolating component testing. No matter how complex a component is, stories make it simple to explore it in all of its permutations. Before we discuss the Storybook testing in any browser, let us try and understand the fundamentals related to the Storybook framework and how it simplifies how we build UI components.

Top Automation Testing Trends To Look Out In 2020

Quality Assurance (QA) is at the point of inflection and it is an exciting time to be in the field of QA as advanced digital technologies are influencing QA practices. As per a press release by Gartner, The encouraging part is that IT and automation will play a major role in transformation as the IT industry will spend close to $3.87 trillion in 2020, up from $3.76 trillion in 2019.

How To Speed Up JavaScript Testing With Selenium and WebDriverIO?

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial and Selenium JavaScript Tutorial.

Blueprint for Test Strategy Creation

Having a strategy or plan can be the key to unlocking many successes, this is true to most contexts in life whether that be sport, business, education, and much more. The same is true for any company or organisation that delivers software/application solutions to their end users/customers. If you narrow that down even further from Engineering to Agile and then even to Testing or Quality Engineering, then strategy and planning is key at every level.

Jest Testing Tutorial

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.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest 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