How to use serializable method in wpt

Best JavaScript code snippet using wpt

serializableStateInvariantMiddleware.test.ts

Source:serializableStateInvariantMiddleware.test.ts Github

copy

Full Screen

1import { Reducer } from 'redux'2import {3 mockConsole,4 createConsole,5 getLog6} from 'console-testing-library/pure'7import { configureStore } from './configureStore'8import {9 createSerializableStateInvariantMiddleware,10 findNonSerializableValue,11 isPlain12} from './serializableStateInvariantMiddleware'13// Mocking console14let restore = () => {}15beforeEach(() => {16 restore = mockConsole(createConsole())17})18afterEach(() => restore())19describe('findNonSerializableValue', () => {20 it('Should return false if no matching values are found', () => {21 const obj = {22 a: 42,23 b: {24 b1: 'test'25 },26 c: [99, { d: 123 }]27 }28 const result = findNonSerializableValue(obj)29 expect(result).toBe(false)30 })31 it('Should return a keypath and the value if it finds a non-serializable value', () => {32 function testFunction() {}33 const obj = {34 a: 42,35 b: {36 b1: testFunction37 },38 c: [99, { d: 123 }]39 }40 const result = findNonSerializableValue(obj)41 expect(result).toEqual({ keyPath: 'b.b1', value: testFunction })42 })43 it('Should return the first non-serializable value it finds', () => {44 const map = new Map()45 const symbol = Symbol.for('testSymbol')46 const obj = {47 a: 42,48 b: {49 b1: 150 },51 c: [99, { d: 123 }, map, symbol, 'test'],52 d: symbol53 }54 const result = findNonSerializableValue(obj)55 expect(result).toEqual({ keyPath: 'c.2', value: map })56 })57 it('Should return a specific value if the root object is non-serializable', () => {58 const value = new Map()59 const result = findNonSerializableValue(value)60 expect(result).toEqual({ keyPath: '<root>', value })61 })62 it('Should accept null as a valid value', () => {63 const obj = {64 a: 42,65 b: {66 b1: 167 },68 c: null69 }70 const result = findNonSerializableValue(obj)71 expect(result).toEqual(false)72 })73})74describe('serializableStateInvariantMiddleware', () => {75 it('Should log an error when a non-serializable action is dispatched', () => {76 const reducer: Reducer = (state = 0, _action) => state + 177 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware()78 const store = configureStore({79 reducer,80 middleware: [serializableStateInvariantMiddleware]81 })82 const type = Symbol.for('SOME_CONSTANT')83 const dispatchedAction = { type }84 store.dispatch(dispatchedAction)85 expect(getLog().log).toMatchInlineSnapshot(`86 "A non-serializable value was detected in an action, in the path: \`type\`. Value: Symbol(SOME_CONSTANT) 87 Take a look at the logic that dispatched this action: Object {88 \\"type\\": Symbol(SOME_CONSTANT),89 } 90 (See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) 91 (To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)"92 `)93 })94 it('Should log an error when a non-serializable value is in state', () => {95 const ACTION_TYPE = 'TEST_ACTION'96 const initialState = {97 a: 098 }99 const badValue = new Map()100 const reducer: Reducer = (state = initialState, action) => {101 switch (action.type) {102 case ACTION_TYPE: {103 return {104 a: badValue105 }106 }107 default:108 return state109 }110 }111 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware()112 const store = configureStore({113 reducer: {114 testSlice: reducer115 },116 middleware: [serializableStateInvariantMiddleware]117 })118 store.dispatch({ type: ACTION_TYPE })119 expect(getLog().log).toMatchInlineSnapshot(`120 "A non-serializable value was detected in the state, in the path: \`testSlice.a\`. Value: Map {} 121 Take a look at the reducer(s) handling this action type: TEST_ACTION.122 (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"123 `)124 })125 describe('consumer tolerated structures', () => {126 const nonSerializableValue = new Map()127 const nestedSerializableObjectWithBadValue = {128 isSerializable: true,129 entries: (): [string, any][] => [130 ['good-string', 'Good!'],131 ['good-number', 1337],132 ['bad-map-instance', nonSerializableValue]133 ]134 }135 const serializableObject = {136 isSerializable: true,137 entries: (): [string, any][] => [138 ['first', 1],139 ['second', 'B!'],140 ['third', nestedSerializableObjectWithBadValue]141 ]142 }143 it('Should log an error when a non-serializable value is nested in state', () => {144 const ACTION_TYPE = 'TEST_ACTION'145 const initialState = {146 a: 0147 }148 const reducer: Reducer = (state = initialState, action) => {149 switch (action.type) {150 case ACTION_TYPE: {151 return {152 a: serializableObject153 }154 }155 default:156 return state157 }158 }159 // use default options160 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware()161 const store = configureStore({162 reducer: {163 testSlice: reducer164 },165 middleware: [serializableStateInvariantMiddleware]166 })167 store.dispatch({ type: ACTION_TYPE })168 // since default options are used, the `entries` function in `serializableObject` will cause the error169 expect(getLog().log).toMatchInlineSnapshot(`170 "A non-serializable value was detected in the state, in the path: \`testSlice.a.entries\`. Value: [Function entries] 171 Take a look at the reducer(s) handling this action type: TEST_ACTION.172 (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"173 `)174 })175 it('Should use consumer supplied isSerializable and getEntries options to tolerate certain structures', () => {176 const ACTION_TYPE = 'TEST_ACTION'177 const initialState = {178 a: 0179 }180 const isSerializable = (val: any): boolean =>181 val.isSerializable || isPlain(val)182 const getEntries = (val: any): [string, any][] =>183 val.isSerializable ? val.entries() : Object.entries(val)184 const reducer: Reducer = (state = initialState, action) => {185 switch (action.type) {186 case ACTION_TYPE: {187 return {188 a: serializableObject189 }190 }191 default:192 return state193 }194 }195 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware(196 { isSerializable, getEntries }197 )198 const store = configureStore({199 reducer: {200 testSlice: reducer201 },202 middleware: [serializableStateInvariantMiddleware]203 })204 store.dispatch({ type: ACTION_TYPE })205 // error reported is from a nested class instance, rather than the `entries` function `serializableObject`206 expect(getLog().log).toMatchInlineSnapshot(`207 "A non-serializable value was detected in the state, in the path: \`testSlice.a.third.bad-map-instance\`. Value: Map {} 208 Take a look at the reducer(s) handling this action type: TEST_ACTION.209 (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"210 `)211 })212 })213 it('Should use the supplied isSerializable function to determine serializability', () => {214 const ACTION_TYPE = 'TEST_ACTION'215 const initialState = {216 a: 0217 }218 const badValue = new Map()219 const reducer: Reducer = (state = initialState, action) => {220 switch (action.type) {221 case ACTION_TYPE: {222 return {223 a: badValue224 }225 }226 default:227 return state228 }229 }230 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware(231 {232 isSerializable: () => true233 }234 )235 const store = configureStore({236 reducer: {237 testSlice: reducer238 },239 middleware: [serializableStateInvariantMiddleware]240 })241 store.dispatch({ type: ACTION_TYPE })242 // Supplied 'isSerializable' considers all values serializable, hence243 // no error logging is expected:244 expect(getLog().log).toBe('')245 })246 it('should not check serializability for ignored action types', () => {247 let numTimesCalled = 0248 const serializableStateMiddleware = createSerializableStateInvariantMiddleware(249 {250 isSerializable: () => {251 numTimesCalled++252 return true253 },254 ignoredActions: ['IGNORE_ME']255 }256 )257 const store = configureStore({258 reducer: () => ({}),259 middleware: [serializableStateMiddleware]260 })261 expect(numTimesCalled).toBe(0)262 store.dispatch({ type: 'IGNORE_ME' })263 expect(numTimesCalled).toBe(0)264 store.dispatch({ type: 'ANY_OTHER_ACTION' })265 expect(numTimesCalled).toBeGreaterThan(0)266 })267 describe('ignored action paths', () => {268 function reducer() {269 return 0270 }271 const nonSerializableValue = new Map()272 it('default value: meta.arg', () => {273 configureStore({274 reducer,275 middleware: [createSerializableStateInvariantMiddleware()]276 }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })277 expect(getLog().log).toMatchInlineSnapshot(`""`)278 })279 it('default value can be overridden', () => {280 configureStore({281 reducer,282 middleware: [283 createSerializableStateInvariantMiddleware({284 ignoredActionPaths: []285 })286 ]287 }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })288 expect(getLog().log).toMatchInlineSnapshot(`289 "A non-serializable value was detected in an action, in the path: \`meta.arg\`. Value: Map {} 290 Take a look at the logic that dispatched this action: Object {291 \\"meta\\": Object {292 \\"arg\\": Map {},293 },294 \\"type\\": \\"test\\",295 } 296 (See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) 297 (To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)"298 `)299 })300 it('can specify (multiple) different values', () => {301 configureStore({302 reducer,303 middleware: [304 createSerializableStateInvariantMiddleware({305 ignoredActionPaths: ['payload', 'meta.arg']306 })307 ]308 }).dispatch({309 type: 'test',310 payload: { arg: nonSerializableValue },311 meta: { arg: nonSerializableValue }312 })313 expect(getLog().log).toMatchInlineSnapshot(`""`)314 })315 })316 it('should not check serializability for ignored slice names', () => {317 const ACTION_TYPE = 'TEST_ACTION'318 const initialState = {319 a: 0320 }321 const badValue = new Map()322 const reducer: Reducer = (state = initialState, action) => {323 switch (action.type) {324 case ACTION_TYPE: {325 return {326 a: badValue,327 b: {328 c: badValue,329 d: badValue330 },331 e: { f: badValue }332 }333 }334 default:335 return state336 }337 }338 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware(339 {340 ignoredPaths: [341 // Test for ignoring a single value342 'testSlice.a',343 // Test for ignoring a single nested value344 'testSlice.b.c',345 // Test for ignoring an object and its children346 'testSlice.e'347 ]348 }349 )350 const store = configureStore({351 reducer: {352 testSlice: reducer353 },354 middleware: [serializableStateInvariantMiddleware]355 })356 store.dispatch({ type: ACTION_TYPE })357 // testSlice.b.d was not covered in ignoredPaths, so will still log the error358 expect(getLog().log).toMatchInlineSnapshot(`359 "A non-serializable value was detected in the state, in the path: \`testSlice.b.d\`. Value: Map {} 360 Take a look at the reducer(s) handling this action type: TEST_ACTION.361 (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"362 `)363 })364 it('Should print a warning if execution takes too long', () => {365 const reducer: Reducer = (state = 42, action) => {366 return state367 }368 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware(369 { warnAfter: 4 }370 )371 const store = configureStore({372 reducer: {373 testSlice: reducer374 },375 middleware: [serializableStateInvariantMiddleware]376 })377 store.dispatch({378 type: 'SOME_ACTION',379 payload: new Array(10000).fill({ value: 'more' })380 })381 expect(getLog().log).toMatch(382 /^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./383 )384 })385 it('Should not print a warning if "reducer" takes too long', () => {386 const reducer: Reducer = (state = 42, action) => {387 const started = Date.now()388 while (Date.now() - started < 8) {}389 return state390 }391 const serializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware(392 { warnAfter: 4 }393 )394 const store = configureStore({395 reducer: {396 testSlice: reducer397 },398 middleware: [serializableStateInvariantMiddleware]399 })400 store.dispatch({ type: 'SOME_ACTION' })401 expect(getLog().log).toMatch('')402 })...

