Best JavaScript code snippet using wpt
BaseTransition.spec.ts
Source:BaseTransition.spec.ts
1import {2 nodeOps,3 render,4 h,5 BaseTransition,6 BaseTransitionProps,7 ref,8 nextTick,9 serializeInner,10 serialize,11 VNodeProps,12 KeepAlive,13 TestElement14} from '@vue/runtime-test'15function mount(16 props: BaseTransitionProps,17 slot: () => any,18 withKeepAlive = false19) {20 const root = nodeOps.createElement('div')21 render(22 h(BaseTransition, props, () => {23 return withKeepAlive ? h(KeepAlive, null, slot()) : slot()24 }),25 root26 )27 return root28}29function mockProps(extra: BaseTransitionProps = {}, withKeepAlive = false) {30 const cbs: {31 doneEnter: Record<string, () => void>32 doneLeave: Record<string, () => void>33 } = {34 doneEnter: {},35 doneLeave: {}36 }37 const props: BaseTransitionProps = {38 onBeforeEnter: jest.fn(el => {39 if (!extra.persisted && !withKeepAlive) {40 expect(el.parentNode).toBeNull()41 }42 }),43 onEnter: jest.fn((el, done) => {44 cbs.doneEnter[serialize(el as TestElement)] = done45 }),46 onAfterEnter: jest.fn(),47 onEnterCancelled: jest.fn(),48 onBeforeLeave: jest.fn(),49 onLeave: jest.fn((el, done) => {50 cbs.doneLeave[serialize(el as TestElement)] = done51 }),52 onAfterLeave: jest.fn(),53 onLeaveCancelled: jest.fn(),54 onBeforeAppear: jest.fn(),55 onAppear: jest.fn((el, done) => {56 cbs.doneEnter[serialize(el as TestElement)] = done57 }),58 onAfterAppear: jest.fn(),59 onAppearCancelled: jest.fn(),60 ...extra61 }62 return {63 props,64 cbs65 }66}67function assertCalls(68 props: BaseTransitionProps,69 calls: Record<string, number>70) {71 Object.keys(calls).forEach(key => {72 expect(props[key as keyof BaseTransitionProps]).toHaveBeenCalledTimes(73 calls[key]74 )75 })76}77function assertCalledWithEl(fn: any, expected: string, callIndex = 0) {78 expect(serialize((fn as jest.Mock).mock.calls[callIndex][0])).toBe(expected)79}80interface ToggleOptions {81 trueBranch: () => any82 falseBranch: () => any83 trueSerialized: string84 falseSerialized: string85}86type TestFn = (o: ToggleOptions, withKeepAlive?: boolean) => void87function runTestWithElements(tester: TestFn) {88 return tester({89 trueBranch: () => h('div'),90 falseBranch: () => h('span'),91 trueSerialized: `<div></div>`,92 falseSerialized: `<span></span>`93 })94}95function runTestWithComponents(tester: TestFn) {96 const CompA = ({ msg }: { msg: string }) => h('div', msg)97 // test HOC98 const CompB = ({ msg }: { msg: string }) => h(CompC, { msg })99 const CompC = ({ msg }: { msg: string }) => h('span', msg)100 return tester({101 trueBranch: () => h(CompA, { msg: 'foo' }),102 falseBranch: () => h(CompB, { msg: 'bar' }),103 trueSerialized: `<div>foo</div>`,104 falseSerialized: `<span>bar</span>`105 })106}107function runTestWithKeepAlive(tester: TestFn) {108 const trueComp = {109 setup() {110 const count = ref(0)111 return () => h('div', count.value)112 }113 }114 const falseComp = {115 setup() {116 const count = ref(0)117 return () => h('span', count.value)118 }119 }120 return tester(121 {122 trueBranch: () => h(trueComp),123 falseBranch: () => h(falseComp),124 trueSerialized: `<div>0</div>`,125 falseSerialized: `<span>0</span>`126 },127 true /* withKeepAlive: true */128 )129}130describe('BaseTransition', () => {131 test('appear: true w/ appear hooks', () => {132 const { props, cbs } = mockProps({133 appear: true134 })135 mount(props, () => h('div'))136 expect(props.onBeforeAppear).toHaveBeenCalledTimes(1)137 expect(props.onAppear).toHaveBeenCalledTimes(1)138 expect(props.onAfterAppear).not.toHaveBeenCalled()139 // enter should not be called140 expect(props.onBeforeEnter).not.toHaveBeenCalled()141 expect(props.onEnter).not.toHaveBeenCalled()142 expect(props.onAfterEnter).not.toHaveBeenCalled()143 cbs.doneEnter[`<div></div>`]()144 expect(props.onAfterAppear).toHaveBeenCalledTimes(1)145 expect(props.onAfterEnter).not.toHaveBeenCalled()146 })147 test('appear: true w/ fallback to enter hooks', () => {148 const { props, cbs } = mockProps({149 appear: true,150 onBeforeAppear: undefined,151 onAppear: undefined,152 onAfterAppear: undefined,153 onAppearCancelled: undefined154 })155 mount(props, () => h('div'))156 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)157 expect(props.onEnter).toHaveBeenCalledTimes(1)158 expect(props.onAfterEnter).not.toHaveBeenCalled()159 cbs.doneEnter[`<div></div>`]()160 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)161 })162 describe('persisted: true', () => {163 // this is pretty much how v-show is implemented164 // (but using the directive API instead)165 function mockPersistedHooks() {166 const state = { show: true }167 const toggle = ref(true)168 const hooks: VNodeProps = {169 onVnodeBeforeMount(vnode) {170 vnode.transition!.beforeEnter(vnode.el!)171 },172 onVnodeMounted(vnode) {173 vnode.transition!.enter(vnode.el!)174 },175 onVnodeUpdated(vnode, oldVnode) {176 if (oldVnode.props!.id !== vnode.props!.id) {177 if (vnode.props!.id) {178 vnode.transition!.beforeEnter(vnode.el!)179 state.show = true180 vnode.transition!.enter(vnode.el!)181 } else {182 vnode.transition!.leave(vnode.el!, () => {183 state.show = false184 })185 }186 }187 }188 }189 return { state, toggle, hooks }190 }191 test('w/ appear: false', async () => {192 const { props, cbs } = mockProps({ persisted: true })193 const { toggle, state, hooks } = mockPersistedHooks()194 mount(props, () => h('div', { id: toggle.value, ...hooks }))195 // without appear: true, enter hooks should not be called on mount196 expect(props.onBeforeEnter).not.toHaveBeenCalled()197 expect(props.onEnter).not.toHaveBeenCalled()198 expect(props.onAfterEnter).not.toHaveBeenCalled()199 toggle.value = false200 await nextTick()201 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)202 expect(props.onLeave).toHaveBeenCalledTimes(1)203 expect(props.onAfterLeave).not.toHaveBeenCalled()204 expect(state.show).toBe(true) // should still be shown205 cbs.doneLeave[`<div id=false></div>`]()206 expect(state.show).toBe(false) // should be hidden now207 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)208 toggle.value = true209 await nextTick()210 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)211 expect(props.onEnter).toHaveBeenCalledTimes(1)212 expect(props.onAfterEnter).not.toHaveBeenCalled()213 expect(state.show).toBe(true) // should be shown now214 cbs.doneEnter[`<div id=true></div>`]()215 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)216 })217 test('w/ appear: true', () => {218 const { props, cbs } = mockProps({ persisted: true, appear: true })219 const { hooks } = mockPersistedHooks()220 mount(props, () => h('div', hooks))221 expect(props.onBeforeAppear).toHaveBeenCalledTimes(1)222 expect(props.onAppear).toHaveBeenCalledTimes(1)223 expect(props.onAfterAppear).not.toHaveBeenCalled()224 cbs.doneEnter[`<div></div>`]()225 expect(props.onAfterAppear).toHaveBeenCalledTimes(1)226 })227 })228 describe('toggle on-off', () => {229 async function testToggleOnOff(230 {231 trueBranch,232 trueSerialized,233 falseBranch,234 falseSerialized235 }: ToggleOptions,236 mode?: BaseTransitionProps['mode']237 ) {238 const toggle = ref(true)239 const { props, cbs } = mockProps({ mode })240 const root = mount(241 props,242 () => (toggle.value ? trueBranch() : falseBranch())243 )244 // without appear: true, enter hooks should not be called on mount245 expect(props.onBeforeEnter).not.toHaveBeenCalled()246 expect(props.onEnter).not.toHaveBeenCalled()247 expect(props.onAfterEnter).not.toHaveBeenCalled()248 toggle.value = false249 await nextTick()250 // comment placeholder enters immediately251 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)252 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)253 assertCalledWithEl(props.onBeforeLeave, trueSerialized)254 expect(props.onLeave).toHaveBeenCalledTimes(1)255 assertCalledWithEl(props.onLeave, trueSerialized)256 expect(props.onAfterLeave).not.toHaveBeenCalled()257 cbs.doneLeave[trueSerialized]()258 expect(serializeInner(root)).toBe(falseSerialized)259 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)260 assertCalledWithEl(props.onAfterLeave, trueSerialized)261 toggle.value = true262 await nextTick()263 expect(serializeInner(root)).toBe(trueSerialized)264 // before enter spy asserts node has no parent when it's called265 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)266 assertCalledWithEl(props.onBeforeEnter, trueSerialized)267 expect(props.onEnter).toHaveBeenCalledTimes(1)268 assertCalledWithEl(props.onEnter, trueSerialized)269 expect(props.onAfterEnter).not.toHaveBeenCalled()270 cbs.doneEnter[trueSerialized]()271 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)272 assertCalledWithEl(props.onAfterEnter, trueSerialized)273 assertCalls(props, {274 onBeforeEnter: 1,275 onEnter: 1,276 onAfterEnter: 1,277 onEnterCancelled: 0,278 onBeforeLeave: 1,279 onLeave: 1,280 onAfterLeave: 1,281 onLeaveCancelled: 0282 })283 }284 test('w/ element', async () => {285 await testToggleOnOff({286 trueBranch: () => h('div'),287 trueSerialized: `<div></div>`,288 falseBranch: () => null,289 falseSerialized: `<!---->`290 })291 })292 test('w/ component', async () => {293 const Comp = ({ msg }: { msg: string }) => h('div', msg)294 await testToggleOnOff({295 trueBranch: () => h(Comp, { msg: 'hello' }),296 trueSerialized: `<div>hello</div>`,297 falseBranch: () => null,298 falseSerialized: `<!---->`299 })300 })301 test('w/ mode: "in-out', async () => {302 await testToggleOnOff(303 {304 trueBranch: () => h('div'),305 trueSerialized: `<div></div>`,306 falseBranch: () => null,307 falseSerialized: `<!---->`308 },309 'in-out'310 )311 })312 })313 describe('toggle on-off before finish', () => {314 async function testToggleOnOffBeforeFinish({315 trueBranch,316 trueSerialized,317 falseBranch = () => null,318 falseSerialized = `<!---->`319 }: ToggleOptions) {320 const toggle = ref(false)321 const { props, cbs } = mockProps()322 const root = mount(323 props,324 () => (toggle.value ? trueBranch() : falseBranch())325 )326 // start enter327 toggle.value = true328 await nextTick()329 expect(serializeInner(root)).toBe(trueSerialized)330 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)331 expect(props.onEnter).toHaveBeenCalledTimes(1)332 // leave before enter finishes333 toggle.value = false334 await nextTick()335 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)336 expect(props.onEnterCancelled).toHaveBeenCalled()337 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)338 expect(props.onLeave).toHaveBeenCalledTimes(1)339 expect(props.onAfterLeave).not.toHaveBeenCalled()340 // calling doneEnter now should have no effect341 cbs.doneEnter[trueSerialized]()342 expect(props.onAfterEnter).not.toHaveBeenCalled()343 // enter again before leave finishes344 toggle.value = true345 await nextTick()346 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)347 expect(props.onEnter).toHaveBeenCalledTimes(2)348 // 1. should remove the previous leaving <div> so there is only one <div>349 // 2. should remove the comment placeholder for the off branch350 expect(serializeInner(root)).toBe(trueSerialized)351 // note onLeaveCancelled is NOT called because it was a forced early352 // removal instead of a cancel. Instead, onAfterLeave should be called.353 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)354 // calling doneLeave again should have no effect now355 cbs.doneLeave[trueSerialized]()356 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)357 cbs.doneEnter[trueSerialized]()358 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)359 assertCalls(props, {360 onBeforeEnter: 2,361 onEnter: 2,362 onAfterEnter: 1,363 onEnterCancelled: 1,364 onBeforeLeave: 1,365 onLeave: 1,366 onAfterLeave: 1,367 onLeaveCancelled: 0368 })369 }370 test('w/ element', async () => {371 await testToggleOnOffBeforeFinish({372 trueBranch: () => h('div'),373 trueSerialized: `<div></div>`,374 falseBranch: () => null,375 falseSerialized: `<!---->`376 })377 })378 test('w/ component', async () => {379 const Comp = ({ msg }: { msg: string }) => h('div', msg)380 await testToggleOnOffBeforeFinish({381 trueBranch: () => h(Comp, { msg: 'hello' }),382 trueSerialized: `<div>hello</div>`,383 falseBranch: () => null,384 falseSerialized: `<!---->`385 })386 })387 })388 describe('toggle between branches', () => {389 async function testToggleBranches(390 {391 trueBranch,392 falseBranch,393 trueSerialized,394 falseSerialized395 }: ToggleOptions,396 withKeepAlive = false397 ) {398 const toggle = ref(true)399 const { props, cbs } = mockProps({}, withKeepAlive)400 const root = mount(401 props,402 () => (toggle.value ? trueBranch() : falseBranch()),403 withKeepAlive404 )405 // without appear: true, enter hooks should not be called on mount406 expect(props.onBeforeEnter).not.toHaveBeenCalled()407 expect(props.onEnter).not.toHaveBeenCalled()408 expect(props.onAfterEnter).not.toHaveBeenCalled()409 // start toggle410 toggle.value = false411 await nextTick()412 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)413 // leave should be triggered414 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)415 assertCalledWithEl(props.onBeforeLeave, trueSerialized)416 expect(props.onLeave).toHaveBeenCalledTimes(1)417 assertCalledWithEl(props.onLeave, trueSerialized)418 expect(props.onAfterLeave).not.toHaveBeenCalled()419 // enter should also be triggered420 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)421 assertCalledWithEl(props.onBeforeEnter, falseSerialized)422 expect(props.onEnter).toHaveBeenCalledTimes(1)423 assertCalledWithEl(props.onEnter, falseSerialized)424 expect(props.onAfterEnter).not.toHaveBeenCalled()425 // finish enter426 cbs.doneEnter[falseSerialized]()427 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)428 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)429 assertCalledWithEl(props.onAfterEnter, falseSerialized)430 expect(props.onAfterLeave).not.toHaveBeenCalled()431 // finish leave432 cbs.doneLeave[trueSerialized]()433 expect(serializeInner(root)).toBe(`${falseSerialized}`)434 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)435 assertCalledWithEl(props.onAfterLeave, trueSerialized)436 // toggle again437 toggle.value = true438 await nextTick()439 expect(serializeInner(root)).toBe(`${falseSerialized}${trueSerialized}`)440 // leave should be triggered441 expect(props.onBeforeLeave).toHaveBeenCalledTimes(2)442 assertCalledWithEl(props.onBeforeLeave, falseSerialized, 1)443 expect(props.onLeave).toHaveBeenCalledTimes(2)444 assertCalledWithEl(props.onLeave, falseSerialized, 1)445 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)446 // enter should also be triggered447 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)448 assertCalledWithEl(props.onBeforeEnter, trueSerialized, 1)449 expect(props.onEnter).toHaveBeenCalledTimes(2)450 assertCalledWithEl(props.onEnter, trueSerialized, 1)451 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)452 // finish leave first453 cbs.doneLeave[falseSerialized]()454 expect(serializeInner(root)).toBe(`${trueSerialized}`)455 expect(props.onAfterLeave).toHaveBeenCalledTimes(2)456 assertCalledWithEl(props.onAfterLeave, falseSerialized, 1)457 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)458 // finish enter459 cbs.doneEnter[trueSerialized]()460 expect(serializeInner(root)).toBe(`${trueSerialized}`)461 expect(props.onAfterEnter).toHaveBeenCalledTimes(2)462 assertCalledWithEl(props.onAfterEnter, trueSerialized, 1)463 assertCalls(props, {464 onBeforeEnter: 2,465 onEnter: 2,466 onAfterEnter: 2,467 onBeforeLeave: 2,468 onLeave: 2,469 onAfterLeave: 2,470 onEnterCancelled: 0,471 onLeaveCancelled: 0472 })473 }474 test('w/ elements', async () => {475 await runTestWithElements(testToggleBranches)476 })477 test('w/ components', async () => {478 await runTestWithComponents(testToggleBranches)479 })480 test('w/ KeepAlive', async () => {481 await runTestWithKeepAlive(testToggleBranches)482 })483 })484 describe('toggle between branches before finish', () => {485 async function testToggleBranchesBeforeFinish(486 {487 trueBranch,488 falseBranch,489 trueSerialized,490 falseSerialized491 }: ToggleOptions,492 withKeepAlive = false493 ) {494 const toggle = ref(true)495 const { props, cbs } = mockProps({}, withKeepAlive)496 const root = mount(497 props,498 () => (toggle.value ? trueBranch() : falseBranch()),499 withKeepAlive500 )501 // start toggle502 toggle.value = false503 await nextTick()504 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)505 // leave should be triggered506 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)507 assertCalledWithEl(props.onBeforeLeave, trueSerialized)508 expect(props.onLeave).toHaveBeenCalledTimes(1)509 assertCalledWithEl(props.onLeave, trueSerialized)510 expect(props.onAfterLeave).not.toHaveBeenCalled()511 // enter should also be triggered512 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)513 assertCalledWithEl(props.onBeforeEnter, falseSerialized)514 expect(props.onEnter).toHaveBeenCalledTimes(1)515 assertCalledWithEl(props.onEnter, falseSerialized)516 expect(props.onAfterEnter).not.toHaveBeenCalled()517 // toggle again before transition finishes518 toggle.value = true519 await nextTick()520 // the previous leaving true branch should have been force-removed521 expect(serializeInner(root)).toBe(`${falseSerialized}${trueSerialized}`)522 if (!withKeepAlive) {523 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)524 assertCalledWithEl(props.onAfterLeave, trueSerialized)525 } else {526 expect(props.onLeaveCancelled).toHaveBeenCalledTimes(1)527 assertCalledWithEl(props.onLeaveCancelled, trueSerialized)528 }529 // false branch enter is cancelled530 expect(props.onEnterCancelled).toHaveBeenCalledTimes(1)531 assertCalledWithEl(props.onEnterCancelled, falseSerialized)532 // calling false branch done should have no effect now533 cbs.doneEnter[falseSerialized]()534 expect(props.onAfterEnter).not.toHaveBeenCalled()535 // false branch leave triggered536 expect(props.onBeforeLeave).toHaveBeenCalledTimes(2)537 assertCalledWithEl(props.onBeforeLeave, falseSerialized, 1)538 expect(props.onLeave).toHaveBeenCalledTimes(2)539 assertCalledWithEl(props.onLeave, falseSerialized, 1)540 // true branch enter triggered541 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)542 assertCalledWithEl(props.onBeforeEnter, trueSerialized, 1)543 expect(props.onEnter).toHaveBeenCalledTimes(2)544 assertCalledWithEl(props.onEnter, trueSerialized, 1)545 expect(props.onAfterEnter).not.toHaveBeenCalled()546 // toggle again547 toggle.value = false548 await nextTick()549 // the previous leaving false branch should have been force-removed550 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)551 if (!withKeepAlive) {552 expect(props.onAfterLeave).toHaveBeenCalledTimes(2)553 assertCalledWithEl(props.onAfterLeave, falseSerialized, 1)554 } else {555 expect(props.onLeaveCancelled).toHaveBeenCalledTimes(2)556 assertCalledWithEl(props.onLeaveCancelled, falseSerialized, 1)557 }558 // true branch enter is cancelled559 expect(props.onEnterCancelled).toHaveBeenCalledTimes(2)560 assertCalledWithEl(props.onEnterCancelled, trueSerialized, 1)561 // calling true branch enter done should have no effect562 cbs.doneEnter[trueSerialized]()563 expect(props.onAfterEnter).not.toHaveBeenCalled()564 // true branch leave triggered (again)565 expect(props.onBeforeLeave).toHaveBeenCalledTimes(3)566 assertCalledWithEl(props.onBeforeLeave, trueSerialized, 2)567 expect(props.onLeave).toHaveBeenCalledTimes(3)568 assertCalledWithEl(props.onLeave, trueSerialized, 2)569 // false branch enter triggered (again)570 expect(props.onBeforeEnter).toHaveBeenCalledTimes(3)571 assertCalledWithEl(props.onBeforeEnter, falseSerialized, 2)572 expect(props.onEnter).toHaveBeenCalledTimes(3)573 assertCalledWithEl(props.onEnter, falseSerialized, 2)574 expect(props.onAfterEnter).not.toHaveBeenCalled()575 cbs.doneEnter[falseSerialized]()576 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)577 assertCalledWithEl(props.onAfterEnter, falseSerialized)578 cbs.doneLeave[trueSerialized]()579 if (!withKeepAlive) {580 expect(props.onAfterLeave).toHaveBeenCalledTimes(3)581 assertCalledWithEl(props.onAfterLeave, trueSerialized, 2)582 } else {583 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)584 assertCalledWithEl(props.onAfterLeave, trueSerialized)585 }586 assertCalls(props, {587 onBeforeEnter: 3,588 onEnter: 3,589 onAfterEnter: 1,590 onEnterCancelled: 2,591 onBeforeLeave: 3,592 onLeave: 3,593 onAfterLeave: withKeepAlive ? 1 : 3,594 onLeaveCancelled: withKeepAlive ? 2 : 0595 })596 }597 test('w/ elements', async () => {598 await runTestWithElements(testToggleBranchesBeforeFinish)599 })600 test('w/ components', async () => {601 await runTestWithComponents(testToggleBranchesBeforeFinish)602 })603 test('w/ KeepAlive', async () => {604 await runTestWithKeepAlive(testToggleBranchesBeforeFinish)605 })606 })607 describe('mode: "out-in"', () => {608 async function testOutIn(609 {610 trueBranch,611 falseBranch,612 trueSerialized,613 falseSerialized614 }: ToggleOptions,615 withKeepAlive = false616 ) {617 const toggle = ref(true)618 const { props, cbs } = mockProps({ mode: 'out-in' }, withKeepAlive)619 const root = mount(620 props,621 () => (toggle.value ? trueBranch() : falseBranch()),622 withKeepAlive623 )624 // trigger toggle625 toggle.value = false626 await nextTick()627 // a placeholder is injected until the leave finishes628 expect(serializeInner(root)).toBe(`${trueSerialized}<!---->`)629 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)630 assertCalledWithEl(props.onBeforeLeave, trueSerialized)631 expect(props.onLeave).toHaveBeenCalledTimes(1)632 assertCalledWithEl(props.onLeave, trueSerialized)633 expect(props.onAfterLeave).not.toHaveBeenCalled()634 // enter should not have started635 expect(props.onBeforeEnter).not.toHaveBeenCalled()636 expect(props.onEnter).not.toHaveBeenCalled()637 expect(props.onAfterEnter).not.toHaveBeenCalled()638 cbs.doneLeave[trueSerialized]()639 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)640 assertCalledWithEl(props.onAfterLeave, trueSerialized)641 // have to wait for a tick because this triggers an update642 await nextTick()643 expect(serializeInner(root)).toBe(falseSerialized)644 // enter should start645 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)646 assertCalledWithEl(props.onBeforeEnter, falseSerialized)647 expect(props.onEnter).toHaveBeenCalledTimes(1)648 assertCalledWithEl(props.onEnter, falseSerialized)649 expect(props.onAfterEnter).not.toHaveBeenCalled()650 // finish enter651 cbs.doneEnter[falseSerialized]()652 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)653 assertCalledWithEl(props.onAfterEnter, falseSerialized)654 // toggle again655 toggle.value = true656 await nextTick()657 expect(serializeInner(root)).toBe(`${falseSerialized}<!---->`)658 expect(props.onBeforeLeave).toHaveBeenCalledTimes(2)659 assertCalledWithEl(props.onBeforeLeave, falseSerialized, 1)660 expect(props.onLeave).toHaveBeenCalledTimes(2)661 assertCalledWithEl(props.onLeave, falseSerialized, 1)662 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)663 // enter should not have started664 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)665 expect(props.onEnter).toHaveBeenCalledTimes(1)666 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)667 cbs.doneLeave[falseSerialized]()668 expect(props.onAfterLeave).toHaveBeenCalledTimes(2)669 assertCalledWithEl(props.onAfterLeave, falseSerialized, 1)670 await nextTick()671 expect(serializeInner(root)).toBe(trueSerialized)672 // enter should start673 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)674 assertCalledWithEl(props.onBeforeEnter, trueSerialized, 1)675 expect(props.onEnter).toHaveBeenCalledTimes(2)676 assertCalledWithEl(props.onEnter, trueSerialized, 1)677 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)678 // finish enter679 cbs.doneEnter[trueSerialized]()680 expect(props.onAfterEnter).toHaveBeenCalledTimes(2)681 assertCalledWithEl(props.onAfterEnter, trueSerialized, 1)682 assertCalls(props, {683 onBeforeEnter: 2,684 onEnter: 2,685 onAfterEnter: 2,686 onEnterCancelled: 0,687 onBeforeLeave: 2,688 onLeave: 2,689 onAfterLeave: 2,690 onLeaveCancelled: 0691 })692 }693 test('w/ elements', async () => {694 await runTestWithElements(testOutIn)695 })696 test('w/ components', async () => {697 await runTestWithComponents(testOutIn)698 })699 test('w/ KeepAlive', async () => {700 await runTestWithKeepAlive(testOutIn)701 })702 })703 describe('mode: "out-in" toggle before finish', () => {704 async function testOutInBeforeFinish(705 { trueBranch, falseBranch, trueSerialized }: ToggleOptions,706 withKeepAlive = false707 ) {708 const toggle = ref(true)709 const { props, cbs } = mockProps({ mode: 'out-in' }, withKeepAlive)710 const root = mount(711 props,712 () => (toggle.value ? trueBranch() : falseBranch()),713 withKeepAlive714 )715 // trigger toggle716 toggle.value = false717 await nextTick()718 // toggle again before finish719 toggle.value = true720 await nextTick()721 // expected behavior: the previous true branch is preserved,722 // and a placeholder is injected for the replacement.723 // the leaving node is replaced with the replace node (of the same branch)724 // when it finishes leaving725 expect(serializeInner(root)).toBe(`${trueSerialized}<!---->`)726 // enter hooks should never be called (for neither branch)727 expect(props.onBeforeEnter).not.toHaveBeenCalled()728 expect(props.onEnter).not.toHaveBeenCalled()729 expect(props.onAfterEnter).not.toHaveBeenCalled()730 // finish leave731 cbs.doneLeave[trueSerialized]()732 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)733 assertCalledWithEl(props.onAfterLeave, trueSerialized)734 await nextTick()735 // leaving node and placeholder removed, enter node injected736 expect(serializeInner(root)).toBe(trueSerialized)737 // enter should start738 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)739 assertCalledWithEl(props.onBeforeEnter, trueSerialized)740 expect(props.onEnter).toHaveBeenCalledTimes(1)741 assertCalledWithEl(props.onEnter, trueSerialized)742 expect(props.onAfterEnter).not.toHaveBeenCalled()743 // finish enter744 cbs.doneEnter[trueSerialized]()745 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)746 assertCalledWithEl(props.onAfterEnter, trueSerialized)747 assertCalls(props, {748 onBeforeEnter: 1,749 onEnter: 1,750 onAfterEnter: 1,751 onEnterCancelled: 0,752 onBeforeLeave: 1,753 onLeave: 1,754 onAfterLeave: 1,755 onLeaveCancelled: 0756 })757 }758 test('w/ elements', async () => {759 await runTestWithElements(testOutInBeforeFinish)760 })761 test('w/ components', async () => {762 await runTestWithComponents(testOutInBeforeFinish)763 })764 test('w/ KeepAlive', async () => {765 await runTestWithKeepAlive(testOutInBeforeFinish)766 })767 })768 describe('mode: "out-in" double quick toggle', () => {769 async function testOutInDoubleToggle(770 {771 trueBranch,772 falseBranch,773 trueSerialized,774 falseSerialized775 }: ToggleOptions,776 withKeepAlive = false777 ) {778 const toggle = ref(true)779 const { props, cbs } = mockProps({ mode: 'out-in' }, withKeepAlive)780 const root = mount(781 props,782 () => (toggle.value ? trueBranch() : falseBranch()),783 withKeepAlive784 )785 // double quick toggle786 toggle.value = false787 await nextTick()788 toggle.value = true789 await nextTick()790 toggle.value = false791 await nextTick()792 // expected behavior: the leaving true branch is preserved no matter793 // how many times the state is toggled as long as the leave isn't finished794 // yet. A placeholder is injected for the replacement.795 expect(serializeInner(root)).toBe(`${trueSerialized}<!---->`)796 // enter hooks should never be called (for neither branch)797 expect(props.onBeforeEnter).not.toHaveBeenCalled()798 expect(props.onEnter).not.toHaveBeenCalled()799 expect(props.onAfterEnter).not.toHaveBeenCalled()800 // finish leave801 cbs.doneLeave[trueSerialized]()802 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)803 assertCalledWithEl(props.onAfterLeave, trueSerialized)804 await nextTick()805 // leaving node and placeholder removed, enter node injected806 expect(serializeInner(root)).toBe(falseSerialized)807 // enter should start808 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)809 assertCalledWithEl(props.onBeforeEnter, falseSerialized)810 expect(props.onEnter).toHaveBeenCalledTimes(1)811 assertCalledWithEl(props.onEnter, falseSerialized)812 expect(props.onAfterEnter).not.toHaveBeenCalled()813 // finish enter814 cbs.doneEnter[falseSerialized]()815 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)816 assertCalledWithEl(props.onAfterEnter, falseSerialized)817 assertCalls(props, {818 onBeforeEnter: 1,819 onEnter: 1,820 onAfterEnter: 1,821 onEnterCancelled: 0,822 onBeforeLeave: 1,823 onLeave: 1,824 onAfterLeave: 1,825 onLeaveCancelled: 0826 })827 }828 test('w/ elements', async () => {829 await runTestWithElements(testOutInDoubleToggle)830 })831 test('w/ components', async () => {832 await runTestWithComponents(testOutInDoubleToggle)833 })834 test('w/ KeepAlive', async () => {835 await runTestWithKeepAlive(testOutInDoubleToggle)836 })837 })838 describe('mode: "in-out"', () => {839 async function testInOut(840 {841 trueBranch,842 falseBranch,843 trueSerialized,844 falseSerialized845 }: ToggleOptions,846 withKeepAlive = false847 ) {848 const toggle = ref(true)849 const { props, cbs } = mockProps({ mode: 'in-out' }, withKeepAlive)850 const root = mount(851 props,852 () => (toggle.value ? trueBranch() : falseBranch()),853 withKeepAlive854 )855 toggle.value = false856 await nextTick()857 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)858 // enter should start859 expect(props.onBeforeEnter).toHaveBeenCalledTimes(1)860 assertCalledWithEl(props.onBeforeEnter, falseSerialized)861 expect(props.onEnter).toHaveBeenCalledTimes(1)862 assertCalledWithEl(props.onEnter, falseSerialized)863 expect(props.onAfterEnter).not.toHaveBeenCalled()864 // leave should not start865 expect(props.onBeforeLeave).not.toHaveBeenCalled()866 expect(props.onLeave).not.toHaveBeenCalled()867 expect(props.onAfterLeave).not.toHaveBeenCalled()868 // finish enter869 cbs.doneEnter[falseSerialized]()870 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)871 assertCalledWithEl(props.onAfterEnter, falseSerialized)872 // leave should start now873 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)874 assertCalledWithEl(props.onBeforeLeave, trueSerialized)875 expect(props.onLeave).toHaveBeenCalledTimes(1)876 assertCalledWithEl(props.onLeave, trueSerialized)877 expect(props.onAfterLeave).not.toHaveBeenCalled()878 // finish leave879 cbs.doneLeave[trueSerialized]()880 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)881 assertCalledWithEl(props.onAfterLeave, trueSerialized)882 // toggle again883 toggle.value = true884 await nextTick()885 expect(serializeInner(root)).toBe(`${falseSerialized}${trueSerialized}`)886 // enter should start887 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)888 assertCalledWithEl(props.onBeforeEnter, trueSerialized, 1)889 expect(props.onEnter).toHaveBeenCalledTimes(2)890 assertCalledWithEl(props.onEnter, trueSerialized, 1)891 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)892 // leave should not start893 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)894 expect(props.onLeave).toHaveBeenCalledTimes(1)895 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)896 // finish enter897 cbs.doneEnter[trueSerialized]()898 expect(props.onAfterEnter).toHaveBeenCalledTimes(2)899 assertCalledWithEl(props.onAfterEnter, trueSerialized, 1)900 // leave should start now901 expect(props.onBeforeLeave).toHaveBeenCalledTimes(2)902 assertCalledWithEl(props.onBeforeLeave, falseSerialized, 1)903 expect(props.onLeave).toHaveBeenCalledTimes(2)904 assertCalledWithEl(props.onLeave, falseSerialized, 1)905 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)906 // finish leave907 cbs.doneLeave[falseSerialized]()908 expect(props.onAfterLeave).toHaveBeenCalledTimes(2)909 assertCalledWithEl(props.onAfterLeave, falseSerialized, 1)910 assertCalls(props, {911 onBeforeEnter: 2,912 onEnter: 2,913 onAfterEnter: 2,914 onEnterCancelled: 0,915 onBeforeLeave: 2,916 onLeave: 2,917 onAfterLeave: 2,918 onLeaveCancelled: 0919 })920 }921 test('w/ elements', async () => {922 await runTestWithElements(testInOut)923 })924 test('w/ components', async () => {925 await runTestWithComponents(testInOut)926 })927 test('w/ KeepAlive', async () => {928 await runTestWithKeepAlive(testInOut)929 })930 })931 describe('mode: "in-out" toggle before finish', () => {932 async function testInOutBeforeFinish(933 {934 trueBranch,935 falseBranch,936 trueSerialized,937 falseSerialized938 }: ToggleOptions,939 withKeepAlive = false940 ) {941 const toggle = ref(true)942 const { props, cbs } = mockProps({ mode: 'in-out' }, withKeepAlive)943 const root = mount(944 props,945 () => (toggle.value ? trueBranch() : falseBranch()),946 withKeepAlive947 )948 toggle.value = false949 await nextTick()950 expect(serializeInner(root)).toBe(`${trueSerialized}${falseSerialized}`)951 // toggle back before enter finishes952 toggle.value = true953 await nextTick()954 // should force remove stale true branch955 expect(serializeInner(root)).toBe(`${falseSerialized}${trueSerialized}`)956 expect(props.onBeforeEnter).toHaveBeenCalledTimes(2)957 assertCalledWithEl(props.onBeforeEnter, falseSerialized)958 assertCalledWithEl(props.onBeforeEnter, trueSerialized, 1)959 expect(props.onEnter).toHaveBeenCalledTimes(2)960 assertCalledWithEl(props.onEnter, falseSerialized)961 assertCalledWithEl(props.onEnter, trueSerialized, 1)962 expect(props.onAfterEnter).not.toHaveBeenCalled()963 expect(props.onEnterCancelled).not.toHaveBeenCalled()964 // calling the enter done for false branch does fire the afterEnter965 // hook, but should have no other effects since stale branch has already966 // left967 cbs.doneEnter[falseSerialized]()968 expect(props.onAfterEnter).toHaveBeenCalledTimes(1)969 assertCalledWithEl(props.onAfterEnter, falseSerialized)970 // leave should not start for either branch971 expect(props.onBeforeLeave).not.toHaveBeenCalled()972 expect(props.onLeave).not.toHaveBeenCalled()973 expect(props.onAfterLeave).not.toHaveBeenCalled()974 cbs.doneEnter[trueSerialized]()975 expect(props.onAfterEnter).toHaveBeenCalledTimes(2)976 assertCalledWithEl(props.onAfterEnter, trueSerialized, 1)977 // should start leave for false branch978 expect(props.onBeforeLeave).toHaveBeenCalledTimes(1)979 assertCalledWithEl(props.onBeforeLeave, falseSerialized)980 expect(props.onLeave).toHaveBeenCalledTimes(1)981 assertCalledWithEl(props.onLeave, falseSerialized)982 expect(props.onAfterLeave).not.toHaveBeenCalled()983 // finish leave984 cbs.doneLeave[falseSerialized]()985 expect(serializeInner(root)).toBe(trueSerialized)986 expect(props.onAfterLeave).toHaveBeenCalledTimes(1)987 assertCalledWithEl(props.onAfterLeave, falseSerialized)988 assertCalls(props, {989 onBeforeEnter: 2,990 onEnter: 2,991 onAfterEnter: 2,992 onEnterCancelled: 0,993 onBeforeLeave: 1,994 onLeave: 1,995 onAfterLeave: 1,996 onLeaveCancelled: 0997 })998 }999 test('w/ elements', async () => {1000 await runTestWithElements(testInOutBeforeFinish)1001 })1002 test('w/ components', async () => {1003 await runTestWithComponents(testInOutBeforeFinish)1004 })1005 test('w/ KeepAlive', async () => {1006 await runTestWithKeepAlive(testInOutBeforeFinish)1007 })1008 })...
test_augassign.py
Source:test_augassign.py
1# Augmented assignment test.2from test.support import run_unittest3import unittest4class AugAssignTest(unittest.TestCase):5 def testBasic(self):6 x = 27 x += 18 x *= 29 x **= 210 x -= 811 x //= 512 x %= 313 x &= 214 x |= 515 x ^= 116 x /= 217 self.assertEqual(x, 3.0)18 def test_with_unpacking(self):19 self.assertRaises(SyntaxError, compile, "x, b += 3", "<test>", "exec")20 def testInList(self):21 x = [2]22 x[0] += 123 x[0] *= 224 x[0] **= 225 x[0] -= 826 x[0] //= 527 x[0] %= 328 x[0] &= 229 x[0] |= 530 x[0] ^= 131 x[0] /= 232 self.assertEqual(x[0], 3.0)33 def testInDict(self):34 x = {0: 2}35 x[0] += 136 x[0] *= 237 x[0] **= 238 x[0] -= 839 x[0] //= 540 x[0] %= 341 x[0] &= 242 x[0] |= 543 x[0] ^= 144 x[0] /= 245 self.assertEqual(x[0], 3.0)46 def testSequences(self):47 x = [1,2]48 x += [3,4]49 x *= 250 self.assertEqual(x, [1, 2, 3, 4, 1, 2, 3, 4])51 x = [1, 2, 3]52 y = x53 x[1:2] *= 254 y[1:2] += [1]55 self.assertEqual(x, [1, 2, 1, 2, 3])56 self.assertTrue(x is y)57 def testCustomMethods1(self):58 class aug_test:59 def __init__(self, value):60 self.val = value61 def __radd__(self, val):62 return self.val + val63 def __add__(self, val):64 return aug_test(self.val + val)65 class aug_test2(aug_test):66 def __iadd__(self, val):67 self.val = self.val + val68 return self69 class aug_test3(aug_test):70 def __iadd__(self, val):71 return aug_test3(self.val + val)72 x = aug_test(1)73 y = x74 x += 1075 self.assertIsInstance(x, aug_test)76 self.assertTrue(y is not x)77 self.assertEqual(x.val, 11)78 x = aug_test2(2)79 y = x80 x += 1081 self.assertTrue(y is x)82 self.assertEqual(x.val, 12)83 x = aug_test3(3)84 y = x85 x += 1086 self.assertIsInstance(x, aug_test3)87 self.assertTrue(y is not x)88 self.assertEqual(x.val, 13)89 def testCustomMethods2(test_self):90 output = []91 class testall:92 def __add__(self, val):93 output.append("__add__ called")94 def __radd__(self, val):95 output.append("__radd__ called")96 def __iadd__(self, val):97 output.append("__iadd__ called")98 return self99 def __sub__(self, val):100 output.append("__sub__ called")101 def __rsub__(self, val):102 output.append("__rsub__ called")103 def __isub__(self, val):104 output.append("__isub__ called")105 return self106 def __mul__(self, val):107 output.append("__mul__ called")108 def __rmul__(self, val):109 output.append("__rmul__ called")110 def __imul__(self, val):111 output.append("__imul__ called")112 return self113 def __div__(self, val):114 output.append("__div__ called")115 def __rdiv__(self, val):116 output.append("__rdiv__ called")117 def __idiv__(self, val):118 output.append("__idiv__ called")119 return self120 def __floordiv__(self, val):121 output.append("__floordiv__ called")122 return self123 def __ifloordiv__(self, val):124 output.append("__ifloordiv__ called")125 return self126 def __rfloordiv__(self, val):127 output.append("__rfloordiv__ called")128 return self129 def __truediv__(self, val):130 output.append("__truediv__ called")131 return self132 def __rtruediv__(self, val):133 output.append("__rtruediv__ called")134 return self135 def __itruediv__(self, val):136 output.append("__itruediv__ called")137 return self138 def __mod__(self, val):139 output.append("__mod__ called")140 def __rmod__(self, val):141 output.append("__rmod__ called")142 def __imod__(self, val):143 output.append("__imod__ called")144 return self145 def __pow__(self, val):146 output.append("__pow__ called")147 def __rpow__(self, val):148 output.append("__rpow__ called")149 def __ipow__(self, val):150 output.append("__ipow__ called")151 return self152 def __or__(self, val):153 output.append("__or__ called")154 def __ror__(self, val):155 output.append("__ror__ called")156 def __ior__(self, val):157 output.append("__ior__ called")158 return self159 def __and__(self, val):160 output.append("__and__ called")161 def __rand__(self, val):162 output.append("__rand__ called")163 def __iand__(self, val):164 output.append("__iand__ called")165 return self166 def __xor__(self, val):167 output.append("__xor__ called")168 def __rxor__(self, val):169 output.append("__rxor__ called")170 def __ixor__(self, val):171 output.append("__ixor__ called")172 return self173 def __rshift__(self, val):174 output.append("__rshift__ called")175 def __rrshift__(self, val):176 output.append("__rrshift__ called")177 def __irshift__(self, val):178 output.append("__irshift__ called")179 return self180 def __lshift__(self, val):181 output.append("__lshift__ called")182 def __rlshift__(self, val):183 output.append("__rlshift__ called")184 def __ilshift__(self, val):185 output.append("__ilshift__ called")186 return self187 x = testall()188 x + 1189 1 + x190 x += 1191 x - 1192 1 - x193 x -= 1194 x * 1195 1 * x196 x *= 1197 x / 1198 1 / x199 x /= 1200 x // 1201 1 // x202 x //= 1203 x % 1204 1 % x205 x %= 1206 x ** 1207 1 ** x208 x **= 1209 x | 1210 1 | x211 x |= 1212 x & 1213 1 & x214 x &= 1215 x ^ 1216 1 ^ x217 x ^= 1218 x >> 1219 1 >> x220 x >>= 1221 x << 1222 1 << x223 x <<= 1224 test_self.assertEqual(output, '''\225__add__ called226__radd__ called227__iadd__ called228__sub__ called229__rsub__ called230__isub__ called231__mul__ called232__rmul__ called233__imul__ called234__truediv__ called235__rtruediv__ called236__itruediv__ called237__floordiv__ called238__rfloordiv__ called239__ifloordiv__ called240__mod__ called241__rmod__ called242__imod__ called243__pow__ called244__rpow__ called245__ipow__ called246__or__ called247__ror__ called248__ior__ called249__and__ called250__rand__ called251__iand__ called252__xor__ called253__rxor__ called254__ixor__ called255__rshift__ called256__rrshift__ called257__irshift__ called258__lshift__ called259__rlshift__ called260__ilshift__ called261'''.splitlines())262def test_main():263 run_unittest(AugAssignTest)264if __name__ == '__main__':...
useDeepEffect.unit.test.ts
Source:useDeepEffect.unit.test.ts
1import { renderHook } from "@testing-library/react-hooks"2import useDeepEffect from "./useDeepEffect"3const tests = [4 {5 description: "number dependencies",6 expectation: "runs the callback",7 initialDeps: [1, 2],8 finalDeps: [2, 2],9 calledTimes: 1,10 finalCalledTimes: 2,11 },12 {13 description: "number dependencies",14 expectation: "does not run the callback",15 initialDeps: [1, 2],16 finalDeps: [1, 2],17 calledTimes: 1,18 finalCalledTimes: 1,19 },20 {21 description: "string dependencies",22 expectation: "runs the callback",23 initialDeps: ["foo", "bar"],24 finalDeps: ["foo", "baz"],25 calledTimes: 1,26 finalCalledTimes: 2,27 },28 {29 description: "string dependencies",30 expectation: "does not run the callback",31 initialDeps: ["foo", "bar"],32 finalDeps: ["foo", "bar"],33 calledTimes: 1,34 finalCalledTimes: 1,35 },36 {37 description: "object dependencies",38 expectation: "runs the callback",39 initialDeps: [{ foo: "bar" }],40 finalDeps: [{ foo: "baz" }],41 calledTimes: 1,42 finalCalledTimes: 2,43 },44 {45 description: "object dependencies",46 expectation: "does not run the callback",47 initialDeps: [{ foo: "bar" }],48 finalDeps: [{ foo: "bar" }],49 calledTimes: 1,50 finalCalledTimes: 1,51 },52 {53 description: "array of objects dependencies",54 expectation: "runs the callback",55 initialDeps: [[{ foo: "bar" }]],56 finalDeps: [[{ foo: "baz" }]],57 calledTimes: 1,58 finalCalledTimes: 2,59 },60 {61 description: "array of objects dependencies",62 expectation: "does not run the callback",63 initialDeps: [{ foo: "bar" }],64 finalDeps: [{ foo: "bar" }],65 calledTimes: 1,66 finalCalledTimes: 1,67 },68 {69 description: "Set dependencies",70 expectation: "runs the callback",71 initialDeps: [new Set([1, 2])],72 finalDeps: [new Set([2, 2])],73 calledTimes: 1,74 finalCalledTimes: 2,75 },76 {77 description: "Set dependencies",78 expectation: "does not run the callback",79 initialDeps: [new Set([1, 2])],80 finalDeps: [new Set([1, 2])],81 calledTimes: 1,82 finalCalledTimes: 1,83 },84 {85 description: "Map dependencies",86 expectation: "runs the callback",87 initialDeps: [new Map([[1, "one"]])],88 finalDeps: [new Map([[2, "two"]])],89 calledTimes: 1,90 finalCalledTimes: 2,91 },92 {93 description: "Map dependencies",94 expectation: "does not run the callback",95 initialDeps: [new Map([[1, "one"]])],96 finalDeps: [new Map([[1, "one"]])],97 calledTimes: 1,98 finalCalledTimes: 1,99 },100 {101 description: "undefined dependencies",102 expectation: "runs the callback",103 initialDeps: [undefined],104 finalDeps: [1],105 calledTimes: 1,106 finalCalledTimes: 2,107 },108 {109 description: "undefined dependencies",110 expectation: "does not run the callback",111 initialDeps: [undefined],112 finalDeps: [undefined],113 calledTimes: 1,114 finalCalledTimes: 1,115 },116 {117 description: "null dependencies",118 expectation: "runs the callback",119 initialDeps: [null],120 finalDeps: [1],121 calledTimes: 1,122 finalCalledTimes: 2,123 },124 {125 description: "null dependencies",126 expectation: "does not run the callback",127 initialDeps: [null],128 finalDeps: [null],129 calledTimes: 1,130 finalCalledTimes: 1,131 },132 {133 description: "NaN dependencies",134 expectation: "runs the callback",135 initialDeps: [NaN],136 finalDeps: [1],137 calledTimes: 1,138 finalCalledTimes: 2,139 },140 {141 description: "NaN dependencies",142 expectation: "does not run the callback",143 initialDeps: [NaN],144 finalDeps: [NaN],145 calledTimes: 1,146 finalCalledTimes: 1,147 },148]149describe("useDeepEffect", () => {150 tests.forEach((aTest) => {151 describe(aTest.description, () => {152 test(aTest.expectation, () => {153 const fn = jest.fn()154 let depencencies = aTest.initialDeps155 const { rerender } = renderHook(() => useDeepEffect(fn, depencencies))156 expect(fn).toHaveBeenCalledTimes(aTest.calledTimes)157 depencencies = aTest.finalDeps158 rerender()159 expect(fn).toHaveBeenCalledTimes(aTest.finalCalledTimes)160 })161 })162 })163 // Manipulation is not a best practice, and it is not supported164 describe("with manipulation", () => {165 it("does not trigger the callback", () => {166 const fn = jest.fn()167 const depencencies = [{ foo: "bar" }]168 const { rerender } = renderHook(() => useDeepEffect(fn, depencencies))169 expect(fn).toHaveBeenCalledTimes(1)170 depencencies[0].foo = "baz"171 rerender()172 expect(fn).toHaveBeenCalledTimes(1)173 })174 })175 describe("with custom comparison function", () => {176 it("does not trigger the callback", () => {177 const fn = jest.fn()178 let depencencies = [1]179 const customComparison = (a: number): boolean => a !== 1180 const { rerender } = renderHook(() =>181 useDeepEffect(fn, depencencies, customComparison)182 )183 expect(fn).toHaveBeenCalledTimes(1)184 depencencies = [2]185 rerender()186 expect(fn).toHaveBeenCalledTimes(1)187 })188 })...
timeout-bumper.test.js
Source:timeout-bumper.test.js
1// @flow2import { createTimeoutBumper } from './timeout-bumper';3jest.useFakeTimers();4const TIMEOUT1 = 1000;5const TIMEOUT2 = 2000;6const TIMEOUT3 = 3000;7const handler1 = jest.fn();8const handler2 = jest.fn();9const handler3 = jest.fn();10beforeEach(() => {11 jest.clearAllMocks();12});13test('handlers are called sequentially', () => {14 const { bumpTimeout } = createTimeoutBumper(15 {16 handler: handler1,17 timeout: TIMEOUT118 },19 {20 handler: handler2,21 timeout: TIMEOUT222 },23 {24 handler: handler3,25 timeout: TIMEOUT326 }27 );28 bumpTimeout('1337');29 expect(handler1).not.toHaveBeenCalled();30 expect(handler2).not.toHaveBeenCalled();31 expect(handler3).not.toHaveBeenCalled();32 jest.runTimersToTime(TIMEOUT1);33 expect(handler1).toHaveBeenCalledWith('1337');34 expect(handler1).toHaveBeenCalledTimes(1);35 expect(handler2).not.toHaveBeenCalled();36 expect(handler3).not.toHaveBeenCalled();37 jest.runTimersToTime(TIMEOUT2);38 expect(handler1).toHaveBeenCalledTimes(1);39 expect(handler2).toHaveBeenCalledWith('1337');40 expect(handler2).toHaveBeenCalledTimes(1);41 expect(handler3).not.toHaveBeenCalled();42 jest.runTimersToTime(TIMEOUT3);43 expect(handler1).toHaveBeenCalledTimes(1);44 expect(handler2).toHaveBeenCalledTimes(1);45 expect(handler3).toHaveBeenCalledWith('1337');46 expect(handler3).toHaveBeenCalledTimes(1);47 // From this point we want to make sure the handlers aren't called again48 jest.runTimersToTime(100000);49 expect(handler1).toHaveBeenCalledTimes(1);50 expect(handler2).toHaveBeenCalledTimes(1);51 expect(handler3).toHaveBeenCalledTimes(1);52});53test('handlers are not called while bumping', () => {54 const { bumpTimeout } = createTimeoutBumper(55 {56 handler: handler1,57 timeout: TIMEOUT158 },59 {60 handler: handler2,61 timeout: TIMEOUT262 },63 {64 handler: handler3,65 timeout: TIMEOUT366 }67 );68 bumpTimeout('1337');69 expect(handler1).not.toHaveBeenCalled();70 expect(handler2).not.toHaveBeenCalled();71 expect(handler3).not.toHaveBeenCalled();72 jest.runTimersToTime(TIMEOUT1 - 1);73 bumpTimeout('1337');74 jest.runTimersToTime(TIMEOUT1 - 1);75 expect(handler1).not.toHaveBeenCalled();76 expect(handler2).not.toHaveBeenCalled();77 expect(handler3).not.toHaveBeenCalled();78 jest.runTimersToTime(1);79 expect(handler1).toHaveBeenCalledWith('1337');80 expect(handler1).toHaveBeenCalledTimes(1);81 expect(handler2).not.toHaveBeenCalled();82 expect(handler3).not.toHaveBeenCalled();83 bumpTimeout('1337');84 jest.runTimersToTime(TIMEOUT1 - 1);85 expect(handler1).toHaveBeenCalledWith('1337');86 expect(handler1).toHaveBeenCalledTimes(1);87 expect(handler2).not.toHaveBeenCalled();88 expect(handler3).not.toHaveBeenCalled();89 jest.runTimersToTime(1);90 expect(handler1).toHaveBeenCalledWith('1337');91 expect(handler1).toHaveBeenCalledTimes(2);92 expect(handler2).not.toHaveBeenCalled();93 expect(handler3).not.toHaveBeenCalled();94 jest.runTimersToTime(TIMEOUT2 + TIMEOUT3);95 expect(handler1).toHaveBeenCalledTimes(2);96 expect(handler2).toHaveBeenCalledTimes(1);97 expect(handler3).toHaveBeenCalledTimes(1);98});99test('handlers are canceled', () => {100 const { bumpTimeout, cancelAllTimeouts } = createTimeoutBumper(101 {102 handler: handler1,103 timeout: TIMEOUT1104 },105 {106 handler: handler2,107 timeout: TIMEOUT2108 },109 {110 handler: handler3,111 timeout: TIMEOUT3112 }113 );114 bumpTimeout('1337');115 bumpTimeout('1338');116 bumpTimeout('1339');117 cancelAllTimeouts();118 jest.runTimersToTime(TIMEOUT1 + TIMEOUT2 + TIMEOUT3);119 expect(handler1).not.toHaveBeenCalled();120 expect(handler2).not.toHaveBeenCalled();121 expect(handler3).not.toHaveBeenCalled();...
Using AI Code Generation
1var wpt = require('wpt.js');2var options = {3};4wpt.runTest(options, function(err, data) {5 if (err) {6 console.log(err);7 } else {var options = {8 console.log(data);9 }10});
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt.getTest(1000, function (err, data) {3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPagetest('www.webpagetest.org', 'A.1234567890abcdefghijklmnopqrstuvwxyz');3 if (err) return console.log(err);4 console.log(data);5});6### WebPagetest(host, key, options)7Default: `{}`8### .runTest(url, options, callback)9Default: `{}`10Default: `function() {}`11### .getTestStatus(testId, callback)12Default: `function() {}`
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt.test();3module.exports.test = function() {4 console.log("test");5}6### .getTestResults(testId, callback)7Default: `function() {}`8### .getLocations(callback)9Default: `function() {}`10### .getTesters(callback)11Default: `function() {}`12### .getTestersAtLocation(location, callback)
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt.wpt(url);3exports.wpt = function(url){4 var WebPageTest = require('webpagetest');5 var wpt = new WebPageTest('www.webpagetest.org');6 wpt.runTest(url, function(err, data) {7 if (err) return console.error(err);8 console.log('Test status:', data.statusText);9 console.log('Test ID:', data.data.testId);10 console.log('Test URL:', data.data.summary);11 });12}
Using AI Code Generation
1var wpt = require('wpt');2 console.log(data);3});4 console.log(data);5 });6var wpt = require('wpt');7 console.log(data);8});9### wpt.runTest(url, [options], callback)10 * `location` - Location to test from (default: `Dulles:Chrome`)11 * `runs` - Number of test runs (default: `3`)12 * `firstViewOnly` - Only run the test once and return the first view results (default: `false`)13 * `video` - Capture a video of the test (default: `true`)14 * `pollResults` - Poll for test results (default: `true`)15 * `timeout` - Timeout for polling (default: `60`)16 * `connectivity` - Simulated connectivity profile (default: `Cable`)17 * `bwDown` - Downstream bandwidth in Kbps (default: `5000`)18 * `bwUp` - Upstream bandwidth in Kbps (default: `1000`)19 * `latency` - Latency in ms (default: `28`)20 * `plr` - Packet loss rate in % (default: `0`)21 * `mobile` - Emulate a mobile device (default: `false`)22 * `mobileDevice` - Emulated mobile device (default: `Nexus 6`)23 * `mobileCarrier` - Emulated mobile carrier (default: `Verizon`)
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!!