Best JavaScript code snippet using storybook-test-runner
ObjectMiddleware.js
Source:ObjectMiddleware.js
1/*2 MIT License http://www.opensource.org/licenses/mit-license.php3*/4"use strict";5const createHash = require("../util/createHash");6const ArraySerializer = require("./ArraySerializer");7const DateObjectSerializer = require("./DateObjectSerializer");8const ErrorObjectSerializer = require("./ErrorObjectSerializer");9const MapObjectSerializer = require("./MapObjectSerializer");10const NullPrototypeObjectSerializer = require("./NullPrototypeObjectSerializer");11const PlainObjectSerializer = require("./PlainObjectSerializer");12const RegExpObjectSerializer = require("./RegExpObjectSerializer");13const SerializerMiddleware = require("./SerializerMiddleware");14const SetObjectSerializer = require("./SetObjectSerializer");15/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */16/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */17/** @typedef {new (...params: any[]) => any} Constructor */18/*19Format:20File -> Section*21Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection22ObjectSection -> ESCAPE (23 number:relativeOffset (number > 0) |24 string:request (string|null):export25) Section:value* ESCAPE ESCAPE_END_OBJECT26ReferenceSection -> ESCAPE number:relativeOffset (number < 0)27EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE)28EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE)29OtherSection -> any (except ESCAPE)30Why using null as escape value?31Multiple null values can merged by the BinaryMiddleware, which makes it very efficient32Technically any value can be used.33*/34/**35 * @typedef {Object} ObjectSerializerContext36 * @property {function(any): void} write37 */38/**39 * @typedef {Object} ObjectDeserializerContext40 * @property {function(): any} read41 */42/**43 * @typedef {Object} ObjectSerializer44 * @property {function(any, ObjectSerializerContext): void} serialize45 * @property {function(ObjectDeserializerContext): any} deserialize46 */47const setSetSize = (set, size) => {48 let i = 0;49 for (const item of set) {50 if (i++ >= size) {51 set.delete(item);52 }53 }54};55const setMapSize = (map, size) => {56 let i = 0;57 for (const item of map.keys()) {58 if (i++ >= size) {59 map.delete(item);60 }61 }62};63const toHash = buffer => {64 const hash = createHash("md4");65 hash.update(buffer);66 return /** @type {string} */ (hash.digest("latin1"));67};68const ESCAPE = null;69const ESCAPE_ESCAPE_VALUE = null;70const ESCAPE_END_OBJECT = true;71const ESCAPE_UNDEFINED = false;72const CURRENT_VERSION = 2;73const serializers = new Map();74const serializerInversed = new Map();75const loadedRequests = new Set();76const NOT_SERIALIZABLE = {};77const jsTypes = new Map();78jsTypes.set(Object, new PlainObjectSerializer());79jsTypes.set(Array, new ArraySerializer());80jsTypes.set(null, new NullPrototypeObjectSerializer());81jsTypes.set(Map, new MapObjectSerializer());82jsTypes.set(Set, new SetObjectSerializer());83jsTypes.set(Date, new DateObjectSerializer());84jsTypes.set(RegExp, new RegExpObjectSerializer());85jsTypes.set(Error, new ErrorObjectSerializer(Error));86jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError));87jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError));88jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError));89jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError));90jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError));91// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers92// real Object and Array types to. These types may occur in the wild too, e. g. when93// using Structured Clone in postMessage.94if (exports.constructor !== Object) {95 const Obj = /** @type {typeof Object} */ (exports.constructor);96 const Fn = /** @type {typeof Function} */ (Obj.constructor);97 for (const [type, config] of Array.from(jsTypes)) {98 if (type) {99 const Type = new Fn(`return ${type.name};`)();100 jsTypes.set(Type, config);101 }102 }103}104{105 let i = 1;106 for (const [type, serializer] of jsTypes) {107 serializers.set(type, {108 request: "",109 name: i++,110 serializer111 });112 }113}114for (const { request, name, serializer } of serializers.values()) {115 serializerInversed.set(`${request}/${name}`, serializer);116}117/** @type {Map<RegExp, (request: string) => boolean>} */118const loaders = new Map();119/**120 * @typedef {ComplexSerializableType[]} DeserializedType121 * @typedef {PrimitiveSerializableType[]} SerializedType122 * @extends {SerializerMiddleware<DeserializedType, SerializedType>}123 */124class ObjectMiddleware extends SerializerMiddleware {125 constructor(extendContext) {126 super();127 this.extendContext = extendContext;128 }129 /**130 * @param {RegExp} regExp RegExp for which the request is tested131 * @param {function(string): boolean} loader loader to load the request, returns true when successful132 * @returns {void}133 */134 static registerLoader(regExp, loader) {135 loaders.set(regExp, loader);136 }137 /**138 * @param {Constructor} Constructor the constructor139 * @param {string} request the request which will be required when deserializing140 * @param {string} name the name to make multiple serializer unique when sharing a request141 * @param {ObjectSerializer} serializer the serializer142 * @returns {void}143 */144 static register(Constructor, request, name, serializer) {145 const key = request + "/" + name;146 if (serializers.has(Constructor)) {147 throw new Error(148 `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered`149 );150 }151 if (serializerInversed.has(key)) {152 throw new Error(153 `ObjectMiddleware.register: serializer for ${key} is already registered`154 );155 }156 serializers.set(Constructor, {157 request,158 name,159 serializer160 });161 serializerInversed.set(key, serializer);162 }163 /**164 * @param {Constructor} Constructor the constructor165 * @returns {void}166 */167 static registerNotSerializable(Constructor) {168 if (serializers.has(Constructor)) {169 throw new Error(170 `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered`171 );172 }173 serializers.set(Constructor, NOT_SERIALIZABLE);174 }175 static getSerializerFor(object) {176 const proto = Object.getPrototypeOf(object);177 let c;178 if (proto === null) {179 // Object created with Object.create(null)180 c = null;181 } else {182 c = proto.constructor;183 if (!c) {184 throw new Error(185 "Serialization of objects with prototype without valid constructor property not possible"186 );187 }188 }189 const config = serializers.get(c);190 if (!config) throw new Error(`No serializer registered for ${c.name}`);191 if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE;192 return config;193 }194 static getDeserializerFor(request, name) {195 const key = request + "/" + name;196 const serializer = serializerInversed.get(key);197 if (serializer === undefined) {198 throw new Error(`No deserializer registered for ${key}`);199 }200 return serializer;201 }202 static _getDeserializerForWithoutError(request, name) {203 const key = request + "/" + name;204 const serializer = serializerInversed.get(key);205 return serializer;206 }207 /**208 * @param {DeserializedType} data data209 * @param {Object} context context object210 * @returns {SerializedType|Promise<SerializedType>} serialized data211 */212 serialize(data, context) {213 /** @type {any[]} */214 let result = [CURRENT_VERSION];215 let currentPos = 0;216 let referenceable = new Map();217 const addReferenceable = item => {218 referenceable.set(item, currentPos++);219 };220 let bufferDedupeMap = new Map();221 const dedupeBuffer = buf => {222 const len = buf.length;223 const entry = bufferDedupeMap.get(len);224 if (entry === undefined) {225 bufferDedupeMap.set(len, buf);226 return buf;227 }228 if (Buffer.isBuffer(entry)) {229 if (len < 32) {230 if (buf.equals(entry)) {231 return entry;232 }233 bufferDedupeMap.set(len, [entry, buf]);234 return buf;235 } else {236 const hash = toHash(entry);237 const newMap = new Map();238 newMap.set(hash, entry);239 bufferDedupeMap.set(len, newMap);240 const hashBuf = toHash(buf);241 if (hash === hashBuf) {242 return entry;243 }244 return buf;245 }246 } else if (Array.isArray(entry)) {247 if (entry.length < 16) {248 for (const item of entry) {249 if (buf.equals(item)) {250 return item;251 }252 }253 entry.push(buf);254 return buf;255 } else {256 const newMap = new Map();257 const hash = toHash(buf);258 let found;259 for (const item of entry) {260 const itemHash = toHash(item);261 newMap.set(itemHash, item);262 if (found === undefined && itemHash === hash) found = item;263 }264 bufferDedupeMap.set(len, newMap);265 if (found === undefined) {266 newMap.set(hash, buf);267 return buf;268 } else {269 return found;270 }271 }272 } else {273 const hash = toHash(buf);274 const item = entry.get(hash);275 if (item !== undefined) {276 return item;277 }278 entry.set(hash, buf);279 return buf;280 }281 };282 let currentPosTypeLookup = 0;283 let objectTypeLookup = new Map();284 const cycleStack = new Set();285 const stackToString = item => {286 const arr = Array.from(cycleStack);287 arr.push(item);288 return arr289 .map(item => {290 if (typeof item === "string") {291 if (item.length > 100) {292 return `String ${JSON.stringify(item.slice(0, 100)).slice(293 0,294 -1295 )}..."`;296 }297 return `String ${JSON.stringify(item)}`;298 }299 try {300 const { request, name } = ObjectMiddleware.getSerializerFor(item);301 if (request) {302 return `${request}${name ? `.${name}` : ""}`;303 }304 } catch (e) {305 // ignore -> fallback306 }307 if (typeof item === "object" && item !== null) {308 if (item.constructor) {309 if (item.constructor === Object)310 return `Object { ${Object.keys(item).join(", ")} }`;311 if (item.constructor === Map) return `Map { ${item.size} items }`;312 if (item.constructor === Array)313 return `Array { ${item.length} items }`;314 if (item.constructor === Set) return `Set { ${item.size} items }`;315 if (item.constructor === RegExp) return item.toString();316 return `${item.constructor.name}`;317 }318 return `Object [null prototype] { ${Object.keys(item).join(319 ", "320 )} }`;321 }322 try {323 return `${item}`;324 } catch (e) {325 return `(${e.message})`;326 }327 })328 .join(" -> ");329 };330 let hasDebugInfoAttached;331 let ctx = {332 write(value, key) {333 try {334 process(value);335 } catch (e) {336 if (e !== NOT_SERIALIZABLE) {337 if (hasDebugInfoAttached === undefined)338 hasDebugInfoAttached = new WeakSet();339 if (!hasDebugInfoAttached.has(e)) {340 e.message += `\nwhile serializing ${stackToString(value)}`;341 hasDebugInfoAttached.add(e);342 }343 }344 throw e;345 }346 },347 setCircularReference(ref) {348 addReferenceable(ref);349 },350 snapshot() {351 return {352 length: result.length,353 cycleStackSize: cycleStack.size,354 referenceableSize: referenceable.size,355 currentPos,356 objectTypeLookupSize: objectTypeLookup.size,357 currentPosTypeLookup358 };359 },360 rollback(snapshot) {361 result.length = snapshot.length;362 setSetSize(cycleStack, snapshot.cycleStackSize);363 setMapSize(referenceable, snapshot.referenceableSize);364 currentPos = snapshot.currentPos;365 setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize);366 currentPosTypeLookup = snapshot.currentPosTypeLookup;367 },368 ...context369 };370 this.extendContext(ctx);371 const process = item => {372 if (Buffer.isBuffer(item)) {373 // check if we can emit a reference374 const ref = referenceable.get(item);375 if (ref !== undefined) {376 result.push(ESCAPE, ref - currentPos);377 return;378 }379 const alreadyUsedBuffer = dedupeBuffer(item);380 if (alreadyUsedBuffer !== item) {381 const ref = referenceable.get(alreadyUsedBuffer);382 if (ref !== undefined) {383 referenceable.set(item, ref);384 result.push(ESCAPE, ref - currentPos);385 return;386 }387 item = alreadyUsedBuffer;388 }389 addReferenceable(item);390 result.push(item);391 } else if (item === ESCAPE) {392 result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);393 } else if (394 typeof item === "object"395 // We don't have to check for null as ESCAPE is null and this has been checked before396 ) {397 // check if we can emit a reference398 const ref = referenceable.get(item);399 if (ref !== undefined) {400 result.push(ESCAPE, ref - currentPos);401 return;402 }403 if (cycleStack.has(item)) {404 throw new Error(405 `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.`406 );407 }408 const { request, name, serializer } =409 ObjectMiddleware.getSerializerFor(item);410 const key = `${request}/${name}`;411 const lastIndex = objectTypeLookup.get(key);412 if (lastIndex === undefined) {413 objectTypeLookup.set(key, currentPosTypeLookup++);414 result.push(ESCAPE, request, name);415 } else {416 result.push(ESCAPE, currentPosTypeLookup - lastIndex);417 }418 cycleStack.add(item);419 try {420 serializer.serialize(item, ctx);421 } finally {422 cycleStack.delete(item);423 }424 result.push(ESCAPE, ESCAPE_END_OBJECT);425 addReferenceable(item);426 } else if (typeof item === "string") {427 if (item.length > 1) {428 // short strings are shorter when not emitting a reference (this saves 1 byte per empty string)429 // check if we can emit a reference430 const ref = referenceable.get(item);431 if (ref !== undefined) {432 result.push(ESCAPE, ref - currentPos);433 return;434 }435 addReferenceable(item);436 }437 if (item.length > 102400 && context.logger) {438 context.logger.warn(439 `Serializing big strings (${Math.round(440 item.length / 1024441 )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)`442 );443 }444 result.push(item);445 } else if (typeof item === "function") {446 if (!SerializerMiddleware.isLazy(item))447 throw new Error("Unexpected function " + item);448 /** @type {SerializedType} */449 const serializedData =450 SerializerMiddleware.getLazySerializedValue(item);451 if (serializedData !== undefined) {452 if (typeof serializedData === "function") {453 result.push(serializedData);454 } else {455 throw new Error("Not implemented");456 }457 } else if (SerializerMiddleware.isLazy(item, this)) {458 throw new Error("Not implemented");459 } else {460 result.push(461 SerializerMiddleware.serializeLazy(item, data =>462 this.serialize([data], context)463 )464 );465 }466 } else if (item === undefined) {467 result.push(ESCAPE, ESCAPE_UNDEFINED);468 } else {469 result.push(item);470 }471 };472 try {473 for (const item of data) {474 process(item);475 }476 return result;477 } catch (e) {478 if (e === NOT_SERIALIZABLE) return null;479 throw e;480 } finally {481 // Get rid of these references to avoid leaking memory482 // This happens because the optimized code v8 generates483 // is optimized for our "ctx.write" method so it will reference484 // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write485 data =486 result =487 referenceable =488 bufferDedupeMap =489 objectTypeLookup =490 ctx =491 undefined;492 }493 }494 /**495 * @param {SerializedType} data data496 * @param {Object} context context object497 * @returns {DeserializedType|Promise<DeserializedType>} deserialized data498 */499 deserialize(data, context) {500 let currentDataPos = 0;501 const read = () => {502 if (currentDataPos >= data.length)503 throw new Error("Unexpected end of stream");504 return data[currentDataPos++];505 };506 if (read() !== CURRENT_VERSION)507 throw new Error("Version mismatch, serializer changed");508 let currentPos = 0;509 let referenceable = [];510 const addReferenceable = item => {511 referenceable.push(item);512 currentPos++;513 };514 let currentPosTypeLookup = 0;515 let objectTypeLookup = [];516 let result = [];517 let ctx = {518 read() {519 return decodeValue();520 },521 setCircularReference(ref) {522 addReferenceable(ref);523 },524 ...context525 };526 this.extendContext(ctx);527 const decodeValue = () => {528 const item = read();529 if (item === ESCAPE) {530 const nextItem = read();531 if (nextItem === ESCAPE_ESCAPE_VALUE) {532 return ESCAPE;533 } else if (nextItem === ESCAPE_UNDEFINED) {534 return undefined;535 } else if (nextItem === ESCAPE_END_OBJECT) {536 throw new Error(537 `Unexpected end of object at position ${currentDataPos - 1}`538 );539 } else {540 const request = nextItem;541 let serializer;542 if (typeof request === "number") {543 if (request < 0) {544 // relative reference545 return referenceable[currentPos + request];546 }547 serializer = objectTypeLookup[currentPosTypeLookup - request];548 } else {549 if (typeof request !== "string") {550 throw new Error(551 `Unexpected type (${typeof request}) of request ` +552 `at position ${currentDataPos - 1}`553 );554 }555 const name = read();556 serializer = ObjectMiddleware._getDeserializerForWithoutError(557 request,558 name559 );560 if (serializer === undefined) {561 if (request && !loadedRequests.has(request)) {562 let loaded = false;563 for (const [regExp, loader] of loaders) {564 if (regExp.test(request)) {565 if (loader(request)) {566 loaded = true;567 break;568 }569 }570 }571 if (!loaded) {572 require(request);573 }574 loadedRequests.add(request);575 }576 serializer = ObjectMiddleware.getDeserializerFor(request, name);577 }578 objectTypeLookup.push(serializer);579 currentPosTypeLookup++;580 }581 try {582 const item = serializer.deserialize(ctx);583 const end1 = read();584 if (end1 !== ESCAPE) {585 throw new Error("Expected end of object");586 }587 const end2 = read();588 if (end2 !== ESCAPE_END_OBJECT) {589 throw new Error("Expected end of object");590 }591 addReferenceable(item);592 return item;593 } catch (err) {594 // As this is only for error handling, we omit creating a Map for595 // faster access to this information, as this would affect performance596 // in the good case597 let serializerEntry;598 for (const entry of serializers) {599 if (entry[1].serializer === serializer) {600 serializerEntry = entry;601 break;602 }603 }604 const name = !serializerEntry605 ? "unknown"606 : !serializerEntry[1].request607 ? serializerEntry[0].name608 : serializerEntry[1].name609 ? `${serializerEntry[1].request} ${serializerEntry[1].name}`610 : serializerEntry[1].request;611 err.message += `\n(during deserialization of ${name})`;612 throw err;613 }614 }615 } else if (typeof item === "string") {616 if (item.length > 1) {617 addReferenceable(item);618 }619 return item;620 } else if (Buffer.isBuffer(item)) {621 addReferenceable(item);622 return item;623 } else if (typeof item === "function") {624 return SerializerMiddleware.deserializeLazy(625 item,626 data => this.deserialize(data, context)[0]627 );628 } else {629 return item;630 }631 };632 try {633 while (currentDataPos < data.length) {634 result.push(decodeValue());635 }636 return result;637 } finally {638 // Get rid of these references to avoid leaking memory639 // This happens because the optimized code v8 generates640 // is optimized for our "ctx.read" method so it will reference641 // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read642 result = referenceable = data = objectTypeLookup = ctx = undefined;643 }644 }645}646module.exports = ObjectMiddleware;...
serialization.js
Source:serialization.js
1/*2 MIT License http://www.opensource.org/licenses/mit-license.php3*/4"use strict";5const memoize = require("./memoize");6/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_END_OPERATION_TYPE} MEASURE_END_OPERATION */7/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_START_OPERATION_TYPE} MEASURE_START_OPERATION */8/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */9/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */10/** @typedef {import("../serialization/Serializer")} Serializer */11const getBinaryMiddleware = memoize(() =>12 require("../serialization/BinaryMiddleware")13);14const getObjectMiddleware = memoize(() =>15 require("../serialization/ObjectMiddleware")16);17const getSingleItemMiddleware = memoize(() =>18 require("../serialization/SingleItemMiddleware")19);20const getSerializer = memoize(() => require("../serialization/Serializer"));21const getSerializerMiddleware = memoize(() =>22 require("../serialization/SerializerMiddleware")23);24const getBinaryMiddlewareInstance = memoize(25 () => new (getBinaryMiddleware())()26);27const registerSerializers = memoize(() => {28 require("./registerExternalSerializer");29 // Load internal paths with a relative require30 // This allows bundling all internal serializers31 const internalSerializables = require("./internalSerializables");32 getObjectMiddleware().registerLoader(/^webpack\/lib\//, req => {33 const loader = internalSerializables[req.slice("webpack/lib/".length)];34 if (loader) {35 loader();36 } else {37 console.warn(`${req} not found in internalSerializables`);38 }39 return true;40 });41});42/** @type {Serializer} */43let buffersSerializer;44// Expose serialization API45module.exports = {46 get register() {47 return getObjectMiddleware().register;48 },49 get registerLoader() {50 return getObjectMiddleware().registerLoader;51 },52 get registerNotSerializable() {53 return getObjectMiddleware().registerNotSerializable;54 },55 get NOT_SERIALIZABLE() {56 return getObjectMiddleware().NOT_SERIALIZABLE;57 },58 /** @type {MEASURE_START_OPERATION} */59 get MEASURE_START_OPERATION() {60 return getBinaryMiddleware().MEASURE_START_OPERATION;61 },62 /** @type {MEASURE_END_OPERATION} */63 get MEASURE_END_OPERATION() {64 return getBinaryMiddleware().MEASURE_END_OPERATION;65 },66 get buffersSerializer() {67 if (buffersSerializer !== undefined) return buffersSerializer;68 registerSerializers();69 const Serializer = getSerializer();70 const binaryMiddleware = getBinaryMiddlewareInstance();71 const SerializerMiddleware = getSerializerMiddleware();72 const SingleItemMiddleware = getSingleItemMiddleware();73 return (buffersSerializer = new Serializer([74 new SingleItemMiddleware(),75 new (getObjectMiddleware())(context => {76 if (context.write) {77 context.writeLazy = value => {78 context.write(79 SerializerMiddleware.createLazy(value, binaryMiddleware)80 );81 };82 }83 }),84 binaryMiddleware85 ]));86 },87 createFileSerializer: fs => {88 registerSerializers();89 const Serializer = getSerializer();90 const FileMiddleware = require("../serialization/FileMiddleware");91 const fileMiddleware = new FileMiddleware(fs);92 const binaryMiddleware = getBinaryMiddlewareInstance();93 const SerializerMiddleware = getSerializerMiddleware();94 const SingleItemMiddleware = getSingleItemMiddleware();95 return new Serializer([96 new SingleItemMiddleware(),97 new (getObjectMiddleware())(context => {98 if (context.write) {99 context.writeLazy = value => {100 context.write(101 SerializerMiddleware.createLazy(value, binaryMiddleware)102 );103 };104 context.writeSeparate = (value, options) => {105 context.write(106 SerializerMiddleware.createLazy(value, fileMiddleware, options)107 );108 };109 }110 }),111 binaryMiddleware,112 fileMiddleware113 ]);114 }...
application-test.js
Source:application-test.js
1import { module } from 'qunit';2import test from 'ember-sinon-qunit/test-support/test';3import { setupTest } from 'ember-qunit';4import {5 HEADERS_SYMBOL as META,6 HEADERS_DATACENTER as DC,7 HEADERS_NAMESPACE as NSPACE,8} from 'consul-ui/utils/http/consul';9module('Unit | Serializer | application', function(hooks) {10 setupTest(hooks);11 // Replace this with your real tests.12 test('it exists', function(assert) {13 const store = this.owner.lookup('service:store');14 const serializer = store.serializerFor('application');15 assert.ok(serializer);16 });17 test('respondForDeleteRecord returns the expected pojo structure', function(assert) {18 const store = this.owner.lookup('service:store');19 const serializer = store.serializerFor('application');20 serializer.primaryKey = 'primary-key-name';21 serializer.slugKey = 'Name';22 serializer.fingerprint = function(primary, slug, foreignValue) {23 return function(item) {24 return {25 ...item,26 ...{27 Datacenter: foreignValue,28 [primary]: item[slug],29 },30 };31 };32 };33 // adapter.uidForURL = this.stub().returnsArg(0);34 const respond = function(cb) {35 const headers = {};36 const body = true;37 return cb(headers, body);38 };39 const expected = {40 'primary-key-name': 'name',41 };42 const actual = serializer.respondForDeleteRecord(respond, {}, { Name: 'name', dc: 'dc-1' });43 assert.deepEqual(actual, expected);44 // assert.ok(adapter.uidForURL.calledOnce);45 });46 test('respondForQueryRecord returns the expected pojo structure', function(assert) {47 const store = this.owner.lookup('service:store');48 const serializer = store.serializerFor('application');49 serializer.primaryKey = 'primary-key-name';50 serializer.slugKey = 'Name';51 serializer.fingerprint = function(primary, slug, foreignValue) {52 return function(item) {53 return {54 ...item,55 ...{56 Datacenter: foreignValue,57 [primary]: item[slug],58 },59 };60 };61 };62 const expected = {63 Datacenter: 'dc-1',64 Name: 'name',65 [META]: {66 [DC.toLowerCase()]: 'dc-1',67 [NSPACE.toLowerCase()]: 'default',68 },69 'primary-key-name': 'name',70 };71 const respond = function(cb) {72 const headers = {};73 const body = {74 Name: 'name',75 };76 return cb(headers, body);77 };78 const actual = serializer.respondForQueryRecord(respond, { Name: 'name', dc: 'dc-1' });79 assert.deepEqual(actual, expected);80 });81 test('respondForQuery returns the expected pojo structure', function(assert) {82 const store = this.owner.lookup('service:store');83 const serializer = store.serializerFor('application');84 serializer.primaryKey = 'primary-key-name';85 serializer.slugKey = 'Name';86 serializer.fingerprint = function(primary, slug, foreignValue) {87 return function(item) {88 return {89 ...item,90 ...{91 Datacenter: foreignValue,92 [primary]: item[slug],93 },94 };95 };96 };97 const expected = [98 {99 Datacenter: 'dc-1',100 Name: 'name1',101 'primary-key-name': 'name1',102 },103 {104 Datacenter: 'dc-1',105 Name: 'name2',106 'primary-key-name': 'name2',107 },108 ];109 const respond = function(cb) {110 const headers = {};111 const body = [112 {113 Name: 'name1',114 },115 {116 Name: 'name2',117 },118 ];119 return cb(headers, body);120 };121 const actual = serializer.respondForQuery(respond, { Name: 'name', dc: 'dc-1' });122 assert.deepEqual(actual, expected);123 // assert.ok(adapter.uidForURL.calledTwice);124 });...
Using AI Code Generation
1const { createSerializer } = require('enzyme-to-json');2const { configure } = require('enzyme');3const Adapter = require('enzyme-adapter-react-16');4configure({ adapter: new Adapter() });5expect.addSnapshotSerializer(createSerializer({ mode: 'deep' }));6const { configure } = require('enzyme');7const Adapter = require('enzyme-adapter-react-16');8configure({ adapter: new Adapter() });9import { configure } from '@storybook/react';10import { setOptions } from '@storybook/addon-options';11import { setDefaults } from 'storybook-addon-jsx';12setOptions({13});14setDefaults({15});16import { configure } from '@storybook/react';17import { setOptions } from '@storybook/addon-options';18import { setDefaults } from 'storybook-addon-jsx';19setOptions({20});21setDefaults({22});23import { configure } from '@storybook/react';24import { setOptions } from '@storybook/addon-options';25import { setDefaults } from 'storybook-addon-jsx';26setOptions({27});28setDefaults({
Using AI Code Generation
1import { serializer } from '@storybook/addon-storyshots';2import initStoryshots from '@storybook/addon-storyshots';3initStoryshots({4});5import initStoryshots from '@storybook/addon-storyshots';6import { snapshotWithOptions } from '@storybook/addon-storyshots-puppeteer';7initStoryshots({8 test: snapshotWithOptions({}),9});10import initStoryshots from '@storybook/addon-storyshots';11import { imageSnapshot } from '@storybook/addon-storyshots-puppeteer';12initStoryshots({13 test: imageSnapshot(),14});15import initStoryshots from '@storybook/addon-storyshots';16import { multiSnapshotWithOptions } from '@storybook/addon-storyshots-puppeteer';17initStoryshots({18 test: multiSnapshotWithOptions(),19});20import initStoryshots from '@storybook/addon-storyshots';21import { snapshotWithOptions } from '@storybook/addon-storyshots-puppeteer';22initStoryshots({23 test: snapshotWithOptions({24 customizePage: (page) => page.emulateMedia('screen'),25 }),26});27import initStoryshots from '@storybook/addon-storyshots';28import { imageSnapshot } from '@storybook/addon-storyshots-puppeteer';29initStoryshots({30 test: imageSnapshot({31 }),32});33import initStoryshots from '@storybook/addon-storyshots';34import { multiSnapshotWithOptions } from '@storybook/addon-storyshots-puppeteer';35initStoryshots({36 test: multiSnapshotWithOptions({37 }),38});39import initStoryshots from '@storybook/addon-storyshots';40import { snapshotWithOptions } from '@storybook/addon-storyshots-puppeteer';41initStoryshots({42 test: snapshotWithOptions({43 getGotoOptions: ({ context }) => {44 const { kind, story } = context;45 return {46 url: `iframe.html?id=${kind}--${story}`,47 };
Using AI Code Generation
1const { serializer } = require('storybook-test-runner');2const { storiesOf } = require('@storybook/react');3const { withInfo } = require('@storybook/addon-info');4storiesOf('My Button', module)5 .add('with text', () => <MyButton>Hello Button</MyButton>, { info: 'This is a test' })6 .add('with some emoji', () => <MyButton>π π π π―</MyButton>, { info: 'This is a test' })7 .add('with serializer', () => <MyButton>π π π π―</MyButton>, { info: serializer('This is a test') });8const { testStory } = require('storybook-test-runner');9describe('My Button', () => {10 testStory('with text', () => <MyButton>Hello Button</MyButton>);11 testStory('with some emoji', () => <MyButton>π π π π―</MyButton>);12 testStory('with serializer', () => <MyButton>π π π π―</MyButton>);13});14const { testStory } = require('storybook-test-runner');15describe('My Button', () => {16 testStory('with text', () => <MyButton>Hello Button</MyButton>);17 testStory('with some emoji', () => <MyButton>π π π π―</MyButton>);18 testStory('with serializer', () => <MyButton>π π π π―</MyButton>);19});20const { testStory } = require('storybook-test-runner');21describe('My Button', () => {22 testStory('with text', () => <MyButton>Hello Button</MyButton>);23 testStory('with some emoji', () => <MyButton>π π π π―</MyButton>);24 testStory('with serializer', () => <MyButton>π π π π―</MyButton>);25});26const { testStory } = require('storybook-test-runner');27describe('My Button', () => {28 testStory('with text', () => <MyButton>Hello Button</MyButton>);29 testStory('with some emoji', () => <MyButton>π π π
Using AI Code Generation
1import { serializer } from 'storybook-test-runner';2expect.addSnapshotSerializer(serializer);3test('MyComponent', () => {4 const story = storiesOf('MyComponent', module).add('default', () => (5 ));6 expect(story).toMatchSnapshot();7});8test('MyComponent with a theme', () => {9 const story = storiesOf('MyComponent', module).add('with a theme', () => (10 <MyComponent theme={myTheme} />11 ));12 expect(story).toMatchSnapshot();13});14test('MyComponent with a theme and props', () => {15 const story = storiesOf('MyComponent', module).add('with a theme and props', () => (16 <MyComponent theme={myTheme} props={myProps} />17 ));18 expect(story).toMatchSnapshot();19});20test('MyComponent with a theme and props', () => {21 const story = storiesOf('MyComponent', module).add('with a theme and props', () => (22 <MyComponent theme={myTheme} props={myProps} />23 ));24 expect(story).toMatchSnapshot();25});26test('MyComponent with a theme and props', () => {27 const story = storiesOf('MyComponent', module).add('with a theme and props', () => (28 <MyComponent theme={myTheme} props={myProps} />29 ));30 expect(story).toMatchSnapshot();31});32test('MyComponent with a theme and props', () => {33 const story = storiesOf('MyComponent', module).add('with a theme and props', () => (34 <MyComponent theme={myTheme} props={myProps} />35 ));36 expect(story).toMatchSnapshot();37});38test('MyComponent with a theme and props', () => {39 const story = storiesOf('MyComponent', module).add('with a theme and props', () => (40 <MyComponent theme={myTheme} props={myProps} />41 ));42 expect(story
Using AI Code Generation
1import { serializer, toMatchImageSnapshot } from 'storybook-chrome-screenshot';2expect.addSnapshotSerializer(serializer);3expect.extend({ toMatchImageSnapshot });4cy.screenshot('my-image').toMatchImageSnapshot();5const storybook = new StorybookTestRunner();6storybook.start();7it('should match the image snapshot', () => {8 const story = storybook.load('/iframe.html?id=components-button--primary');9 cy.wrap(story).toMatchImageSnapshot();10});11storybook.stop();12cy.end();13const storybook = new StorybookTestRunner();14storybook.start();15it('should match the image snapshot', () => {16 const story = storybook.load('/iframe.html?id=components-button--primary');17 cy.wrap(story).toMatchImageSnapshot();18});19storybook.stop();20cy.end();21const storybook = new StorybookTestRunner();22storybook.start();23it('should match the image snapshot', () => {24 const story = storybook.load('/iframe.html?id=components-button--primary');25 cy.wrap(story).toMatchImageSnapshot();26});27storybook.stop();28cy.end();29const storybook = new StorybookTestRunner();30storybook.start();31it('should match the image snapshot', () => {32 const story = storybook.load('/iframe.html?id=components-button--primary');33 cy.wrap(story).toMatchImageSnapshot();34});35storybook.stop();36cy.end();37const storybook = new StorybookTestRunner();38storybook.start();39it('should match the image snapshot', () => {40 const story = storybook.load('/iframe.html?id=components-button--primary');41 cy.wrap(story).toMatchImageSnapshot();42});43storybook.stop();44cy.end();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!