Best JavaScript code snippet using jest
deep-equal.js
Source: deep-equal.js
...99function equals(a, b, customTesters) {100 customTesters = customTesters || [iterableEquality]101 return eq(a, b, [], [], customTesters)102}103function isAsymmetric(obj) {104 return obj && isA('Function', obj.asymmetricMatch)105}106function asymmetricMatch(a, b) {107 var asymmetricA = isAsymmetric(a),108 asymmetricB = isAsymmetric(b)109 if (asymmetricA && asymmetricB) {110 return undefined111 }112 if (asymmetricA) {113 return a.asymmetricMatch(b)114 }115 if (asymmetricB) {116 return b.asymmetricMatch(a)117 }118}119// Equality function lovingly adapted from isEqual in120// [Underscore](http://underscorejs.org)121function eq(a, b, aStack, bStack, customTesters) {122 var result = true...
matchersUtil.js
Source: matchersUtil.js
...40 }41 return message + '.';42 }43 };44 function isAsymmetric(obj) {45 return obj && j$.isA_('Function', obj.asymmetricMatch);46 }47 function asymmetricMatch(a, b) {48 var asymmetricA = isAsymmetric(a),49 asymmetricB = isAsymmetric(b);50 if (asymmetricA && asymmetricB) {51 return undefined;52 }53 if (asymmetricA) {54 return a.asymmetricMatch(b);55 }56 if (asymmetricB) {57 return b.asymmetricMatch(a);58 }59 }60 // Equality function lovingly adapted from isEqual in61 // [Underscore](http://underscorejs.org)62 function eq(a, b, aStack, bStack, customTesters) {63 var result = true;...
main.js
Source: main.js
1// https://stackoverflow.com/a/12646864/46083642function shuffle(array) {3 for (var i = array.length - 1; i > 0; i--) {4 var j = Math.floor(Math.random() * (i + 1));5 var temp = array[i];6 array[i] = array[j];7 array[j] = temp;8 }9}10// end util //11async function getPokes(count) {12 const pokeTextUrl = new URL(document.location.href).pathname.split('/').slice(0, -1).concat(['pokemon.txt']).join('/');13 const lines = (await (await fetch(pokeTextUrl)).text()).split('\n').filter(l => !!l);14 const pokes = lines.map(l => { const [name, spriteUrl] = l.split(' '); return { name, spriteUrl }; });15 const result = [];16 while (result.length < count && pokes.length > 0) {17 const index = Math.floor(Math.random() * pokes.length);18 const poke = pokes[index];19 pokes.splice(index, 1);20 result.push(poke);21 }22 return result;23}24async function phase1_intro($root, pokes) {25 $root.innerHTML = `26 <div style="text-align: center">27 <p>Make ${Math.pow(pokes.length, 2)} Pokemon comparisons and see what kind of order your opinion relation defines</p>28 <button onclick="document._phase1Resolve()">GO!</button>29 </div>30 `;31 return new Promise(resolve => document._phase1Resolve = resolve);32}33async function phase2_choices($root, pokes) {34 const choices = [];35 for (let i = 0; i < pokes.length; i++)36 for (let j = 0; j < i; j++)37 choices.push( [ pokes[i], pokes[j] ] );38 shuffle(choices);39 for (const choice of choices)40 shuffle(choice);41 const prefMat = {};42 for (const poke1 of pokes) {43 prefMat[poke1.name] = {};44 for (const poke2 of pokes) {45 prefMat[poke1.name][poke2.name] = undefined;46 }47 }48 for (const [poke1, poke2] of choices) {49 $root.innerHTML = `50 <div style="text-align: center">51 <p>Who do you prefer?</p>52 <div style="display: flex; align-items: center; padding: 20px; border: 1px solid grey;">53 ${ renderChoice(poke1) }54 <p style="width: 100px; text-align: center;">OR</p>55 ${ renderChoice(poke2) }56 </div>57 <br />58 <br />59 <button onclick="document._phase2Choose(null)">neither / don't know</button>60 </div>61 `;62 function renderChoice(poke, n) {63 const imgScaleFactor = document.body.offsetWidth > 800 ? 2 : 1;64 return `65 <p style="text-align: center">66 <img src="${poke.spriteUrl}" id="${poke.name}" style="width: ${96 * imgScaleFactor}px; image-rendering: pixelated;" />67 <br />68 <button onclick="document._phase2Choose('${poke.name}')">${poke.name}</button>69 </p>70 `;71 }72 await new Promise(resolve => {73 document._phase2Choose = function(chosenName) {74 prefMat[poke1.name][poke2.name] = chosenName;75 prefMat[poke2.name][poke1.name] = chosenName;76 resolve();77 }78 });79 }80 return prefMat;81}82async function phase3_results($root, prefMat, pokes) {83 const pokeSpriteUrlByName = {};84 for (const poke of pokes)85 pokeSpriteUrlByName[poke.name] = poke.spriteUrl;86 const imgStyle = 'style="' + (document.body.offsetWidth < 800 ? `width: ${96 / 2}px;` : '') + '"';87 let table = '<table>';88 table += '<tr>';89 table += '<td></td>';90 const row1 = prefMat[Object.keys(prefMat)[0]];91 for (let j = 0; j < Object.keys(row1).length; j++) {92 const colPokeName = Object.keys(row1).reverse()[j];93 table += `<td><img src="${pokeSpriteUrlByName[colPokeName]}" ${imgStyle} /></td>`;94 }95 table += '</tr>';96 for (let i = 0; i < Object.keys(prefMat).length; i++) {97 const rowPokeName = Object.keys(prefMat)[i];98 const row = prefMat[rowPokeName];99 table += '<tr>';100 table += `<td><img src="${pokeSpriteUrlByName[rowPokeName]}" ${imgStyle} /></td>`;101 for (let j = 0; j < Object.keys(row).length - i - 1; j++) {102 const colPokeName = Object.keys(row).reverse()[j];103 table += '<td>';104 const prefName = prefMat[rowPokeName][colPokeName];105 if (!prefName)106 table += 'n/a';107 else108 table += `<img src="${pokeSpriteUrlByName[prefName]}" ${imgStyle} />`;109 table += '</td>';110 }111 table += '</tr>';112 }113 table += '</table>';114 const { classification, isTotal, isAsymmetric, isTransitive } = classify(prefMat);115 $root.innerHTML = `116 <div style="display: flex; flex-wrap: wrap; text-align: center; justify-content: center;">117 <div>118 <h3>Preference Matrix</h3>119 <br />120 ${table}121 <style>122 table { border-collapse: collapse; }123 table tr:first-child { border-bottom: 1px solid grey; }124 table tr td:first-child { border-right: 1px solid grey; }125 </style>126 </div>127 <br />128 <br />129 <div style="width: 150px; padding: 0 50px;">130 <h3>Properties</h3>131 <br />132 <p>Transitive? ${renderBool(isTransitive)}</p>133 <p>Asymmetric? ${renderBool(isAsymmetric)}</p>134 <p>Total? ${renderBool(isTotal)}</p>135 <br />136 <p>Your preferences form <b>${classification ? 'a ' + classification : 'nothing special'}</b>!</p>137 </div>138 </div>139 `;140 function renderBool(b) {141 return b ? 'YES' : 'NO';142 }143}144function classify(prefMat) {145 // n.b. not very computationally efficient146 // Assumed147 const isReflexive = true;148 let isTotal = true;149 for (let a in prefMat)150 for (let b in prefMat[a])151 if (a !== b)152 isTotal = isTotal && !!prefMat[a][b];153 // Assumed154 const isAsymmetric = true;155 let isTransitive = true;156 for (let a in prefMat)157 for (let b in prefMat)158 for (let c in prefMat)159 if (a !== b && b !== c && c !== a)160 if (prefMat[a][b] === b && prefMat[b][c] === c && !!prefMat[a] && !!prefMat[b] && !!prefMat[c])161 isTransitive = isTransitive && (prefMat[a][c] === c);162 const classification = (163 isReflexive && isTransitive && isAsymmetric && isTotal ? 'linear order'164 : isReflexive && isTransitive && isAsymmetric ? 'partial order'165 : isReflexive && isTransitive ? 'preorder'166 : null167 );168 return { classification, isReflexive, isTotal, isAsymmetric, isTransitive };169}170async function main() {171 const pokes = await getPokes(5);172 const $root = document.getElementById('root');173 await phase1_intro($root, pokes);174 const prefMat = await phase2_choices($root, pokes);175 await phase3_results($root, prefMat, pokes);176}177console.log('ok');...
base-provider.js
Source: base-provider.js
...95 if (this.isUnsigned()) {96 return this.getNoneKey()97 }9899 return this.isAsymmetric()100 ? this.getPrivateKey()101 : this.getSecret()102 }103104 /**105 * Determines whether to use the 'none' algorithm.106 *107 * @returns {Boolean}108 */109 isUnsigned () {110 return this.noneAlgorithm.includes(111 this.getAlgorithm()112 )113 }114115 /**116 * Determines whether the used algorithm is asymmetric.117 *118 * @returns {Boolean}119 */120 isAsymmetric () {121 return this.asymmetricAlgorithms.includes(122 this.getAlgorithm()123 )124 }125126 /**127 * Returns the 'None' key object that can be used with128 * the 'jose' package to opt-in for unsecured JWS.129 *130 * @returns {Object}131 */132 getNoneKey () {133 return JWK.None134 }135136 /**137 * Returns the signing key, either the secret or public key.138 * This method ensures to read the public key from the139 * file system and returns the content string.140 *141 * @returns {String}142 */143 async getVerificationKey () {144 return this.isAsymmetric()145 ? this.getPublicKey()146 : this.getSecret()147 }148149 /**150 * Returns the signing secret.151 *152 * @returns {String}153 */154 async getSecret () {155 return this.secret156 }157158 /**
...
RadicalComposedNodeWidget.jsx
Source: RadicalComposedNodeWidget.jsx
1import React from 'react';2import { PortWidget } from '@projectstorm/react-diagrams';3import Typography from '@material-ui/core/Typography';4import AccountTreeIcon from '@material-ui/icons/AccountTree';5import Box from '@material-ui/core/Box';6import PropTypes from 'prop-types';7import values from 'lodash/fp/values';8import { getPortStyle } from '../helpers';9import EditableLabel from '../../../../components/EditableLabel';10import NodeContextPanel from '../../../../components/NodeContextPanel';11import { getCanvasNode } from '../../../../../tests/getDataTestId';12import NodeDescriptionIcon from '../../../../components/NodeDescriptionIcon';13const composedIconStyle = {14 position: 'absolute',15 width: 20,16 height: 20,17 left: 15,18 top: 10,19};20const smartPortStyle = {21 width: '16px',22 height: '16px',23};24const RadicalComposedNodeWidget = ({25 node,26 engine,27 children,28 isSelected,29 name,30 isExpanded,31 isAsymmetric,32}) => (33 <div data-testid={getCanvasNode(name)}>34 <div35 style={{36 position: 'relative',37 width: node.width,38 height: node.height,39 color: isExpanded ? '#2f2f2f' : '#ffffff',40 }}41 >42 <div43 style={{44 position: 'absolute',45 width: node.width,46 height: node.height,47 alignItems: isExpanded ? '' : 'center',48 textAlign: 'center',49 display: 'flex',50 justifyContent: 'center',51 top: isAsymmetric ? 20 : 0,52 }}53 >54 <NodeDescriptionIcon node={node} isParentAsymmetric={isAsymmetric} />55 <div56 style={{57 overflow: 'hidden',58 textOverflow: 'ellipsis',59 marginLeft: 7,60 marginRight: 7,61 top: isAsymmetric ? 20 : 0,62 }}63 >64 <EditableLabel65 editedItem={node}66 isItemSelected={isSelected}67 variant="body2"68 label={name}69 width={node.width - 14}70 />71 {node.options.attributes?.technology ? (72 <Typography variant="caption">73 [{node.options.radical_type}:{node.options.attributes?.technology}74 ]75 </Typography>76 ) : (77 <Typography noWrap variant="caption">78 [{node.options.radical_type}]79 </Typography>80 )}81 </div>82 </div>83 <svg width={node.width} height={node.height}>84 <g id="Layer_1">${children}</g>85 </svg>86 {values(node.getPorts()).map((port) => (87 <PortWidget88 style={getPortStyle(89 node.width,90 node.height,91 port.getOptions().alignment,92 port.order93 )}94 key={port.getOptions().name}95 port={port}96 engine={engine}97 >98 <Box sx={smartPortStyle} />99 </PortWidget>100 ))}101 </div>102 {!node.isLocked() && <NodeContextPanel node={node} />}103 {!node.isSelected() && !node.options.isExpanded && node.options.isParent && (104 <Box sx={composedIconStyle}>105 <AccountTreeIcon fontSize="small" />106 </Box>107 )}108 </div>109);110RadicalComposedNodeWidget.propTypes = {111 node: PropTypes.objectOf(PropTypes.any).isRequired,112 engine: PropTypes.objectOf(PropTypes.any).isRequired,113 children: PropTypes.element.isRequired,114 isSelected: PropTypes.bool.isRequired,115 name: PropTypes.string.isRequired,116 isExpanded: PropTypes.bool.isRequired,117 isAsymmetric: PropTypes.bool.isRequired,118};...
matchers.js
Source: matchers.js
...19/*20 * Taken from21 * https://github.com/facebook/jest/blob/be4bec387d90ac8d6a7596be88bf8e4994bc3ed9/packages/expect/src/jasmine_utils.js#L3622 */23function isAsymmetric(obj) {24 return obj && isA('Function', obj.asymmetricMatch)25}26function valueMatches(declaration, value) {27 if (value instanceof RegExp) {28 return value.test(declaration.value)29 }30 if (isAsymmetric(value)) {31 return value.asymmetricMatch(declaration.value)32 }33 return value === declaration.value34}35function toHaveStyleRule(36 received: *,37 property: *,38 value: *,39 options?: { target?: string, media?: string } = {}40) {41 const { target, media } = options42 const classNames = getClassNamesFromNodes([received])43 const cssString = getStylesFromClassNames(classNames, getStyleElements())44 const styles = css.parse(cssString)...
utils.js
Source: utils.js
...8export function applyJestMatcher(matcher, received, ...args) {9 return matcher.apply({ isNot: false, promise: '' }, [received, ...args])10}11export function resolveExpected(expected) {12 return isAsymmetric(expected)13 ? expected.toCypressOutput14 ? expected.toCypressOutput()15 : expected.toString()16 : expected17}18export function isPromise(obj) {19 return (20 !!obj &&21 (typeof obj === 'object' || typeof obj === 'function') &&22 typeof obj.then === 'function'23 )24}25export function isAsymmetric(obj) {26 return !!obj && isA('Function', obj.asymmetricMatch)27}28export function isA(typeName, value) {29 return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'30}31// Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/src/Angular.js#L685-L69332export function isError(value) {33 switch (Object.prototype.toString.call(value)) {34 case '[object Error]':35 return true36 case '[object Exception]':37 return true38 case '[object DOMException]':39 return true...
equals.js
Source: equals.js
...10module.exports = function equals(a, b) {11 return isEqual(a, b, customMatcher);12};13function customMatcher(a, b) {14 const aIsAsymmetric = isAsymmetric(a);15 const bIsAsymmetric = isAsymmetric(b);16 if (aIsAsymmetric && !bIsAsymmetric) {17 return a.asymmetricMatch(b);18 }19 if (bIsAsymmetric && !aIsAsymmetric) {20 return b.asymmetricMatch(a);21 }22}23function isAsymmetric(object) {24 return object && typeof object.asymmetricMatch === 'function';...
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!!