Best JavaScript code snippet using jest
index.js
Source: index.js
1/* eslint-disable jsdoc/no-undefined-types */2import _fs, { promises as fs } from 'fs';3import path from 'path';4import { promisify } from 'util';5import enhancedResolve from 'enhanced-resolve';6import postcss from 'postcss';7import _import from 'postcss-import';8// @ts-ignore9import _importSync from 'postcss-import-sync2';10// @ts-ignore11import allSettled from '@ungap/promise-all-settled';12/**13 * @typedef {import('sass').ImporterReturnType} sass.ImporterReturnType14 * @typedef {import('sass').Options} sass.Options15 */16/**17 * @typedef {(18 * this: { fromImport: boolean, options: { includePaths: string } },19 * url: string,20 * prev: string,21 * done?: (data: sass.ImporterReturnType) => void,22 * ) => sass.ImporterReturnType | void} Importer23 */24/**25 * @typedef {({status: 'fulfilled', value: any, reason?: undefined}|{status: 'rejected', reason: unknown, value?: undefined})} SettledResult26 */27/**28 * @param {Function[]} tasks29 *30 * @returns {SettledResult[]}31 */32function allSettledSync(tasks) {33 return tasks.map((task) => {34 try {35 return { status: 'fulfilled', value: task() };36 } catch (/** @type {any} */ error_) {37 /** @type {Error} */38 const error = error_;39 return { status: 'rejected', reason: error };40 }41 });42}43function createResolvers(sync = false) {44 const { extensions, conditionNames, mainFiles, ...resolveOptions } = {45 extensions: ['.css'],46 conditionNames: ['style', 'browser', 'import', 'require', 'node'],47 mainFields: ['style', 'browser', 'module', 'main'],48 mainFiles: ['index'],49 modules: ['node_modules']50 };51 const createResolveOptions = {52 extensions: ['.scss', ...extensions],53 conditionNames: ['sass', ...conditionNames],54 mainFiles: ['_index', ...mainFiles],55 ...resolveOptions56 };57 const createGenericResolveOptions = {58 extensions,59 conditionNames,60 mainFiles,61 ...resolveOptions62 };63 if (sync) {64 const resolve = enhancedResolve.create.sync(createResolveOptions);65 const genericResolve = enhancedResolve.create.sync(66 createGenericResolveOptions67 );68 const cssProcessor = postcss([69 _importSync({70 resolve: (71 /** @type {string} */ id,72 /** @type {string} */ basedir73 ) => genericResolve(basedir, id)74 })75 ]);76 return {77 resolve,78 genericResolve,79 cssProcessor80 };81 }82 /** @type {(basedir: string, id: string) => Promise<string>} */83 const resolve = promisify(enhancedResolve.create(createResolveOptions));84 /** @type {(basedir: string, id: string) => Promise<string>} */85 const genericResolve = promisify(86 enhancedResolve.create(createGenericResolveOptions)87 );88 // @ts-ignore89 const cssProcessor = postcss([90 _import({91 resolve: (id, basedir) => genericResolve(basedir, id)92 })93 ]);94 return {95 resolve,96 cssProcessor97 };98}99/**100 * Sass importer to import Sass modules using (enhanced) Node resolve.101 */102function api() {103 const { resolve, cssProcessor } = createResolvers();104 const { resolve: resolveSync, cssProcessor: cssProcessorSync } =105 createResolvers(true);106 /**107 * @param {string} includePaths108 */109 function asyncFunction(includePaths) {110 /** @type {Importer} */111 return async function (url, previous, _done) {112 const done = typeof _done !== 'undefined' ? _done : () => {};113 /** @type {string?} */114 let filePath = null;115 try {116 if (previous === 'stdin') {117 /** @type {SettledResult[]} */118 const filePaths = await allSettled.call(119 Promise,120 includePaths121 .split(':')122 .map((includePath) =>123 path.isAbsolute(includePath)124 ? includePath125 : path.resolve(process.cwd(), includePath)126 )127 .map((includePath) => resolve(includePath, url))128 );129 const foundFilePath = filePaths.find(130 ({ status }) => status === 'fulfilled'131 );132 filePath =133 typeof foundFilePath !== 'undefined'134 ? foundFilePath.value135 : null;136 } else {137 const foundFilePath = await resolve(138 path.dirname(previous),139 url140 );141 filePath = foundFilePath || null;142 }143 } catch (error) {144 /* istanbul ignore next */145 filePath = null;146 }147 /* istanbul ignore next */148 if (filePath === null) {149 done(null);150 return;151 }152 if (path.extname(filePath) !== '.css') {153 done({ file: filePath });154 return;155 }156 const css = await fs.readFile(filePath, 'utf8');157 if (!css.includes('@import')) {158 done({ file: filePath });159 return;160 }161 try {162 const result = await cssProcessor.process(css, {163 from: filePath164 });165 done({ contents: result.css });166 } catch (/** @type {any} */ error_) {167 /** @type {Error} */168 const error = error_;169 /* istanbul ignore next */170 done(error);171 }172 };173 }174 /**175 * @param {string} includePaths176 */177 function syncFunction(includePaths) {178 /** @type {Importer} */179 return function (url, previous) {180 /** @type {string?} */181 let filePath = null;182 try {183 if (previous === 'stdin') {184 const filePaths = allSettledSync.call(185 null,186 includePaths187 .split(':')188 .map((includePath) =>189 path.isAbsolute(includePath)190 ? includePath191 : path.resolve(process.cwd(), includePath)192 )193 .map(194 (includePath) => () =>195 resolveSync(includePath, url)196 )197 );198 const foundFilePath = filePaths.find(199 ({ status }) => status === 'fulfilled'200 );201 filePath =202 typeof foundFilePath !== 'undefined'203 ? foundFilePath.value204 : null;205 } else {206 const foundFilePath = resolveSync(207 path.dirname(previous),208 url209 );210 // @ts-ignore211 filePath = foundFilePath || null;212 }213 } catch (error) {214 /* istanbul ignore next */215 filePath = null;216 }217 /* istanbul ignore next */218 if (filePath === null) {219 return null;220 }221 if (path.extname(filePath) !== '.css') {222 return { file: filePath };223 }224 const css = _fs.readFileSync(filePath, 'utf8');225 if (!css.includes('@import')) {226 return { file: filePath };227 }228 try {229 const result = cssProcessorSync.process(css, {230 from: filePath231 });232 return { contents: result.css };233 } catch (/** @type {any} */ error_) {234 /** @type {Error} */235 const error = error_;236 /* istanbul ignore next */237 return error;238 }239 };240 }241 /**242 * @type {Importer}243 */244 function main(...arguments_) {245 const { includePaths } = this.options;246 const [url, previous, done] = arguments_;247 asyncFunction(includePaths).apply(this, [url, previous, done]);248 }249 /**250 * @type {Importer}251 */252 function sync(...arguments_) {253 const { includePaths } = this.options;254 const [url, previous] = arguments_;255 return syncFunction(includePaths).apply(this, [url, previous]);256 }257 /**258 * Sass importer to import Sass modules using (enhanced) Node resolve. Synchronous version.259 */260 main.sync = sync;261 return main;262}...
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 '__mocks__' 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.
Check out the latest blogs from LambdaTest on this topic:
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.
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.
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.
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.
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.
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!!