Full Screen

Full Screen

serializableStateInvariantMiddleware.ts

Source:serializableStateInvariantMiddleware.ts Github

copy

Full Screen

1import isPlainObject from './isPlainObject'2import { Middleware } from 'redux'3import { getTimeMeasureUtils } from './utils'4/**5 * Returns true if the passed value is "plain", i.e. a value that is either6 * directly JSON-serializable (boolean, number, string, array, plain object)7 * or `undefined`.8 *9 * @param val The value to check.10 *11 * @public12 */13export function isPlain(val: any) {14 return (15 typeof val === 'undefined' ||16 val === null ||17 typeof val === 'string' ||18 typeof val === 'boolean' ||19 typeof val === 'number' ||20 Array.isArray(val) ||21 isPlainObject(val)22 )23}24interface NonSerializableValue {25 keyPath: string26 value: unknown27}28/**29 * @public30 */31export function findNonSerializableValue(32 value: unknown,33 path: ReadonlyArray<string> = [],34 isSerializable: (value: unknown) => boolean = isPlain,35 getEntries?: (value: unknown) => [string, any][],36 ignoredPaths: string[] = []37): NonSerializableValue | false {38 let foundNestedSerializable: NonSerializableValue | false39 if (!isSerializable(value)) {40 return {41 keyPath: path.join('.') || '<root>',42 value: value43 }44 }45 if (typeof value !== 'object' || value === null) {46 return false47 }48 const entries = getEntries != null ? getEntries(value) : Object.entries(value)49 const hasIgnoredPaths = ignoredPaths.length > 050 for (const [property, nestedValue] of entries) {51 const nestedPath = path.concat(property)52 if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath.join('.')) >= 0) {53 continue54 }55 if (!isSerializable(nestedValue)) {56 return {57 keyPath: nestedPath.join('.'),58 value: nestedValue59 }60 }61 if (typeof nestedValue === 'object') {62 foundNestedSerializable = findNonSerializableValue(63 nestedValue,64 nestedPath,65 isSerializable,66 getEntries,67 ignoredPaths68 )69 if (foundNestedSerializable) {70 return foundNestedSerializable71 }72 }73 }74 return false75}76/**77 * Options for `createSerializableStateInvariantMiddleware()`.78 *79 * @public80 */81export interface SerializableStateInvariantMiddlewareOptions {82 /**83 * The function to check if a value is considered serializable. This84 * function is applied recursively to every value contained in the85 * state. Defaults to `isPlain()`.86 */87 isSerializable?: (value: any) => boolean88 /**89 * The function that will be used to retrieve entries from each90 * value. If unspecified, `Object.entries` will be used. Defaults91 * to `undefined`.92 */93 getEntries?: (value: any) => [string, any][]94 /**95 * An array of action types to ignore when checking for serializability.96 * Defaults to []97 */98 ignoredActions?: string[]99 /**100 * An array of dot-separated path strings to ignore when checking101 * for serializability, Defaults to ['meta.arg']102 */103 ignoredActionPaths?: string[]104 /**105 * An array of dot-separated path strings to ignore when checking106 * for serializability, Defaults to []107 */108 ignoredPaths?: string[]109 /**110 * Execution time warning threshold. If the middleware takes longer111 * than `warnAfter` ms, a warning will be displayed in the console.112 * Defaults to 32ms.113 */114 warnAfter?: number115}116/**117 * Creates a middleware that, after every state change, checks if the new118 * state is serializable. If a non-serializable value is found within the119 * state, an error is printed to the console.120 *121 * @param options Middleware options.122 *123 * @public124 */125export function createSerializableStateInvariantMiddleware(126 options: SerializableStateInvariantMiddlewareOptions = {}127): Middleware {128 if (process.env.NODE_ENV === 'production') {129 return () => next => action => next(action)130 }131 const {132 isSerializable = isPlain,133 getEntries,134 ignoredActions = [],135 ignoredActionPaths = ['meta.arg'],136 ignoredPaths = [],137 warnAfter = 32138 } = options139 return storeAPI => next => action => {140 if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) {141 return next(action)142 }143 const measureUtils = getTimeMeasureUtils(144 warnAfter,145 'SerializableStateInvariantMiddleware'146 )147 measureUtils.measureTime(() => {148 const foundActionNonSerializableValue = findNonSerializableValue(149 action,150 [],151 isSerializable,152 getEntries,153 ignoredActionPaths154 )155 if (foundActionNonSerializableValue) {156 const { keyPath, value } = foundActionNonSerializableValue157 console.error(158 `A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`,159 value,160 '\nTake a look at the logic that dispatched this action: ',161 action,162 '\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',163 '\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)'164 )165 }166 })167 const result = next(action)168 measureUtils.measureTime(() => {169 const state = storeAPI.getState()170 const foundStateNonSerializableValue = findNonSerializableValue(171 state,172 [],173 isSerializable,174 getEntries,175 ignoredPaths176 )177 if (foundStateNonSerializableValue) {178 const { keyPath, value } = foundStateNonSerializableValue179 console.error(180 `A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`,181 value,182 `183Take a look at the reducer(s) handling this action type: ${action.type}.184(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`185 )186 }187 })188 measureUtils.warnIfExceeded()189 return result190 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var page = require('webpage').create();2 console.log("Status: " + status);3 if(status === "success") {4 page.render('google.png');5 }6 phantom.exit();7});8var webdriver = require('selenium-webdriver');9var driver = new webdriver.Builder()10 .forBrowser('phantomjs')11 .build();12driver.takeScreenshot().then(function(data) {13 require('fs').writeFile('google.png', data, 'base64', function(err) {14 console.log(err);15 });16});17driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var api = new wpt('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('webpagetest');10var api = new wpt('www.webpagetest.org');11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});17var wpt = require('webpagetest');18var api = new wpt('www.webpagetest.org');19 if (err) {20 console.log(err);21 } else {22 console.log(data);23 }24});25var wpt = require('webpagetest');26var api = new wpt('www.webpagetest.org');27 if (err) {28 console.log(err);29 } else {30 console.log(data);31 }32});33var wpt = require('webpagetest');34var api = new wpt('www.webpagetest.org');35 if (err) {36 console.log(err);37 } else {38 console.log(data);39 }40});41var wpt = require('webpagetest');42var api = new wpt('www.webpagetest.org');43 if (err) {44 console.log(err);45 } else {46 console.log(data);47 }48});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');3var options = {4};5test.runTest(url, options, function(err, data) {6 if (err) {7 console.log('Error: ' + err);8 } else {9 console.log('Test ID: ' + data.data.testId);10 console.log('Test URL: ' + data.data.summary);11 test.getTestResults(data.data.testId, function(err, data) {12 if (err) {13 console.log('Error: ' + err);14 } else {15 console.log('Load Time: ' + data.data.median.firstView.loadTime);16 console.log('Speed Index: ' + data.data.median.firstView.SpeedIndex);17 }18 });19 }20});21var wpt = require('webpagetest');22var test = new wpt('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');23var options = {24};25test.runTest(url, options, function(err, data) {26 if (err) {27 console.log('Error: ' + err);28 } else {29 console.log('Test ID: ' + data.data.testId);30 console.log('Test URL: ' + data.data.summary);31 test.getTestResults(data.data.testId, function(err, data) {32 if (err) {33 console.log('Error: ' + err);34 } else {35 console.log('Load Time: ' + data.data.median.firstView.loadTime);36 console.log('Speed Index: ' + data.data.median.firstView.SpeedIndex);37 }38 });39 }40});41var wpt = require('webpagetest');42var test = new wpt('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');43var options = {44};45test.runTest(url, options,

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var webpagetest = new wpt('www.webpagetest.org');3var options = {4};5webpagetest.runTest(options, function(err, data) {6 if (err) {7 console.error(err);8 } else {9 var testId = data.data.testId;10 console.log('Test ID: ' + testId);11 webpagetest.getTestResults(testId, function(err, data) {12 if (err) {13 console.error(err);14 } else {15 console.log(data);16 }17 });18 }19});20{ statusCode: 400,21 { statusCode: 400,22 tester: 'www.webpagetest.org' } }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wiki = wptools.page('Albert Einstein');3wiki.get(function(err, data) {4 console.log(data);5});6{7 "extract": "Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist who developed the general theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). Einstein's work is also known for its influence on the philosophy of science. He is best known in popular culture for his mass–energy equivalence formula E = mc2 (which has been dubbed \"the world's most famous equation\"). He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the evolution of quantum theory.",8 {9 },10 {11 },12 {13 },14 {15 },16 {17 },18 {19 },20 {21 },22 {23 },24 {25 },26 {27 },28 {

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

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