Best JavaScript code snippet using testing-library-react-hooks
ReactFiberHydrationContext.js
Source:ReactFiberHydrationContext.js
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow8 */9import type {Fiber} from './ReactFiber';10import type {11 Instance,12 TextInstance,13 HydratableInstance,14 SuspenseInstance,15 Container,16 HostContext,17} from './ReactFiberHostConfig';18import type {SuspenseState} from './ReactFiberSuspenseComponent';19import {20 HostComponent,21 HostText,22 HostRoot,23 SuspenseComponent,24} from 'shared/ReactWorkTags';25import {Deletion, Placement, Hydrating} from 'shared/ReactSideEffectTags';26import invariant from 'shared/invariant';27import {28 createFiberFromHostInstanceForDeletion,29 createFiberFromDehydratedFragment,30} from './ReactFiber';31import {32 shouldSetTextContent,33 supportsHydration,34 canHydrateInstance,35 canHydrateTextInstance,36 canHydrateSuspenseInstance,37 getNextHydratableSibling,38 getFirstHydratableChild,39 hydrateInstance,40 hydrateTextInstance,41 hydrateSuspenseInstance,42 getNextHydratableInstanceAfterSuspenseInstance,43 didNotMatchHydratedContainerTextInstance,44 didNotMatchHydratedTextInstance,45 didNotHydrateContainerInstance,46 didNotHydrateInstance,47 didNotFindHydratableContainerInstance,48 didNotFindHydratableContainerTextInstance,49 didNotFindHydratableContainerSuspenseInstance,50 didNotFindHydratableInstance,51 didNotFindHydratableTextInstance,52 didNotFindHydratableSuspenseInstance,53} from './ReactFiberHostConfig';54import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags';55import {Never} from './ReactFiberExpirationTime';56// The deepest Fiber on the stack involved in a hydration context.57// This may have been an insertion or a hydration.58let hydrationParentFiber: null | Fiber = null;59let nextHydratableInstance: null | HydratableInstance = null;60let isHydrating: boolean = false;61function warnIfHydrating() {62 if (__DEV__) {63 if (isHydrating) {64 console.error(65 'We should not be hydrating here. This is a bug in React. Please file a bug.',66 );67 }68 }69}70function enterHydrationState(fiber: Fiber): boolean {71 if (!supportsHydration) {72 return false;73 }74 const parentInstance = fiber.stateNode.containerInfo;75 nextHydratableInstance = getFirstHydratableChild(parentInstance);76 hydrationParentFiber = fiber;77 isHydrating = true;78 return true;79}80function reenterHydrationStateFromDehydratedSuspenseInstance(81 fiber: Fiber,82 suspenseInstance: SuspenseInstance,83): boolean {84 if (!supportsHydration) {85 return false;86 }87 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);88 popToNextHostParent(fiber);89 isHydrating = true;90 return true;91}92function deleteHydratableInstance(93 returnFiber: Fiber,94 instance: HydratableInstance,95) {96 if (__DEV__) {97 switch (returnFiber.tag) {98 case HostRoot:99 didNotHydrateContainerInstance(100 returnFiber.stateNode.containerInfo,101 instance,102 );103 break;104 case HostComponent:105 didNotHydrateInstance(106 returnFiber.type,107 returnFiber.memoizedProps,108 returnFiber.stateNode,109 instance,110 );111 break;112 }113 }114 const childToDelete = createFiberFromHostInstanceForDeletion();115 childToDelete.stateNode = instance;116 childToDelete.return = returnFiber;117 childToDelete.effectTag = Deletion;118 // This might seem like it belongs on progressedFirstDeletion. However,119 // these children are not part of the reconciliation list of children.120 // Even if we abort and rereconcile the children, that will try to hydrate121 // again and the nodes are still in the host tree so these will be122 // recreated.123 if (returnFiber.lastEffect !== null) {124 returnFiber.lastEffect.nextEffect = childToDelete;125 returnFiber.lastEffect = childToDelete;126 } else {127 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;128 }129}130function insertNonHydratedInstance(returnFiber: Fiber, fiber: Fiber) {131 fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement;132 if (__DEV__) {133 switch (returnFiber.tag) {134 case HostRoot: {135 const parentContainer = returnFiber.stateNode.containerInfo;136 switch (fiber.tag) {137 case HostComponent:138 const type = fiber.type;139 const props = fiber.pendingProps;140 didNotFindHydratableContainerInstance(parentContainer, type, props);141 break;142 case HostText:143 const text = fiber.pendingProps;144 didNotFindHydratableContainerTextInstance(parentContainer, text);145 break;146 case SuspenseComponent:147 didNotFindHydratableContainerSuspenseInstance(parentContainer);148 break;149 }150 break;151 }152 case HostComponent: {153 const parentType = returnFiber.type;154 const parentProps = returnFiber.memoizedProps;155 const parentInstance = returnFiber.stateNode;156 switch (fiber.tag) {157 case HostComponent:158 const type = fiber.type;159 const props = fiber.pendingProps;160 didNotFindHydratableInstance(161 parentType,162 parentProps,163 parentInstance,164 type,165 props,166 );167 break;168 case HostText:169 const text = fiber.pendingProps;170 didNotFindHydratableTextInstance(171 parentType,172 parentProps,173 parentInstance,174 text,175 );176 break;177 case SuspenseComponent:178 didNotFindHydratableSuspenseInstance(179 parentType,180 parentProps,181 parentInstance,182 );183 break;184 }185 break;186 }187 default:188 return;189 }190 }191}192function tryHydrate(fiber, nextInstance) {193 switch (fiber.tag) {194 case HostComponent: {195 const type = fiber.type;196 const props = fiber.pendingProps;197 const instance = canHydrateInstance(nextInstance, type, props);198 if (instance !== null) {199 fiber.stateNode = (instance: Instance);200 return true;201 }202 return false;203 }204 case HostText: {205 const text = fiber.pendingProps;206 const textInstance = canHydrateTextInstance(nextInstance, text);207 if (textInstance !== null) {208 fiber.stateNode = (textInstance: TextInstance);209 return true;210 }211 return false;212 }213 case SuspenseComponent: {214 if (enableSuspenseServerRenderer) {215 const suspenseInstance: null | SuspenseInstance = canHydrateSuspenseInstance(216 nextInstance,217 );218 if (suspenseInstance !== null) {219 const suspenseState: SuspenseState = {220 dehydrated: suspenseInstance,221 retryTime: Never,222 };223 fiber.memoizedState = suspenseState;224 // Store the dehydrated fragment as a child fiber.225 // This simplifies the code for getHostSibling and deleting nodes,226 // since it doesn't have to consider all Suspense boundaries and227 // check if they're dehydrated ones or not.228 const dehydratedFragment = createFiberFromDehydratedFragment(229 suspenseInstance,230 );231 dehydratedFragment.return = fiber;232 fiber.child = dehydratedFragment;233 return true;234 }235 }236 return false;237 }238 default:239 return false;240 }241}242function tryToClaimNextHydratableInstance(fiber: Fiber): void {243 if (!isHydrating) {244 return;245 }246 let nextInstance = nextHydratableInstance;247 if (!nextInstance) {248 // Nothing to hydrate. Make it an insertion.249 insertNonHydratedInstance((hydrationParentFiber: any), fiber);250 isHydrating = false;251 hydrationParentFiber = fiber;252 return;253 }254 const firstAttemptedInstance = nextInstance;255 if (!tryHydrate(fiber, nextInstance)) {256 // If we can't hydrate this instance let's try the next one.257 // We use this as a heuristic. It's based on intuition and not data so it258 // might be flawed or unnecessary.259 nextInstance = getNextHydratableSibling(firstAttemptedInstance);260 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {261 // Nothing to hydrate. Make it an insertion.262 insertNonHydratedInstance((hydrationParentFiber: any), fiber);263 isHydrating = false;264 hydrationParentFiber = fiber;265 return;266 }267 // We matched the next one, we'll now assume that the first one was268 // superfluous and we'll delete it. Since we can't eagerly delete it269 // we'll have to schedule a deletion. To do that, this node needs a dummy270 // fiber associated with it.271 deleteHydratableInstance(272 (hydrationParentFiber: any),273 firstAttemptedInstance,274 );275 }276 hydrationParentFiber = fiber;277 nextHydratableInstance = getFirstHydratableChild((nextInstance: any));278}279function prepareToHydrateHostInstance(280 fiber: Fiber,281 rootContainerInstance: Container,282 hostContext: HostContext,283): boolean {284 if (!supportsHydration) {285 invariant(286 false,287 'Expected prepareToHydrateHostInstance() to never be called. ' +288 'This error is likely caused by a bug in React. Please file an issue.',289 );290 }291 const instance: Instance = fiber.stateNode;292 const updatePayload = hydrateInstance(293 instance,294 fiber.type,295 fiber.memoizedProps,296 rootContainerInstance,297 hostContext,298 fiber,299 );300 // TODO: Type this specific to this type of component.301 fiber.updateQueue = (updatePayload: any);302 // If the update payload indicates that there is a change or if there303 // is a new ref we mark this as an update.304 if (updatePayload !== null) {305 return true;306 }307 return false;308}309function prepareToHydrateHostTextInstance(fiber: Fiber): boolean {310 if (!supportsHydration) {311 invariant(312 false,313 'Expected prepareToHydrateHostTextInstance() to never be called. ' +314 'This error is likely caused by a bug in React. Please file an issue.',315 );316 }317 const textInstance: TextInstance = fiber.stateNode;318 const textContent: string = fiber.memoizedProps;319 const shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);320 if (__DEV__) {321 if (shouldUpdate) {322 // We assume that prepareToHydrateHostTextInstance is called in a context where the323 // hydration parent is the parent host component of this host text.324 const returnFiber = hydrationParentFiber;325 if (returnFiber !== null) {326 switch (returnFiber.tag) {327 case HostRoot: {328 const parentContainer = returnFiber.stateNode.containerInfo;329 didNotMatchHydratedContainerTextInstance(330 parentContainer,331 textInstance,332 textContent,333 );334 break;335 }336 case HostComponent: {337 const parentType = returnFiber.type;338 const parentProps = returnFiber.memoizedProps;339 const parentInstance = returnFiber.stateNode;340 didNotMatchHydratedTextInstance(341 parentType,342 parentProps,343 parentInstance,344 textInstance,345 textContent,346 );347 break;348 }349 }350 }351 }352 }353 return shouldUpdate;354}355function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void {356 if (!supportsHydration) {357 invariant(358 false,359 'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' +360 'This error is likely caused by a bug in React. Please file an issue.',361 );362 }363 let suspenseState: null | SuspenseState = fiber.memoizedState;364 let suspenseInstance: null | SuspenseInstance =365 suspenseState !== null ? suspenseState.dehydrated : null;366 invariant(367 suspenseInstance,368 'Expected to have a hydrated suspense instance. ' +369 'This error is likely caused by a bug in React. Please file an issue.',370 );371 hydrateSuspenseInstance(suspenseInstance, fiber);372}373function skipPastDehydratedSuspenseInstance(374 fiber: Fiber,375): null | HydratableInstance {376 if (!supportsHydration) {377 invariant(378 false,379 'Expected skipPastDehydratedSuspenseInstance() to never be called. ' +380 'This error is likely caused by a bug in React. Please file an issue.',381 );382 }383 let suspenseState: null | SuspenseState = fiber.memoizedState;384 let suspenseInstance: null | SuspenseInstance =385 suspenseState !== null ? suspenseState.dehydrated : null;386 invariant(387 suspenseInstance,388 'Expected to have a hydrated suspense instance. ' +389 'This error is likely caused by a bug in React. Please file an issue.',390 );391 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);392}393function popToNextHostParent(fiber: Fiber): void {394 let parent = fiber.return;395 while (396 parent !== null &&397 parent.tag !== HostComponent &&398 parent.tag !== HostRoot &&399 parent.tag !== SuspenseComponent400 ) {401 parent = parent.return;402 }403 hydrationParentFiber = parent;404}405function popHydrationState(fiber: Fiber): boolean {406 if (!supportsHydration) {407 return false;408 }409 if (fiber !== hydrationParentFiber) {410 // We're deeper than the current hydration context, inside an inserted411 // tree.412 return false;413 }414 if (!isHydrating) {415 // If we're not currently hydrating but we're in a hydration context, then416 // we were an insertion and now need to pop up reenter hydration of our417 // siblings.418 popToNextHostParent(fiber);419 isHydrating = true;420 return false;421 }422 const type = fiber.type;423 // If we have any remaining hydratable nodes, we need to delete them now.424 // We only do this deeper than head and body since they tend to have random425 // other nodes in them. We also ignore components with pure text content in426 // side of them.427 // TODO: Better heuristic.428 if (429 fiber.tag !== HostComponent ||430 (type !== 'head' &&431 type !== 'body' &&432 !shouldSetTextContent(type, fiber.memoizedProps))433 ) {434 let nextInstance = nextHydratableInstance;435 while (nextInstance) {436 deleteHydratableInstance(fiber, nextInstance);437 nextInstance = getNextHydratableSibling(nextInstance);438 }439 }440 popToNextHostParent(fiber);441 if (fiber.tag === SuspenseComponent) {442 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);443 } else {444 nextHydratableInstance = hydrationParentFiber445 ? getNextHydratableSibling(fiber.stateNode)446 : null;447 }448 return true;449}450function resetHydrationState(): void {451 if (!supportsHydration) {452 return;453 }454 hydrationParentFiber = null;455 nextHydratableInstance = null;456 isHydrating = false;457}458export {459 warnIfHydrating,460 enterHydrationState,461 reenterHydrationStateFromDehydratedSuspenseInstance,462 resetHydrationState,463 tryToClaimNextHydratableInstance,464 prepareToHydrateHostInstance,465 prepareToHydrateHostTextInstance,466 prepareToHydrateHostSuspenseInstance,467 popHydrationState,...
commissionsReducer.js
Source:commissionsReducer.js
1import axios from 'axios';2import { api, getConfig } from '../../api/apiInterfaceProvider';3import { commissionsMessages } from '../../utils/messages';4import {5 formatterDate,6 getStudentsNames,7 getTutorsNames8} from '../../utils/services/functions';9import {10 clearAlert,11 queryError,12 toggleLoading,13 hydrateAlert14} from '../login/authReducer';15const HYDRATE_APPROVED_COMMISSIONS = 'HYDRATE_APPROVED_COMMISSIONS';16const HYDRATE_TERMINATED_COMMISSIONS = 'HYDRATE_TERMINATED_COMMISSIONS';17const HYDRATE_PENDING_COMMISSIONS = 'HYDRATE_PENDING_COMMISSIONS';18const HYDRATE_COMMISSION = 'HYDRATE_COMMISSION';19const abandonedIdea = () =>20 hydrateAlert({21 message: commissionsMessages.ABANDON_SUCCESS,22 style: 'success',23 onDismiss: clearAlert24 });25const hydratePendingProjects = (data) => ({26 type: HYDRATE_PENDING_COMMISSIONS,27 data28});29const hydrateApprovedProjects = (data) => ({30 type: HYDRATE_APPROVED_COMMISSIONS,31 data32});33const hydrateTerminatedProjects = (data) => ({34 type: HYDRATE_TERMINATED_COMMISSIONS,35 data36});37const hydrateProject = (data) => ({38 type: HYDRATE_COMMISSION,39 data40});41export const rejectIdea = (projectId, memberId, postAction = () => {}) => (42 dispatch43) => {44 dispatch(toggleLoading({ loading: true }));45 const config = getConfig();46 axios47 .delete(api.abandonTutorProject(projectId, memberId), config)48 .then((res) => res.data.data)49 .then(() => {50 dispatch(toggleLoading({ loading: false }));51 dispatch(abandonedIdea());52 postAction();53 })54 .catch((error) => {55 dispatch(queryError(error));56 dispatch(toggleLoading({ loading: false }));57 });58};59export const getActiveProject = (projectId, dispatch) => {60 dispatch(toggleLoading({ loading: true }));61 const config = getConfig();62 axios63 .get(api.project(projectId), config)64 .then((res) => res.data.data)65 .then((data) => {66 dispatch(toggleLoading({ loading: false }));67 dispatch(hydrateProject(data));68 })69 .catch((error) => {70 dispatch(queryError(error));71 dispatch(toggleLoading({ loading: false }));72 });73};74export const getProject = (projectId) => (dispatch) => {75 getActiveProject(projectId, dispatch);76};77export const getProjects = (approved, terminated, career, dispatch) => {78 dispatch(toggleLoading({ loading: true }));79 const config = getConfig();80 const projectUrl = `${api.projectsForCommissions}?1=1${81 approved ? '&approved=1' : ''82 }${terminated ? '&terminated=1' : ''}${career ? `&career=${career}` : ''}`;83 axios84 .get(projectUrl, config)85 .then((res) => res.data.data)86 .then((data) => {87 dispatch(toggleLoading({ loading: false }));88 if (approved) {89 dispatch(hydrateApprovedProjects(data));90 } else if (terminated) {91 dispatch(hydrateTerminatedProjects(data));92 } else {93 dispatch(hydratePendingProjects(data));94 }95 })96 .catch((error) => {97 dispatch(toggleLoading({ loading: false }));98 dispatch(queryError(error));99 });100};101export const editPresentationData = (102 projectId,103 presentationId,104 {105 description,106 documentation_visible: documentationVisible,107 presentation_visible: presentationViisible108 }109) => (dispatch) => {110 dispatch(toggleLoading({ loading: true }));111 const config = getConfig();112 const body = {113 description,114 documentation_visible: documentationVisible,115 presentation_visible: presentationViisible116 };117 axios118 .put(api.editPresentations(presentationId), body, config)119 .then((res) => res.data.data)120 .then(() => {121 getActiveProject(projectId, dispatch);122 })123 .then(() => {124 dispatch(toggleLoading({ loading: false }));125 })126 .catch((error) => {127 dispatch(queryError(error));128 dispatch(toggleLoading({ loading: false }));129 });130};131export const approve = (projectId, careerId, postAction) => (dispatch) => {132 dispatch(toggleLoading({ loading: true }));133 const config = getConfig();134 const body = {135 career: careerId,136 status: 'accepted'137 };138 axios139 .put(api.assessment(projectId), body, config)140 .then((res) => res.data.data)141 .then(() => {142 getActiveProject(projectId, dispatch);143 postAction();144 dispatch(toggleLoading({ loading: false }));145 })146 .catch((error) => {147 dispatch(queryError(error));148 dispatch(toggleLoading({ loading: false }));149 });150};151export const reprobate = (projectId, careerId, rejectionReason, postAction) => (152 dispatch153) => {154 dispatch(toggleLoading({ loading: true }));155 const config = getConfig();156 const body = {157 career: careerId,158 status: 'rejected',159 reject_reason: rejectionReason160 };161 axios162 .put(api.assessment(projectId), body, config)163 .then((res) => res.data.data)164 .then(() => {165 getActiveProject(projectId, dispatch);166 postAction();167 dispatch(toggleLoading({ loading: false }));168 })169 .catch((error) => {170 dispatch(queryError(error));171 dispatch(toggleLoading({ loading: false }));172 });173};174export const getInitialData = (approved, terminated, career) => (dispatch) => {175 getProjects(approved, terminated, career, dispatch);176};177const fetchProjectsTable = (data) =>178 data.map((project) => ({179 id: project.id,180 name: project.name,181 description: project.description,182 students: getStudentsNames(project.Creator, project.Students),183 tutors: getTutorsNames(project.Tutor, project.Cotutors),184 careers: project.ProjectCareers.map(185 (projectCareer) => projectCareer.Career.name186 ).join(', '),187 type: project.Type.name,188 created_at: formatterDate(project.createdAt)189 }));190export default (191 state = {192 approvedProjects: [],193 pendingProjects: [],194 terminatedProjects: [],195 project: {}196 },197 action198) => {199 switch (action.type) {200 case HYDRATE_PENDING_COMMISSIONS:201 return {202 ...state,203 pendingProjects: fetchProjectsTable(action.data)204 };205 case HYDRATE_APPROVED_COMMISSIONS:206 return {207 ...state,208 approvedProjects: fetchProjectsTable(action.data)209 };210 case HYDRATE_TERMINATED_COMMISSIONS:211 return {212 ...state,213 terminatedProjects: fetchProjectsTable(action.data)214 };215 case HYDRATE_COMMISSION:216 return {217 ...state,218 project: action.data219 };220 default:221 return state;222 }...
LazyHydrate.test.js
Source:LazyHydrate.test.js
1import React from 'react'2import { mount } from 'enzyme'3import { styled } from '@mui/material/styles'4import { act } from 'react-dom/test-utils'5describe('LazyHydrate', () => {6 let isBrowser, LazyHydrate, LazyStyles, getRegistryCount, wrapper, Router7 afterEach(() => {8 wrapper && wrapper.unmount()9 })10 describe('on the server', () => {11 beforeEach(() => {12 jest.isolateModules(() => {13 isBrowser = jest.doMock('react-storefront/utils/isBrowser', () => () => false)14 const mod = require('react-storefront/LazyHydrate')15 LazyHydrate = mod.default16 LazyStyles = mod.LazyStyles17 getRegistryCount = mod.getRegistryCount18 })19 })20 it('should clear registries', () => {21 const PREFIX = 'LazyHydrate.test'22 const classes = {23 root: `${PREFIX}-root`,24 '@media (min-width: 1024px)': `${PREFIX}-@media (min-width: 1024px)`,25 }26 const Root = styled('button')(() => ({27 [`& .${classes.root}`]: {28 fontWeight: 'bold',29 'media (min-width: 1024px)': {30 width: 200,31 },32 },33 }))34 const TestComponent = () => {35 return <Root className={classes.root}>click</Root>36 }37 const hydrate = mount(38 <LazyHydrate id="test">39 <TestComponent />40 </LazyHydrate>,41 )42 expect(getRegistryCount()).toBe(1)43 wrapper = mount(44 <div>45 <LazyStyles />46 </div>,47 )48 expect(getRegistryCount()).toBe(0)49 hydrate.unmount()50 })51 it('should render children during SSR only mode', () => {52 const click = jest.fn()53 wrapper = mount(54 <LazyHydrate id="test" ssrOnly>55 <button onClick={click}>click</button>56 </LazyHydrate>,57 )58 expect(wrapper.html()).toContain('<button>click</button>')59 })60 })61 describe('in the browser', () => {62 let events, intersectionObserverCallback, intersectionObserverFallback63 beforeEach(() => {64 jest.isolateModules(() => {65 events = {}66 isBrowser = jest.doMock('react-storefront/utils/isBrowser', () => () => true)67 Router = jest.doMock('next/router', () => ({68 events: {69 on: (name, callback) => {70 events[name] = callback71 },72 },73 }))74 jest.doMock('react-storefront/hooks/useIntersectionObserver', () => {75 return (_el, callback, fallback) => {76 intersectionObserverCallback = callback77 intersectionObserverFallback = fallback78 }79 })80 const mod = require('react-storefront/LazyHydrate')81 LazyHydrate = mod.default82 LazyStyles = mod.LazyStyles83 getRegistryCount = mod.getRegistryCount84 })85 })86 it('should pass event through when hydrated', () => {87 const click = jest.fn()88 wrapper = mount(89 <LazyHydrate id="test" hydrated>90 <button onClick={click}>click</button>91 </LazyHydrate>,92 )93 wrapper.find('button').simulate('click')94 expect(click).toHaveBeenCalled()95 })96 it('should not render children in the browser during SSR only mode', () => {97 const click = jest.fn()98 wrapper = mount(99 <LazyHydrate id="test" ssrOnly>100 <button onClick={click}>click</button>101 </LazyHydrate>,102 )103 expect(wrapper.find('button').length).toBe(0)104 })105 it('should hydrate in browser once triggered', () => {106 wrapper = mount(107 <LazyHydrate id="test" hydrated={false}>108 <button>click</button>109 </LazyHydrate>,110 )111 expect(wrapper.html()).not.toContain('<button>click</button>')112 wrapper.setProps({ hydrated: true })113 expect(wrapper.html()).toContain('<button>click</button>')114 })115 it('should hydrate new elements immediately after navigation', () => {116 events.routeChangeStart()117 wrapper = mount(118 <LazyHydrate id="test" hydrated={false}>119 <button>click</button>120 </LazyHydrate>,121 )122 expect(wrapper.html()).toContain('<button>click</button>')123 })124 it('should remove the server side style sheet after hydration', () => {125 const style = document.createElement('style')126 style.setAttribute('id', 'test')127 document.head.appendChild(style)128 wrapper = mount(129 <LazyHydrate id="test" hydrated={false}>130 <button>click</button>131 </LazyHydrate>,132 )133 wrapper.setProps({ hydrated: true })134 expect(document.querySelector('style[id=test]')).toBe(null)135 })136 it('should hydrate on touch', async () => {137 wrapper = mount(138 <LazyHydrate id="test" on="touch">139 <button>click</button>140 </LazyHydrate>,141 )142 await act(async () => {143 wrapper.getDOMNode().dispatchEvent(new Event('touchstart'))144 })145 expect(wrapper.html()).toContain('<button>click</button>')146 })147 it('should hydrate on the first user interaction with the window', async () => {148 wrapper = mount(149 <LazyHydrate id="test" on="fui">150 <button>click</button>151 </LazyHydrate>,152 )153 await act(async () => {154 window.dispatchEvent(new Event('mouseover'))155 })156 expect(wrapper.html()).toContain('<button>click</button>')157 })158 it('should hydrate when visible', async () => {159 wrapper = mount(160 <LazyHydrate id="test" on="visible">161 <button>click</button>162 </LazyHydrate>,163 )164 await act(async () => {165 intersectionObserverCallback(true, jest.fn())166 })167 expect(wrapper.html()).toContain('<button>click</button>')168 })169 it('should not hydrate when not visible', async () => {170 wrapper = mount(171 <LazyHydrate id="test" on="visible">172 <button>click</button>173 </LazyHydrate>,174 )175 await act(async () => {176 intersectionObserverCallback(false, jest.fn())177 })178 expect(wrapper.html()).not.toContain('<button>click</button>')179 })180 })...
LazyHydrate.js
Source:LazyHydrate.js
...29 // (only relevant when using Preact) - see https://github.com/preactjs/preact/issues/2364#issuecomment-73695689430 const addToLazyComponents = useStore((state) => state.addToLazyComponents)31 const initHydrate = () => {32 id && addToLazyComponents(childRef?.current?.children?.[id])33 hydrate()34 }35 if (isDev && !ssrOnly && !whenIdle && !whenVisible && !on.length && !promise) {36 console.error(37 `LazyHydration: Enable atleast one trigger for hydration.\n` +38 `If you don't want to hydrate, use ssrOnly`39 )40 }41 useIsomorphicLayoutEffect(() => {42 // FIXME: hydrates instantly on page route changes because SSR HTML isn't present on route changes43 // No SSR Content44 if (!childRef.current.hasChildNodes()) {45 initHydrate()46 }47 }, [])...
PlaylistActions.js
Source:PlaylistActions.js
1import * as PlaylistAction from './constants/PlaylistActionConstants';2import { parseRSSFeed } from '../utils/playlists';3import { fetchingPlaylists } from './AppActions';4import isEmpty from 'lodash/isEmpty';5export const readFeedAndHydratePlaylist = (feedUrl, feedData = {}) => ({6 type: PlaylistAction.alias.READ_FEED_AND_HYDRATE_PLAYLIST,7 payload: {8 feedUrl,9 feedData10 }11});12const readFeedAndHydratePlaylistImpl = action => {13 let { feedUrl, feedData } = action.payload;14 return async (dispatch) => {15 if (isEmpty(feedData)) {16 try {17 feedData = await parseRSSFeed(feedUrl);18 feedData = feedData.feed;19 } catch (err) {20 console.error('[ytp] Error in readFeedAndHydratePlaylist:', err);21 throw new Error('Error in readFeedAndHydratePlaylist:' + err);22 }23 }24 dispatch(hydratePlaylist(feedData));25 };26};27export const readFeedAndHydrateAllPlaylists = feedUrls => ({28 type: PlaylistAction.alias.READ_FEED_AND_HYDRATE_ALL_PLAYLISTS,29 payload: feedUrls30});31const readFeedAndHydrateAllPlaylistsImpl = action => {32 const feedUrls = action.payload;33 return async (dispatch) => {34 dispatch(fetchingPlaylists(true));35 try {36 const promises = [];37 feedUrls.forEach(feed => {38 promises.push(parseRSSFeed(feed));39 });40 Promise.all(promises).then(feedData => {41 dispatch(fetchingPlaylists(false));42 feedData = feedData.map(data => data.feed);43 dispatch(hydrateAllPlaylists(feedData));44 });45 } catch (err) {46 console.error('[ytp] Error in readFeedAndHydrateAllPlaylists:', err);47 }48 };49};50export const hydratePlaylist = feedData => ({51 type: PlaylistAction.HYDRATE_PLAYLIST,52 payload: feedData53});54export const hydrateAllPlaylists = feedData => ({55 type: PlaylistAction.HYDRATE_ALL_PLAYLISTS,56 payload: feedData57});58export const aliases = {59 [PlaylistAction.alias.READ_FEED_AND_HYDRATE_PLAYLIST]: readFeedAndHydratePlaylistImpl,60 [PlaylistAction.alias.READ_FEED_AND_HYDRATE_ALL_PLAYLISTS]: readFeedAndHydrateAllPlaylistsImpl...
getReactStack.js
Source:getReactStack.js
1'use strict';2exports.__esModule = true;3var _hydrateFiberStack = require('./stack/hydrateFiberStack');4var _hydrateFiberStack2 = _interopRequireDefault(_hydrateFiberStack);5var _hydrateLegacyStack = require('./stack/hydrateLegacyStack');6var _hydrateLegacyStack2 = _interopRequireDefault(_hydrateLegacyStack);7var _reactUtils = require('./reactUtils');8function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }9function getReactStack(instance) {10 var rootNode = (0, _reactUtils.getInternalInstance)(instance);11 var stack = {};12 var isFiber = typeof rootNode.tag === 'number';13 if (isFiber) {14 (0, _hydrateFiberStack2.default)(rootNode, stack);15 } else {16 (0, _hydrateLegacyStack2.default)(rootNode, stack);17 }18 return stack;19} /* eslint-disable no-underscore-dangle */...
hydrate.test.js
Source:hydrate.test.js
...6 it('Testa se hydrate é uma função', () => {7 expect(typeof hydrate).toBe('function');8 });9 it('Ao receber uma string retorne a sugestão de quantos copos de água deve-se beber', () => {10 expect(hydrate('1 cerveja')).toBe('1 copo de água');11 expect(hydrate('1 cachaça, 5 cervejas e 1 copo de vinho')).toBe('7 copos de água');12 expect(hydrate('2 shots de tequila, 2 cervejas e 1 corote')).toBe('5 copos de água');13 expect(hydrate('1 copo de catuaba, 1 cervejas e 1 copo de vinho')).toBe('3 copos de água');14 expect(hydrate('4 caipirinhas e 2 cervejas')).toBe('6 copos de água');15 });...
hidratar.test.js
Source:hidratar.test.js
...6 it('Testa se hydrate é uma função', () => {7 expect(typeof hydrate).toBe('function');8 });9 it('Ao receber uma string retorne a sugestão de quantos copos de água deve-se beber', () => {10 expect(hydrate('1 cerveja')).toBe('1 copo de água');11 expect(hydrate('1 cachaça, 5 cervejas e 1 copo de vinho')).toBe('7 copos de água');12 expect(hydrate('2 shots de tequila, 2 cervejas e 1 corote')).toBe('5 copos de água');13 expect(hydrate('1 copo de catuaba, 1 cervejas e 1 copo de vinho')).toBe('3 copos de água');14 expect(hydrate('4 caipirinhas e 2 cervejas')).toBe('6 copos de água');15 });...
Using AI Code Generation
1import { hydrate } from 'react-dom'2import { App } from './App'3hydrate(<App />, document.getElementById('root'))4import { render } from 'react-dom'5import { App } from './App'6render(<App />, document.getElementById('root'))7import { render } from '@testing-library/react'8import { App } from './App'9render(<App />)10import { render } from '@testing-library/react'11import { App } from './App'12render(<App />, { container: document.body.appendChild(document.createElement('div')) })13import { render } from '@testing-library/react'14import { App } from './App'15render(<App />, { container: document.body })16import { render } from '@testing-library/react'17import { App } from './App'18render(<App />, { container: document.body.appendChild(document.createElement('div')) })19import { render } from '@testing-library/react'20import { App } from './App'21render(<App />, { container: document.body.appendChild(document.createElement('div')) })22import { render } from '@testing-library/react'23import { App } from './App'24render(<App />, { container: document.body.appendChild(document.createElement('div')) })25import { render } from '@testing-library/react'26import { App } from './App'27render(<App />, { container: document.body.appendChild(document.createElement('div')) })28import { render } from '@testing-library/react'29import { App } from './App'30render(<App />, { container: document.body.appendChild(document.createElement('div')) })31import
Using AI Code Generation
1import { hydrate } from 'react-dom'2import { act } from 'react-dom/test-utils'3import { renderHook } from '@testing-library/react-hooks'4import useFetch from './useFetch'5describe('useFetch', () => {6 it('should fetch data', async () => {7 await waitForNextUpdate()8 expect(result.current.data.title).toBe('delectus aut autem')9 })10})11import { hydrate } from 'react-dom'12import { act } from 'react-dom/test-utils'13import { renderHook } from '@testing-library/react-hooks'14import useFetch from './useFetch'15describe('useFetch', () => {16 it('should fetch data', async () => {17 await waitForNextUpdate()18 expect(result.current.data.title).toBe('delectus aut autem')19 })20})21import { hydrate } from 'react-dom'22import { act } from 'react-dom/test-utils'23import { renderHook } from '@testing-library/react-hooks'24import useFetch from './useFetch'25describe('useFetch', () => {26 it('should fetch data', async () => {27 await waitForNextUpdate()28 expect(result.current.data.title).toBe('delectus aut autem')29 })30})31import { hydrate } from 'react-dom'32import { act } from 'react-dom/test-utils'33import { renderHook } from '@testing-library/react-hooks'34import useFetch from './useFetch'35describe('useFetch', () => {36 it('should fetch data', async () => {37 const { result, waitForNext
Using AI Code Generation
1import { hydrate } from 'react-dom';2import { App } from './App';3import { act } from 'react-dom/test-utils';4act(() => {5 hydrate(<App />, document.getElementById('root'));6});
Using AI Code Generation
1import { hydrate } from 'react-dom';2import { act } from 'react-dom/test-utils';3import { renderHook } from '@testing-library/react-hooks';4import useFetch from '../useFetch';5describe('useFetch', () => {6 it('should fetch data from server', async () => {7 const { result, waitForNextUpdate } = renderHook(() =>8 );9 await waitForNextUpdate();10 expect(result.current.data).toEqual('hello');11 });12});13import { useState, useEffect } from 'react';14export default function useFetch(url) {15 const [data, setData] = useState(null);16 useEffect(() => {17 fetch(url)18 .then((res) => res.text())19 .then((text) => setData(text));20 }, [url]);21 return { data };22}23module.exports = 'hello';24import { hydrate } from 'react-dom';25import { act } from 'react-dom/test-utils';26import { renderHook, act as actHook } from '@testing-library/react-hooks';27import useCounter from '../useCounter';28describe('useCounter', () => {29 it('should increment counter', () => {30 const { result } = renderHook(() => useCounter());31 actHook(() => {32 result.current.increment();33 });34 expect(result.current.count).toBe(1);35 });36});37import { useReducer } from 'react';38function reducer(state, action) {39 switch (action.type) {40 return { count: state.count + 1 };41 return { count: state.count - 1 };42 throw new Error();43 }44}45export default function useCounter() {46 const [state, dispatch] = useReducer(reducer, { count: 0 });47 const increment = () => dispatch({ type: 'INCREMENT' });48 const decrement = () => dispatch({ type: 'DECREMENT' });49 return { ...state, increment, decrement };50}51import { hydrate } from 'react-dom';52import { act } from 'react-dom/test-utils';53import { renderHook }
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import useCounter from './useCounter';3test('should use custom hook', () => {4 const { result, hydrate } = renderHook(() => useCounter());5 expect(result.current.count).toBe(0);6 act(() => {7 result.current.increment();8 });9 expect(result.current.count).toBe(1);10 hydrate();11 expect(result.current.count).toBe(0);12});13import { useState } from 'react';14const useCounter = () => {15 const [count, setCount] = useState(0);16 const increment = () => setCount(count + 1);17 return { count, increment };18};19export default useCounter;20import { renderHook, act } from '@testing-library/react-hooks';21import useCounter from './useCounter';22test('should use custom hook', () => {23 const { result, hydrate } = renderHook(() => useCounter());24 expect(result.current.count).toBe(0);25 act(() => {26 result.current.increment();27 });28 expect(result.current.count).toBe(1);29 hydrate({ count: 5 });30 expect(result.current.count).toBe(5);31});32import { useState } from 'react';33const useCounter = () => {34 const [count, setCount] = useState(0);35 const increment = () => setCount(count + 1);36 return { count, increment };37};38export default useCounter;
Using AI Code Generation
1import { hydrate } from 'react-dom';2import { App } from './App';3hydrate(<App />, document.getElementById('root'));4import { renderHook } from 'testing-library-react-hooks';5import { useFetch } from './useFetch';6describe('useFetch', () => {7 it('should fetch data', async () => {8 const { result, waitForNextUpdate } = renderHook(() => useFetch());9 await waitForNextUpdate();10 expect(result.current.data).toEqual({ name: 'John' });11 });12});13import { useState, useEffect } from 'react';14export const useFetch = () => {15 const [data, setData] = useState({});16 useEffect(() => {17 (async () => {18 const data = await response.json();19 setData(data);20 })();21 }, []);22 return { data };23};24import { render } from '@testing-library/react';25import { App } from './App';26test('useCounter', () => {27 const { result } = render(<App />);28 expect(result.current.count).toBe(0);29 act(() => {30 result.current.increment();31 });32 expect(result.current.count).toBe(1);33});34import { renderHook, act } from 'testing-library-react-hooks';35import { useCounter } from './useCounter';36describe('useCounter', () => {37 it('should increment', () => {38 const { result } = renderHook(() => useCounter());39 expect(result.current.count).toBe(0);40 act(() => {41 result.current.increment();42 });43 expect(result.current.count).toBe(1);44 });45});46import { useState } from 'react';47export const useCounter = () => {48 const [count, setCount] = useState(0);49 const increment = () => {50 setCount(count + 1);51 };52 return { count, increment };53};
Using AI Code Generation
1import { hydrate } from 'react-dom';2import { act } from 'react-dom/test-utils';3import { renderHook } from '@testing-library/react-hooks';4import { useFetch } from './useFetch';5import { render, screen } from '@testing-library/react';6import App from './App';7import { rest } from 'msw';8import { setupServer } from 'msw/node';9import { waitFor } from '@testing-library/dom';10const server = setupServer(11 return res(12 ctx.json({13 })14 );15 })16);17beforeAll(() => server.listen());18afterEach(() => server.resetHandlers());19afterAll(() => server.close());20test('should fetch data', async () => {21 const { result, waitForNextUpdate } = renderHook(() =>22 );23 expect(result.current.data).toBe(null);24 expect(result.current.loading).toBe(true);25 await waitForNextUpdate();26 expect(result.current.data).not.toBe(null);27 expect(result.current.loading).toBe(false);28});29test('should fetch data and render it in the document', async () => {30 const { container } = render(<App />);31 await waitFor(() => screen.getByText(/delectus aut autem/i));32 expect(container).toMatchSnapshot();33});
Using AI Code Generation
1import { hydrate } from 'react-dom';2import { act } from 'react-dom/test-utils';3import { renderHook } from '@testing-library/react-hooks';4import useFetch from './useFetch';5it('should return data', async () => {6 expect(result.current.loading).toBeTruthy();7 await waitForNextUpdate();8 expect(result.current.loading).toBeFalsy();9 expect(result.current.data).toEqual({ userId: 1, id: 1, title: 'delectus aut autem', completed: false });10});11import { hydrate } from 'react-dom';12import { act } from 'react-dom/test-utils';13import { renderHook } from '@testing-library/react-hooks';14import useFetch from './useFetch';15it('should return data', async () => {16 expect(result.current.loading).toBeTruthy();17 await waitForNextUpdate();18 expect(result.current.loading).toBeFalsy();19 expect(result.current.data).toEqual({ userId: 1, id: 1, title: 'delectus aut autem', completed: false });20});21import { hydrate } from 'react-dom';22import { act } from 'react-dom/test-utils';23import { renderHook } from '@testing-library/react-hooks';24import useFetch from './useFetch';25it('should return data', async () => {26 expect(result.current.loading).toBeTruthy();27 await waitForNextUpdate();28 expect(result.current.loading).toBeFalsy();29 expect(result.current.data).toEqual({ userId: 1, id: 1, title: 'delectus aut autem', completed: false });30});
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!!