Best JavaScript code snippet using jest
PrimitiveHelpers.js
Source: PrimitiveHelpers.js
1'use strict';2var Cesium = require('cesium');3var deepEqual = require('deep-equal');4var AccessorReader = require('./AccessorReader');5var getPrimitiveAttributeSemantics = require('./getPrimitiveAttributeSemantics');6var readAccessor = require('./readAccessor');7var AttributeCompression = Cesium.AttributeCompression;8var Cartesian3 = Cesium.Cartesian3;9var Matrix4 = Cesium.Matrix4;10var WebGLConstants = Cesium.WebGLConstants;11var defined = Cesium.defined;12module.exports = {13 getAllPrimitives : getAllPrimitives,14 getPrimitivesByMaterialMode : getPrimitivesByMaterialMode,15 getPrimitiveConflicts : getPrimitiveConflicts,16 primitiveEquals : primitiveEquals,17 primitivesShareAttributeAccessor: primitivesShareAttributeAccessor,18 primitivesHaveOverlappingIndexAccessors : primitivesHaveOverlappingIndexAccessors,19 transformPrimitives : transformPrimitives20};21/**22 * Compare two primitives to check if they share an attribute accessor.23 *24 * @param {Object} primitive The first primitive to compare.25 * @param {Object} comparePrimitive The second primitive to compare.26 * @param {String[]} [attributesToCheck] An array of attributes to check for sharing. Defaults to checking all attributes.27 * @returns {Boolean} True if primitives share an attribute, false otherwise.28 */29function primitivesShareAttributeAccessor(primitive, comparePrimitive, attributesToCheck) {30 var attributes = primitive.attributes;31 var compareAttributes = comparePrimitive.attributes;32 for (var attribute in attributes) {33 if (!defined(attributesToCheck) || (attributesToCheck.indexOf(attribute) !== -1)) {34 if (attributes.hasOwnProperty(attribute)) {35 if (compareAttributes.hasOwnProperty(attribute)) {36 if (attributes[attribute] === compareAttributes[attribute]) {37 return true;38 }39 }40 }41 }42 }43 return false;44}45/**46 * Compare two primitives to check if they have an overlapping index accessor.47 *48 * @param {Object} gltf A javascript object containing a glTF asset.49 * @param {Object} primitive The first primitive to compare.50 * @param {Object} comparePrimitive The second primitive to compare.51 * @returns {Boolean} True if primitives have an overlapping index accessor, false otherwise.52 */53function primitivesHaveOverlappingIndexAccessors(gltf, primitive, comparePrimitive) {54 var accessors = gltf.accessors;55 var indexAccessorId = primitive.indices;56 var compareIndexAccessorId = comparePrimitive.indices;57 if (!defined(indexAccessorId) || !defined(compareIndexAccessorId)) {58 return false;59 }60 if (indexAccessorId === compareIndexAccessorId) {61 return true;62 }63 var indexAccessor = accessors[indexAccessorId];64 var compareIndexAccessor = accessors[compareIndexAccessorId];65 var indices = [];66 readAccessor(gltf, indexAccessor, indices);67 var accessorReader = new AccessorReader(gltf, compareIndexAccessor);68 var value = [];69 while (!accessorReader.pastEnd()) {70 var index = accessorReader.read(value)[0];71 if (indices.indexOf(index) >= 0) {72 return true;73 }74 accessorReader.next();75 }76 return false;77}78/**79 * Apply a given transform to an array of primitives.80 *81 * @param {Object} gltf A javascript object containing a glTF asset.82 * @param {Object[]} primitives An array containing the primitives that need to be transformed.83 * @param {Matrix4} transform The transform to apply to the primitives.84 */85function transformPrimitives(gltf, primitives, transform) {86 var inverseTranspose = new Matrix4();87 if (Matrix4.equals(transform, Matrix4.IDENTITY)) {88 return;89 }90 var accessors = gltf.accessors;91 Matrix4.inverseTransformation(transform, inverseTranspose);92 Matrix4.transpose(inverseTranspose, inverseTranspose);93 var scratchIndexArray = [];94 var scratchCartesianArray = [];95 var scratchCartesian = new Cartesian3();96 var doneIndicesByAccessor = {};97 var primitivesLength = primitives.length;98 for (var i = 0; i < primitivesLength; i++) {99 var primitive = primitives[i];100 var attributes = primitive.attributes;101 var indexAccessorReader;102 var index = 0;103 if (defined(primitive.indices)) {104 indexAccessorReader = new AccessorReader(gltf, accessors[primitive.indices]);105 indexAccessorReader.read(scratchIndexArray);106 index = scratchIndexArray[0];107 }108 var positionAccessorReader;109 var positionSemantics = getPrimitiveAttributeSemantics(primitive, 'POSITION');110 var positionAccessorId = attributes[positionSemantics[0]];111 if (positionSemantics.length > 0) {112 doneIndicesByAccessor[positionAccessorId] = {};113 positionAccessorReader = new AccessorReader(gltf, accessors[positionAccessorId]);114 }115 var normalAccessorReader;116 var normalSemantics = getPrimitiveAttributeSemantics(primitive, 'NORMAL');117 var normalAccessorId = attributes[normalSemantics[0]];118 var isOctEncoded = false;119 if (normalSemantics.length > 0) {120 doneIndicesByAccessor[normalAccessorId] = {};121 var normalAccessor = accessors[normalAccessorId];122 normalAccessorReader = new AccessorReader(gltf, normalAccessor);123 isOctEncoded = normalAccessor.type === 'VEC2';124 }125 var keepReading = true;126 while (keepReading) {127 if (defined(positionAccessorReader) && !doneIndicesByAccessor[positionAccessorId][index]) {128 positionAccessorReader.index = index;129 positionAccessorReader.read(scratchCartesianArray);130 Cartesian3.unpack(scratchCartesianArray, 0, scratchCartesian);131 Matrix4.multiplyByPoint(transform, scratchCartesian, scratchCartesian);132 Cartesian3.pack(scratchCartesian, scratchCartesianArray);133 positionAccessorReader.write(scratchCartesianArray);134 doneIndicesByAccessor[positionAccessorId][index] = true;135 }136 if (defined(normalAccessorReader) && !doneIndicesByAccessor[normalAccessorId][index]) {137 normalAccessorReader.index = index;138 normalAccessorReader.read(scratchCartesianArray);139 Cartesian3.unpack(scratchCartesianArray, 0, scratchCartesian);140 if (isOctEncoded) {141 // Un-encode oct-encoded normals142 if (normalAccessorReader.componentType === WebGLConstants.BYTE) {143 // Normalize if these are written to signed bytes144 scratchCartesian.x += 128;145 scratchCartesian.y += 128;146 }147 AttributeCompression.octDecode(scratchCartesian.x, scratchCartesian.y, scratchCartesian);148 }149 Matrix4.multiplyByPointAsVector(inverseTranspose, scratchCartesian, scratchCartesian);150 Cartesian3.normalize(scratchCartesian, scratchCartesian);151 if (isOctEncoded) {152 // Re-encode oct-encoded normals153 AttributeCompression.octEncode(scratchCartesian, scratchCartesian);154 if (normalAccessorReader.componentType === WebGLConstants.BYTE) {155 // De-normalize back to signed bytes156 scratchCartesian.x -= 128;157 scratchCartesian.y -= 128;158 }159 }160 Cartesian3.pack(scratchCartesian, scratchCartesianArray);161 normalAccessorReader.write(scratchCartesianArray);162 doneIndicesByAccessor[normalAccessorId][index] = true;163 }164 if (defined(indexAccessorReader)) {165 if (!indexAccessorReader.pastEnd()) {166 indexAccessorReader.next();167 indexAccessorReader.read(scratchIndexArray);168 index = scratchIndexArray[0];169 } else {170 keepReading = false;171 }172 } else if (!positionAccessorReader.pastEnd() && !normalAccessorReader.pastEnd()) {173 index++;174 } else {175 keepReading = false;176 }177 }178 }179}180/**181 * Returns primitives mapped to mode mapped to material.182 *183 * @param {Object[]} primitives An array containing the primitives to sort.184 * @returns {Object} An object mapping material ids to mode to an array of primitives.185 */186function getPrimitivesByMaterialMode(primitives) {187 var primitivesLength = primitives.length;188 var primitivesByMaterialMode = {};189 for (var i = 0; i < primitivesLength; i++) {190 var primitive = primitives[i];191 var materialId = primitive.material;192 var primitivesByMode = primitivesByMaterialMode[materialId];193 if (!defined(primitivesByMode)) {194 primitivesByMode = {};195 primitivesByMaterialMode[materialId] = primitivesByMode;196 }197 var mode = primitive.mode;198 var primitivesArray = primitivesByMode[mode];199 if (!defined(primitivesArray)) {200 primitivesArray = [];201 primitivesByMode[mode] = primitivesArray;202 }203 primitivesArray.push(primitive);204 }205 return primitivesByMaterialMode;206}207/**208 * Return primitives that share attribute accessors with a given primitive.209 *210 * @param {Object[]} primitives An array of primitive objects to compare the primitive against.211 * @param {Object} primitive The primitive to compare for conflicts.212 * @returns {Number[]} An array containing indices of primitives that have attribute accessor conflicts.213 */214function getPrimitiveConflicts(primitives, primitive) {215 var primitivesLength = primitives.length;216 var conflicts = [];217 for (var i = 0; i < primitivesLength; i++) {218 var otherPrimitive = primitives[i];219 if (primitive !== otherPrimitive && primitivesShareAttributeAccessor(primitive, otherPrimitive)) {220 conflicts.push(i);221 }222 }223 return conflicts;224}225/**226 * Return all the primitives in the meshes of the glTF asset.227 *228 * @param {Object} gltf A javascript object containing a glTF asset.229 * @returns {Object[]} An array containing all the primitives.230 */231function getAllPrimitives(gltf) {232 var primitives = [];233 var meshes = gltf.meshes;234 for (var meshId in meshes) {235 if (meshes.hasOwnProperty(meshId)) {236 var mesh = meshes[meshId];237 primitives = primitives.concat(mesh.primitives);238 }239 }240 return primitives;241}242/**243 * Compare two primitives to check if they are equal.244 *245 * @param {Object} primitiveOne The first primitive to compare.246 * @param {Object} primitiveTwo The second primitive to compare.247 * @returns {Boolean} True if primitives are the same, false otherwise.248 */249function primitiveEquals(primitiveOne, primitiveTwo) {250 return primitiveOne.mode === primitiveTwo.mode &&251 primitiveOne.material === primitiveTwo.material &&252 primitiveOne.indices === primitiveTwo.indices &&253 deepEqual(primitiveOne.attributes, primitiveTwo.attributes);...
index.js
Source: index.js
...103 case 'string':104 return (0, _diffLines.default)(a, b, options);105 case 'boolean':106 case 'number':107 return comparePrimitive(a, b, options);108 case 'map':109 return compareObjects(sortMap(a), sortMap(b), options);110 case 'set':111 return compareObjects(sortSet(a), sortSet(b), options);112 default:113 return compareObjects(a, b, options);114 }115}116function comparePrimitive(a, b, options) {117 return (0, _diffLines.default)(118 (0, _prettyFormat.default)(a, FORMAT_OPTIONS),119 (0, _prettyFormat.default)(b, FORMAT_OPTIONS),120 options121 );122}123function sortMap(map) {124 return new Map(Array.from(map.entries()).sort());125}126function sortSet(set) {127 return new Set(Array.from(set.values()).sort());128}129function compareObjects(a, b, options) {130 let diffMessage;...
alphaLess.js
Source: alphaLess.js
...99 }100 return r;101 }102 103 function comparePrimitive( a, b ) {104 if( a < b ) {105 return -1;106 }107 else if( a > b ) {108 return 1;109 }110 else {111 return 0;112 }113 }114 115 function compareTok( a, b, compareLeadZeroes ) {116 var aNum = isDigit( a.charAt( 0 ) );117 var bNum = isDigit( b.charAt( 0 ) );118 119 if( aNum !== bNum ) {120 return aNum ? -1 : 1;121 }122 else if( aNum && bNum ) {123 var cmp = comparePrimitive( Number(a), Number(b) );124 if( cmp === 0 && compareLeadZeroes ) {125 return comparePrimitive( b.length, a.length );126 }127 else {128 return cmp;129 }130 }131 else {132 return comparePrimitive( a, b );133 }134 }135 136 function compareTokArrays( tok1, tok2, compareLeadZeroes ) {137 for( var i=0; i<Math.min(tok1.length, tok2.length); i++ ) {138 var cmp = compareTok( tok1[i], tok2[i], compareLeadZeroes );139 if( cmp !== 0 ) {140 return cmp;141 }142 }143 144 if( tok1.length < tok2.length) {145 return -1;146 }...
RoomBeingCreatedTileViewModel.js
Source: RoomBeingCreatedTileViewModel.js
...34 const parentCmp = super.compare(other);35 if (parentCmp !== 0) {36 return parentCmp;37 }38 const nameCmp = comparePrimitive(this.name, other.name);39 if (nameCmp === 0) {40 return comparePrimitive(this._roomBeingCreated.id, other._roomBeingCreated.id);41 } else {42 return nameCmp;43 }44 }45 avatarUrl(size) {46 // allow blob url which doesn't need mxc => http resolution47 return this._roomBeingCreated.avatarBlobUrl ?? super.avatarUrl(size);48 }49}50export function tests() {51 return {52 "test compare with names": assert => {53 const urlCreator = {openRoomActionUrl() { return "";}}54 const vm1 = new RoomBeingCreatedTileViewModel({roomBeingCreated: {name: "A", id: "1"}, urlCreator});...
InviteTileViewModel.js
Source: InviteTileViewModel.js
...38 const timeDiff = other._invite.timestamp - this._invite.timestamp;39 if (timeDiff !== 0) {40 return timeDiff;41 }42 return comparePrimitive(this._invite.id, other._invite.id);43 }44}45export function tests() {46 return {47 "test compare with timestamp": assert => {48 const urlCreator = {openRoomActionUrl() { return "";}}49 const vm1 = new InviteTileViewModel({invite: {timestamp: 500, id: "1"}, urlCreator});50 const vm2 = new InviteTileViewModel({invite: {timestamp: 250, id: "2"}, urlCreator});51 assert(vm1.compare(vm2) < 0);52 assert(vm2.compare(vm1) > 0);53 assert.equal(vm1.compare(vm1), 0);54 },55 }56}
packages.js
Source: packages.js
2const path = require('path');3const fs = require('fs');4const glob = require('glob');5const yaml = require('js-yaml');6function comparePrimitive(a, b) {7 if (a === null && b !== null) {8 return -1;9 }10 if (b === null && a !== null) {11 return 1;12 }13 if (a < b) {14 return -1;15 }16 if (a > b) {17 return 1;18 }19 return 0;20}21function compareVersions(a, b) {22 const aCmps = a.map(parseVersionPiece);23 const bCmps = b.map(parseVersionPiece);24 for (let i = 0; i < 3; i++) {25 const aCmp = aCmps[i];26 const bCmp = bCmps[i];27 const l = Math.max(aCmp.length, bCmp.length);28 for (let j = 0; j < l; j++) {29 const aV = j < aCmp.length ? aCmp[j] : null;30 const bV = j < bCmp.length ? bCmp[j] : null;31 const cmp = comparePrimitive(aV, bV);32 if (cmp) {33 return cmp;34 }35 }36 }37 return 0;38}39function comparePart(a, b) {40 const aV = parseVersion(a);41 const bV = parseVersion(b);42 if (aV && bV) {43 return compareVersions(aV, bV);44 }45 return comparePrimitive(a, b);46}47function pathToParts(p) {48 return p.replace(/\.yaml$/, '').split('/');49}50function parseVersionPiece(s) {51 if (!/^[\d.]+$/.test(s)) {52 return [s];53 }54 return s.split('.').map(Number);55}56function parseVersion(s) {57 const m = s.match(/^(([^.]*)-)?([\d.]+)(-(.*))?$/);58 if (!m) {59 return null;...
compare.js
Source: compare.js
...35 for (let i = 0; i < array.length; ++i) {36 compare(array[i], value[i]);37 }38}39function comparePrimitive(primitive, value) {40 if (primitive !== value) {41 throw new JsonPatchError(42 `${primitive} is not equal to ${JSON.stringify(value)}`43 );44 }45}46export function compare(item, value) {47 if (isObject(item)) {48 compareObject(item, value);49 } else if (isArray(item)) {50 compareArray(item, value);51 } else {52 comparePrimitive(item, value);53 }...
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!!