Best JavaScript code snippet using root
ArrayField.test.js
Source:ArrayField.test.js
...146 147 userEvent.type(inputs[0], 'Hello'); 148 userEvent.type(inputs[1], 'World'); 149 150 expect(inputs[0]).toHaveValue('Hello');151 expect(inputs[1]).toHaveValue('World');152 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Hello', 'World'] });153 154 let keys = queryAllByTestId('key');155 expect(keys.length).toBe(2);156 });157 it('should add 3 unique fields when add \'3 siblings\' is clicked', () => {158 const formApiRef = {};159 160 const { queryAllByLabelText, getByText } = render(161 <FlatArrayfield formApiRef={formApiRef}/>162 );163 164 let inputs = queryAllByLabelText('Name');165 expect(inputs.length).toBe(0);166 167 const add = getByText('Add 3 Siblings');168 fireEvent.click(add);169 170 inputs = queryAllByLabelText('Name');171 expect(inputs.length).toBe(3);172 expect(inputs[0]).toHaveAttribute('name', 'siblings[0]');173 expect(inputs[1]).toHaveAttribute('name', 'siblings[1]');174 expect(inputs[2]).toHaveAttribute('name', 'siblings[2]');175 });176 177 it('should update state when user deletes 1 index [ a, b ] ---> [ a ]', () => {178 179 const formApiRef = {};180 181 const { queryAllByLabelText, getByText, queryAllByTestId, queryAllByText } = render(182 <FlatArrayfield formApiRef={formApiRef}/>183 );184 185 let inputs = queryAllByLabelText('Name');186 expect(inputs.length).toBe(0);187 188 const add = getByText('Add Sibling');189 fireEvent.click(add);190 191 inputs = queryAllByLabelText('Name');192 expect(inputs.length).toBe(1);193 expect(inputs[0]).toHaveAttribute('name', 'siblings[0]');194 195 fireEvent.click(add);196 197 inputs = queryAllByLabelText('Name');198 expect(inputs.length).toBe(2);199 expect(inputs[0]).toHaveAttribute('name', 'siblings[0]');200 expect(inputs[1]).toHaveAttribute('name', 'siblings[1]');201 202 userEvent.type(inputs[0], 'Hello'); 203 userEvent.type(inputs[1], 'World'); 204 205 expect(inputs[0]).toHaveValue('Hello');206 expect(inputs[1]).toHaveValue('World');207 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Hello', 'World'] });208 209 let keys = queryAllByTestId('key');210 expect(keys.length).toBe(2);211 212 const removeButtons = queryAllByText('Remove');213 expect(removeButtons.length).toBe(2);214 215 fireEvent.click(removeButtons[1]);216 217 inputs = queryAllByLabelText('Name');218 expect(inputs[0]).toHaveValue('Hello');219 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Hello'] });220 221 keys = queryAllByTestId('key');222 expect(keys.length).toBe(1);223 224 });225 226 it('should initialize array field with initialValues from from', () => {227 228 const formApiRef = {};229 const initialValues = { siblings: ['Hello', 'World'] };230 231 const { queryAllByLabelText, queryAllByTestId } = render(232 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>233 );234 235 let inputs = queryAllByLabelText('Name');236 expect(inputs.length).toBe(2);237 238 expect(inputs[0]).toHaveValue('Hello');239 expect(inputs[1]).toHaveValue('World');240 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Hello', 'World'] });241 242 let keys = queryAllByTestId('key');243 expect(keys.length).toBe(2);244 });245 it('should set all fields to touched when touchAllFields is called', () => {246 247 const formApiRef = {};248 const initialValues = { siblings: ['Hello', 'World'] };249 250 const { queryAllByLabelText } = render(251 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>252 );253 254 let inputs = queryAllByLabelText('Name');255 expect(inputs.length).toBe(2);256 257 expect(inputs[0]).toHaveValue('Hello');258 expect(inputs[1]).toHaveValue('World');259 formApiRef.current.touchAllFields();260 expect(formApiRef.current.getFormState().touched).toEqual({ siblings: [ true, true ]});261 262 });263 264 it('should update state when user deletes 0 index [ a, b ] ---> [ b ]', () => {265 266 const formApiRef = {};267 const initialValues = { siblings: ['Hello', 'World'] };268 269 const { queryAllByLabelText, queryAllByTestId, queryAllByText } = render(270 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>271 );272 273 let inputs = queryAllByLabelText('Name');274 expect(inputs.length).toBe(2);275 276 let keys = queryAllByTestId('key');277 expect(keys.length).toBe(2);278 279 expect(inputs[0]).toHaveValue('Hello');280 expect(inputs[1]).toHaveValue('World');281 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Hello', 'World'] });282 283 const removeButtons = queryAllByText('Remove');284 expect(removeButtons.length).toBe(2);285 286 fireEvent.click(removeButtons[0]);287 288 inputs = queryAllByLabelText('Name');289 expect(inputs[0]).toHaveValue('World');290 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['World'] });291 292 keys = queryAllByTestId('key');293 expect(keys.length).toBe(1);294 295 });296 297 it('should update state when user deletes 2 index [ a, b, c ] ---> [ a, b ]', () => {298 299 const formApiRef = {};300 const initialValues = { siblings: ['Joe', 'Anthony', 'Bettina'] };301 302 const { queryAllByLabelText, queryAllByText } = render(303 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>304 );305 306 let inputs = queryAllByLabelText('Name');307 expect(inputs.length).toBe(3);308 309 expect(inputs[0]).toHaveValue('Joe');310 expect(inputs[1]).toHaveValue('Anthony');311 expect(inputs[2]).toHaveValue('Bettina');312 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Joe', 'Anthony', 'Bettina'] });313 314 const removeButtons = queryAllByText('Remove');315 expect(removeButtons.length).toBe(3);316 317 fireEvent.click(removeButtons[2]);318 319 inputs = queryAllByLabelText('Name');320 expect(inputs.length).toBe(2);321 expect(inputs[0]).toHaveValue('Joe');322 expect(inputs[1]).toHaveValue('Anthony');323 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Joe', 'Anthony'] });324 325 });326 327 it('should update state when user deletes 0 index [ a, b, c ] ---> [ b, c ]', () => {328 329 const formApiRef = {};330 const initialValues = { siblings: ['Joe', 'Anthony', 'Bettina'] };331 332 const { queryAllByLabelText, queryAllByText } = render(333 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>334 );335 336 let inputs = queryAllByLabelText('Name');337 expect(inputs.length).toBe(3);338 339 expect(inputs[0]).toHaveValue('Joe');340 expect(inputs[1]).toHaveValue('Anthony');341 expect(inputs[2]).toHaveValue('Bettina');342 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Joe', 'Anthony', 'Bettina'] });343 344 const removeButtons = queryAllByText('Remove');345 expect(removeButtons.length).toBe(3);346 347 fireEvent.click(removeButtons[0]);348 349 inputs = queryAllByLabelText('Name');350 expect(inputs.length).toBe(2);351 expect(inputs[0]).toHaveValue('Anthony');352 expect(inputs[1]).toHaveValue('Bettina');353 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Anthony', 'Bettina'] });354 355 });356 357 it('should update state when user deletes 1 index [ a, b, c ] ---> [ a, c ]', () => {358 359 const formApiRef = {};360 const initialValues = { siblings: ['Joe', 'Anthony', 'Bettina'] };361 362 const { queryAllByLabelText, queryAllByText } = render(363 <FlatArrayfield formApiRef={formApiRef} initialValues={initialValues}/>364 );365 366 let inputs = queryAllByLabelText('Name');367 expect(inputs.length).toBe(3);368 369 expect(inputs[0]).toHaveValue('Joe');370 expect(inputs[1]).toHaveValue('Anthony');371 expect(inputs[2]).toHaveValue('Bettina');372 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Joe', 'Anthony', 'Bettina'] });373 374 const removeButtons = queryAllByText('Remove');375 expect(removeButtons.length).toBe(3);376 377 fireEvent.click(removeButtons[1]);378 379 inputs = queryAllByLabelText('Name');380 expect(inputs.length).toBe(2);381 expect(inputs[0]).toHaveValue('Joe');382 expect(inputs[1]).toHaveValue('Bettina');383 expect(formApiRef.current.getFormState().values).toEqual({ siblings: ['Joe', 'Bettina'] });384 385 });386 });387 /* ------------------------------------ Object Array Field ------------------------------------ */388 describe('Object Array Field', () => {389 it('should add unique fields when add is clicked', () => {390 const formApiRef = {};391 392 const { queryAllByLabelText, getByText, queryAllByTestId } = render(393 <ObjectArrayfield formApiRef={formApiRef}/>394 );395 396 let inputs = queryAllByLabelText('Name');397 expect(inputs.length).toBe(0);398 399 const add = getByText('Add Sibling');400 fireEvent.click(add);401 402 let first = queryAllByLabelText('First');403 let last = queryAllByLabelText('Last');404 expect(first.length).toBe(1);405 expect(last.length).toBe(1);406 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');407 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');408 409 fireEvent.click(add);410 411 first = queryAllByLabelText('First');412 last = queryAllByLabelText('Last');413 expect(first.length).toBe(2);414 expect(last.length).toBe(2);415 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');416 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');417 418 userEvent.type(first[0], 'Hello'); 419 userEvent.type(last[0], 'World'); 420 userEvent.type(first[1], 'Foo'); 421 userEvent.type(last[1], 'Bar'); 422 423 expect(first[0]).toHaveValue('Hello');424 expect(last[0]).toHaveValue('World');425 expect(first[1]).toHaveValue('Foo');426 expect(last[1]).toHaveValue('Bar');427 expect(formApiRef.current.getFormState().values).toEqual({ siblings: [{428 first: 'Hello', 429 last: 'World'430 }, {431 first: 'Foo', 432 last: 'Bar'433 }] });434 435 let keys = queryAllByTestId('key');436 expect(keys.length).toBe(2);437 });438 439 it('should update state when user deletes 1 index [ a, b ] ---> [ a ]', () => {440 441 const formApiRef = {};442 443 const { queryAllByLabelText, getByText, queryAllByTestId, queryAllByText } = render(444 <ObjectArrayfield formApiRef={formApiRef}/>445 );446 447 let inputs = queryAllByLabelText('Name');448 expect(inputs.length).toBe(0);449 450 const add = getByText('Add Sibling');451 fireEvent.click(add);452 453 let first = queryAllByLabelText('First');454 let last = queryAllByLabelText('Last');455 expect(first.length).toBe(1);456 expect(last.length).toBe(1);457 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');458 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');459 460 fireEvent.click(add);461 462 first = queryAllByLabelText('First');463 last = queryAllByLabelText('Last');464 expect(first.length).toBe(2);465 expect(last.length).toBe(2);466 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');467 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');468 469 userEvent.type(first[0], 'Hello'); 470 userEvent.type(last[0], 'World'); 471 userEvent.type(first[1], 'Foo'); 472 userEvent.type(last[1], 'Bar'); 473 474 expect(first[0]).toHaveValue('Hello');475 expect(last[0]).toHaveValue('World');476 expect(first[1]).toHaveValue('Foo');477 expect(last[1]).toHaveValue('Bar');478 expect(formApiRef.current.getFormState().values).toEqual({ siblings: [{479 first: 'Hello', 480 last: 'World'481 }, {482 first: 'Foo', 483 last: 'Bar'484 }] });485 486 let keys = queryAllByTestId('key');487 expect(keys.length).toBe(2);488 489 const removeButtons = queryAllByText('Remove');490 expect(removeButtons.length).toBe(2);491 492 fireEvent.click(removeButtons[1]);493 494 first = queryAllByLabelText('First');495 last = queryAllByLabelText('Last');496 expect(first.length).toBe(1);497 expect(last.length).toBe(1);498 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');499 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');500 501 expect(first[0]).toHaveValue('Hello');502 expect(last[0]).toHaveValue('World');503 expect(formApiRef.current.getFormState().values).toEqual({ siblings: [{504 first: 'Hello', 505 last: 'World'506 }] });507 508 keys = queryAllByTestId('key');509 expect(keys.length).toBe(1);510 511 });512 513 it('should initialize array field with initialValues from from', () => {514 515 const formApiRef = {};516 const initialValues = { 517 siblings: [518 {519 first: 'Hello', 520 last: 'World'521 }, {522 first: 'Foo', 523 last: 'Bar'524 }525 ]526 };527 528 const { queryAllByLabelText, queryAllByTestId } = render(529 <ObjectArrayfield formApiRef={formApiRef} initialValues={initialValues}/>530 );531 let first = queryAllByLabelText('First');532 let last = queryAllByLabelText('Last');533 expect(first.length).toBe(2);534 expect(last.length).toBe(2);535 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');536 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');537 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');538 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');539 540 expect(first[0]).toHaveValue('Hello');541 expect(last[0]).toHaveValue('World');542 expect(first[1]).toHaveValue('Foo');543 expect(last[1]).toHaveValue('Bar');544 expect(formApiRef.current.getFormState().values).toEqual({ siblings: [{545 first: 'Hello', 546 last: 'World'547 }, {548 first: 'Foo', 549 last: 'Bar'550 }] });551 552 let keys = queryAllByTestId('key');553 expect(keys.length).toBe(2);554 });555 556 it('should update state when user deletes 0 index [ a, b ] ---> [ b ]', () => {557 558 const formApiRef = {};559 const initialValues = { 560 siblings: [561 {562 first: 'Hello', 563 last: 'World'564 }, {565 first: 'Foo', 566 last: 'Bar'567 }568 ]569 }; 570 const { queryAllByLabelText, queryAllByText } = render(571 <ObjectArrayfield formApiRef={formApiRef} initialValues={initialValues}/>572 );573 574 const removeButtons = queryAllByText('Remove');575 expect(removeButtons.length).toBe(2);576 577 fireEvent.click(removeButtons[0]);578 579 const first = queryAllByLabelText('First');580 const last = queryAllByLabelText('Last');581 expect(first.length).toBe(1);582 expect(last.length).toBe(1);583 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');584 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');585 586 expect(first[0]).toHaveValue('Foo');587 expect(last[0]).toHaveValue('Bar');588 expect(formApiRef.current.getFormState().values).toEqual({ siblings: [{589 first: 'Foo', 590 last: 'Bar'591 }] });592 593 });594 595 it('should update state when user deletes 2 index [ a, b, c ] ---> [ a, b ]', () => {596 597 const formApiRef = {}; 598 const initialValues = { 599 siblings: [600 {601 first: 'Hello', 602 last: 'World'603 }, {604 first: 'Foo', 605 last: 'Bar'606 }, {607 first: 'Baz', 608 last: 'Taz'609 },610 ]611 }; 612 613 const { queryAllByLabelText, queryAllByText } = render(614 <ObjectArrayfield formApiRef={formApiRef} initialValues={initialValues}/>615 );616 617 const removeButtons = queryAllByText('Remove');618 expect(removeButtons.length).toBe(3);619 620 fireEvent.click(removeButtons[2]);621 622 const first = queryAllByLabelText('First');623 const last = queryAllByLabelText('Last');624 expect(first.length).toBe(2);625 expect(last.length).toBe(2);626 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');627 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');628 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');629 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');630 631 expect(first[0]).toHaveValue('Hello');632 expect(last[0]).toHaveValue('World');633 expect(first[1]).toHaveValue('Foo');634 expect(last[1]).toHaveValue('Bar');635 expect(formApiRef.current.getFormState().values).toEqual({ 636 siblings: [637 {638 first: 'Hello', 639 last: 'World'640 }, {641 first: 'Foo', 642 last: 'Bar'643 }644 ]645 });646 647 });648 649 it('should update state when user deletes 0 index [ a, b, c ] ---> [ b, c ]', () => {650 651 const formApiRef = {}; 652 const initialValues = { 653 siblings: [654 {655 first: 'Hello', 656 last: 'World'657 }, {658 first: 'Foo', 659 last: 'Bar'660 }, {661 first: 'Baz', 662 last: 'Taz'663 },664 ]665 }; 666 667 const { queryAllByLabelText, queryAllByText } = render(668 <ObjectArrayfield formApiRef={formApiRef} initialValues={initialValues}/>669 );670 671 const removeButtons = queryAllByText('Remove');672 expect(removeButtons.length).toBe(3);673 674 fireEvent.click(removeButtons[0]);675 676 const first = queryAllByLabelText('First');677 const last = queryAllByLabelText('Last');678 expect(first.length).toBe(2);679 expect(last.length).toBe(2);680 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');681 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');682 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');683 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');684 685 expect(first[0]).toHaveValue('Foo');686 expect(last[0]).toHaveValue('Bar');687 expect(first[1]).toHaveValue('Baz');688 expect(last[1]).toHaveValue('Taz');689 expect(formApiRef.current.getFormState().values).toEqual({ 690 siblings: [691 {692 first: 'Foo', 693 last: 'Bar'694 }, {695 first: 'Baz', 696 last: 'Taz'697 }698 ]699 });700 701 });702 703 it('should update state when user deletes 1 index [ a, b, c ] ---> [ a, c ]', () => {704 705 const formApiRef = {}; 706 const initialValues = { 707 siblings: [708 {709 first: 'Hello', 710 last: 'World'711 }, {712 first: 'Foo', 713 last: 'Bar'714 }, {715 first: 'Baz', 716 last: 'Taz'717 },718 ]719 }; 720 721 const { queryAllByLabelText, queryAllByText } = render(722 <ObjectArrayfield formApiRef={formApiRef} initialValues={initialValues}/>723 );724 725 const removeButtons = queryAllByText('Remove');726 expect(removeButtons.length).toBe(3);727 728 fireEvent.click(removeButtons[1]);729 730 const first = queryAllByLabelText('First');731 const last = queryAllByLabelText('Last');732 expect(first.length).toBe(2);733 expect(last.length).toBe(2);734 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');735 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');736 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');737 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');738 739 expect(first[0]).toHaveValue('Hello');740 expect(last[0]).toHaveValue('World');741 expect(first[1]).toHaveValue('Baz');742 expect(last[1]).toHaveValue('Taz');743 expect(formApiRef.current.getFormState().values).toEqual({ 744 siblings: [745 {746 first: 'Hello', 747 last: 'World'748 }, {749 first: 'Baz', 750 last: 'Taz'751 }752 ]753 });754 755 });756 });757 /* ------------------------------------ Relevant Array Field ------------------------------------ */758 describe('Relevant Array Field', () => {759 760 it('should initialize array field with initialValues from from', () => {761 762 const formApiRef = {};763 const initialValues = { 764 siblings: [765 {766 first: 'Hello', 767 last: 'World'768 }, {769 first: 'Foo', 770 last: 'Bar'771 }, {772 first: 'Baz', 773 last: 'Taz'774 }775 ]776 };777 778 const { queryAllByLabelText } = render(779 <RelevantArrayfield formApiRef={formApiRef} initialValues={initialValues}/>780 );781 let first = queryAllByLabelText('First');782 let last = queryAllByLabelText('Last');783 let foo = queryAllByLabelText('Foo');784 let show = queryAllByLabelText('Show Info?');785 786 expect(first.length).toBe(3);787 expect(last.length).toBe(3);788 expect(foo.length).toBe(3);789 expect(show.length).toBe(3);790 expect(first[0]).toHaveAttribute('name', 'siblings[0].first');791 expect(last[0]).toHaveAttribute('name', 'siblings[0].last');792 expect(foo[0]).toHaveAttribute('name', 'siblings[0].foo');793 expect(show[0]).toHaveAttribute('name', 'siblings[0].showInfo');794 expect(first[1]).toHaveAttribute('name', 'siblings[1].first');795 expect(last[1]).toHaveAttribute('name', 'siblings[1].last');796 expect(foo[1]).toHaveAttribute('name', 'siblings[1].foo');797 expect(show[1]).toHaveAttribute('name', 'siblings[1].showInfo');798 expect(first[2]).toHaveAttribute('name', 'siblings[2].first');799 expect(last[2]).toHaveAttribute('name', 'siblings[2].last');800 expect(foo[2]).toHaveAttribute('name', 'siblings[2].foo');801 expect(show[2]).toHaveAttribute('name', 'siblings[2].showInfo');802 803 expect(first[0]).toHaveValue('Hello');804 expect(last[0]).toHaveValue('World');805 expect(foo[0]).toHaveValue('foo-siblings[0]');806 expect(first[1]).toHaveValue('Foo');807 expect(last[1]).toHaveValue('Bar');808 expect(foo[1]).toHaveValue('foo-siblings[1]');809 expect(first[2]).toHaveValue('Baz');810 expect(last[2]).toHaveValue('Taz');811 expect(foo[2]).toHaveValue('foo-siblings[2]');812 expect(formApiRef.current.getFormState().values).toEqual({ 813 siblings: [814 {815 first: 'Hello', 816 last: 'World',817 foo: 'foo-siblings[0]'818 }, {819 first: 'Foo', 820 last: 'Bar',821 foo: 'foo-siblings[1]'822 }, {823 first: 'Baz', 824 last: 'Taz',825 foo: 'foo-siblings[2]'826 }827 ]828 });829 830 });831 const fillOneAndTwo = () => {832 const formApiRef = {};833 const initialValues = { 834 siblings: [835 {836 first: 'Hello', 837 last: 'World'838 }, {839 first: 'Foo', 840 last: 'Bar'841 }, {842 first: 'Baz', 843 last: 'Taz'844 }845 ]846 };847 848 const { queryAllByLabelText, queryAllByText, getByText } = render(849 <RelevantArrayfield formApiRef={formApiRef} initialValues={initialValues}/>850 );851 let show = queryAllByLabelText('Show Info?');852 let removeButtons = queryAllByText('Remove');853 expect(removeButtons.length).toBe(3);854 // Show middle guys info855 fireEvent.click(show[1]);856 let age = queryAllByLabelText('Age');857 let color = queryAllByLabelText('Favorite Color');858 let food = queryAllByLabelText('Favorite Food');859 expect(age.length).toBe(1);860 expect(color.length).toBe(1);861 expect(food.length).toBe(1);862 userEvent.type(age[0], '27');863 userEvent.type(color[0], 'Green');864 userEvent.type(food[0], 'Apples');865 expect(age[0]).toHaveAttribute('name', 'siblings[1].age');866 expect(color[0]).toHaveAttribute('name', 'siblings[1].color');867 expect(food[0]).toHaveAttribute('name', 'siblings[1].food');868 expect(age[0]).toHaveValue(27);869 expect(color[0]).toHaveValue('Green');870 expect(food[0]).toHaveValue('Apples');871 expect(formApiRef.current.getFormState().values).toEqual({ 872 siblings: [873 {874 first: 'Hello', 875 last: 'World',876 foo: 'foo-siblings[0]'877 }, {878 first: 'Foo', 879 last: 'Bar',880 foo: 'foo-siblings[1]',881 showInfo: true,882 age: 27,883 color: 'Green', 884 food: 'Apples'885 }, {886 first: 'Baz', 887 last: 'Taz',888 foo: 'foo-siblings[2]'889 }890 ]891 });892 fireEvent.click(show[2]);893 age = queryAllByLabelText('Age');894 color = queryAllByLabelText('Favorite Color');895 food = queryAllByLabelText('Favorite Food');896 expect(age.length).toBe(2);897 expect(color.length).toBe(2);898 expect(food.length).toBe(2);899 userEvent.type(age[1], '20');900 userEvent.type(color[1], 'Blue');901 userEvent.type(food[1], 'Berries');902 expect(age[1]).toHaveAttribute('name', 'siblings[2].age');903 expect(color[1]).toHaveAttribute('name', 'siblings[2].color');904 expect(food[1]).toHaveAttribute('name', 'siblings[2].food');905 expect(age[1]).toHaveValue(20);906 expect(color[1]).toHaveValue('Blue');907 expect(food[1]).toHaveValue('Berries');908 expect(formApiRef.current.getFormState().values).toEqual({ 909 siblings: [910 {911 first: 'Hello', 912 last: 'World',913 foo: 'foo-siblings[0]'914 }, {915 first: 'Foo', 916 last: 'Bar',917 foo: 'foo-siblings[1]',918 showInfo: true,919 age: 27,920 color: 'Green', 921 food: 'Apples'922 }, {923 first: 'Baz', 924 last: 'Taz',925 foo: 'foo-siblings[2]',926 showInfo: true,927 age: 20,928 color: 'Blue', 929 food: 'Berries'930 }931 ]932 });933 return { formApiRef, queryAllByLabelText, queryAllByText, getByText };934 };935 it('should update correctly when hiding and showing', () => {936 const { formApiRef, queryAllByLabelText } = fillOneAndTwo();937 let show = queryAllByLabelText('Show Info?');938 // Hide the middle guys info939 fireEvent.click(show[1]);940 let age = queryAllByLabelText('Age');941 let color = queryAllByLabelText('Favorite Color');942 let food = queryAllByLabelText('Favorite Food');943 expect(age.length).toBe(1);944 expect(color.length).toBe(1);945 expect(food.length).toBe(1);946 expect(age[0]).toHaveAttribute('name', 'siblings[2].age');947 expect(color[0]).toHaveAttribute('name', 'siblings[2].color');948 expect(food[0]).toHaveAttribute('name', 'siblings[2].food');949 expect(age[0]).toHaveValue(20);950 expect(color[0]).toHaveValue('Blue');951 expect(food[0]).toHaveValue('Berries');952 expect(formApiRef.current.getFormState().values).toEqual({ 953 siblings: [954 {955 first: 'Hello', 956 last: 'World',957 foo: 'foo-siblings[0]'958 }, {959 first: 'Foo', 960 last: 'Bar',961 foo: 'foo-siblings[1]',962 showInfo: false,963 color: 'Green',964 }, {965 first: 'Baz', 966 last: 'Taz',967 foo: 'foo-siblings[2]',968 showInfo: true,969 age: 20,970 color: 'Blue', 971 food: 'Berries'972 }973 ]974 });975 // Hide the last guys info976 fireEvent.click(show[2]);977 age = queryAllByLabelText('Age');978 color = queryAllByLabelText('Favorite Color');979 food = queryAllByLabelText('Favorite Food');980 expect(age.length).toBe(0);981 expect(color.length).toBe(0);982 expect(food.length).toBe(0);983 expect(formApiRef.current.getFormState().values).toEqual({ 984 siblings: [985 {986 first: 'Hello', 987 last: 'World',988 foo: 'foo-siblings[0]'989 }, {990 first: 'Foo', 991 last: 'Bar',992 foo: 'foo-siblings[1]',993 showInfo: false,994 color: 'Green',995 }, {996 first: 'Baz', 997 last: 'Taz',998 foo: 'foo-siblings[2]',999 showInfo: false,1000 color: 'Blue', 1001 }1002 ]1003 });1004 // Show the middle guys info1005 fireEvent.click(show[1]);1006 age = queryAllByLabelText('Age');1007 color = queryAllByLabelText('Favorite Color');1008 food = queryAllByLabelText('Favorite Food');1009 expect(age.length).toBe(1);1010 expect(color.length).toBe(1);1011 expect(food.length).toBe(1);1012 expect(age[0]).toHaveAttribute('name', 'siblings[1].age');1013 expect(color[0]).toHaveAttribute('name', 'siblings[1].color');1014 expect(food[0]).toHaveAttribute('name', 'siblings[1].food');1015 expect(age[0]).not.toHaveValue(27);1016 expect(color[0]).toHaveValue('Green');1017 expect(food[0]).not.toHaveValue('Apples');1018 expect(formApiRef.current.getFormState().values).toEqual({ 1019 siblings: [1020 {1021 first: 'Hello', 1022 last: 'World',1023 foo: 'foo-siblings[0]'1024 }, {1025 first: 'Foo', 1026 last: 'Bar',1027 foo: 'foo-siblings[1]',1028 showInfo: true,1029 color: 'Green',1030 }, {1031 first: 'Baz', 1032 last: 'Taz',1033 foo: 'foo-siblings[2]',1034 showInfo: false,1035 color: 'Blue', 1036 }1037 ]1038 });1039 });1040 it('should update correctly when removing last index', () => {1041 const { formApiRef, queryAllByLabelText, queryAllByText, getByText } = fillOneAndTwo();1042 let removeButtons = queryAllByText('Remove');1043 expect(removeButtons.length).toBe(3);1044 fireEvent.click(removeButtons[2]);1045 let age = queryAllByLabelText('Age');1046 let color = queryAllByLabelText('Favorite Color');1047 let food = queryAllByLabelText('Favorite Food');1048 expect(age.length).toBe(1);1049 expect(color.length).toBe(1);1050 expect(food.length).toBe(1);1051 expect(age[0]).toHaveAttribute('name', 'siblings[1].age');1052 expect(color[0]).toHaveAttribute('name', 'siblings[1].color');1053 expect(food[0]).toHaveAttribute('name', 'siblings[1].food');1054 expect(age[0]).toHaveValue(27);1055 expect(color[0]).toHaveValue('Green');1056 expect(food[0]).toHaveValue('Apples');1057 expect(formApiRef.current.getFormState().values).toEqual({ 1058 siblings: [1059 {1060 first: 'Hello', 1061 last: 'World',1062 foo: 'foo-siblings[0]'1063 }, {1064 first: 'Foo', 1065 last: 'Bar',1066 foo: 'foo-siblings[1]',1067 showInfo: true,1068 age: 27,1069 color: 'Green', 1070 food: 'Apples'1071 }1072 ]1073 });1074 // Now add it back 1075 const add = getByText('Add Sibling');1076 fireEvent.click(add);1077 age = queryAllByLabelText('Age');1078 color = queryAllByLabelText('Favorite Color');1079 food = queryAllByLabelText('Favorite Food');1080 expect(age.length).toBe(1);1081 expect(color.length).toBe(1);1082 expect(food.length).toBe(1);1083 expect(formApiRef.current.getFormState().values).toEqual({ 1084 siblings: [1085 {1086 first: 'Hello', 1087 last: 'World',1088 foo: 'foo-siblings[0]'1089 }, {1090 first: 'Foo', 1091 last: 'Bar',1092 foo: 'foo-siblings[1]',1093 showInfo: true,1094 age: 27,1095 color: 'Green', 1096 food: 'Apples'1097 },{1098 // NOTE HOW INITIAL VALUES ARE NOT HERE ( This is a good thing! )1099 foo: 'foo-siblings[2]',1100 }1101 ]1102 });1103 });1104 it('should update correctly when removing middle index', () => {1105 const { formApiRef, queryAllByLabelText, queryAllByText, getByText } = fillOneAndTwo();1106 let removeButtons = queryAllByText('Remove');1107 expect(removeButtons.length).toBe(3);1108 1109 fireEvent.click(removeButtons[1]);1110 let age = queryAllByLabelText('Age');1111 let color = queryAllByLabelText('Favorite Color');1112 let food = queryAllByLabelText('Favorite Food');1113 expect(age.length).toBe(1);1114 expect(color.length).toBe(1);1115 expect(food.length).toBe(1);1116 expect(age[0]).toHaveAttribute('name', 'siblings[1].age');1117 expect(color[0]).toHaveAttribute('name', 'siblings[1].color');1118 expect(food[0]).toHaveAttribute('name', 'siblings[1].food');1119 expect(age[0]).toHaveValue(20);1120 expect(color[0]).toHaveValue('Blue');1121 expect(food[0]).toHaveValue('Berries');1122 expect(formApiRef.current.getFormState().values).toEqual({ 1123 siblings: [1124 {1125 first: 'Hello', 1126 last: 'World',1127 foo: 'foo-siblings[0]'1128 }, {1129 first: 'Baz', 1130 last: 'Taz',1131 foo: 'foo-siblings[2]', // << Important to note it has initial value from when it was 3rd element1132 showInfo: true,1133 age: 20,1134 color: 'Blue', 1135 food: 'Berries'1136 }1137 ]1138 });1139 // Now add it back 1140 const add = getByText('Add Sibling');1141 fireEvent.click(add);1142 age = queryAllByLabelText('Age');1143 color = queryAllByLabelText('Favorite Color');1144 food = queryAllByLabelText('Favorite Food');1145 expect(age.length).toBe(1);1146 expect(color.length).toBe(1);1147 expect(food.length).toBe(1);1148 expect(formApiRef.current.getFormState().values).toEqual({ 1149 siblings: [1150 {1151 first: 'Hello', 1152 last: 'World',1153 foo: 'foo-siblings[0]'1154 }, {1155 first: 'Baz', 1156 last: 'Taz',1157 foo: 'foo-siblings[2]', // << Important to note it has initial value from when it was 3rd element1158 showInfo: true,1159 age: 20,1160 color: 'Blue', 1161 food: 'Berries'1162 }, {1163 // NOTE HOW INITIAL VALUES ARE NOT HERE ( This is a good thing! )1164 foo: 'foo-siblings[2]',1165 }1166 ]1167 });1168 });1169 it('should update correctly when removing first index', () => {1170 const { formApiRef, queryAllByLabelText, queryAllByText, getByText } = fillOneAndTwo();1171 let removeButtons = queryAllByText('Remove');1172 expect(removeButtons.length).toBe(3);1173 fireEvent.click(removeButtons[0]);1174 let age = queryAllByLabelText('Age');1175 let color = queryAllByLabelText('Favorite Color');1176 let food = queryAllByLabelText('Favorite Food');1177 expect(age.length).toBe(2);1178 expect(color.length).toBe(2);1179 expect(food.length).toBe(2);1180 expect(age[0]).toHaveAttribute('name', 'siblings[0].age');1181 expect(color[0]).toHaveAttribute('name', 'siblings[0].color');1182 expect(food[0]).toHaveAttribute('name', 'siblings[0].food');1183 expect(age[1]).toHaveAttribute('name', 'siblings[1].age');1184 expect(color[1]).toHaveAttribute('name', 'siblings[1].color');1185 expect(food[1]).toHaveAttribute('name', 'siblings[1].food');1186 expect(age[0]).toHaveValue(27);1187 expect(color[0]).toHaveValue('Green');1188 expect(food[0]).toHaveValue('Apples');1189 expect(age[1]).toHaveValue(20);1190 expect(color[1]).toHaveValue('Blue');1191 expect(food[1]).toHaveValue('Berries');1192 expect(formApiRef.current.getFormState().values).toEqual({ 1193 siblings: [1194 {1195 first: 'Foo', 1196 last: 'Bar',1197 foo: 'foo-siblings[1]', // << Important to note it has initial value from when it was 2nd element1198 showInfo: true,1199 age: 27,1200 color: 'Green', 1201 food: 'Apples'1202 }, {1203 first: 'Baz', 1204 last: 'Taz',1205 foo: 'foo-siblings[2]', // << Important to note it has initial value from when it was 3rd element...
AddMovie.test.js
Source:AddMovie.test.js
...66 expect(titleInputLabel).toBeInTheDocument();67 expect(titleInputLabel).toHaveTextContent('TÃtulo');68 });69 it('Defina o estado inicial do titulo como "", ou seja, uma string vazia', () => {70 expect(titleInput).toHaveValue(initialState.title);71 });72 it('Altere o valor do input de tÃtulo quando algo for digitado nele', () => {73 event.type(titleInput, 'my awesome movie title');74 expect(titleInput).toHaveValue('my awesome movie title');75 });76});77describe('9 - Renderize um input do tipo texto dentro do formulário em `<AddMovie />` para obter o subtÃtulo do novo filme', () => {78 it('Renderize um input de texto para quem usa escrever o subtÃtulo do filme', () => {79 expect(subtitleInput).toBeInTheDocument();80 });81 it('Renderize a label "SubtÃtulo" para o input de subtitulo', () => {82 expect(subtitleInputLabel).toBeInTheDocument();83 expect(subtitleInputLabel).toHaveTextContent('SubtÃtulo');84 });85 it('Defina o estado inicial do subtitulo como "", ou seja, uma string vazia', () => {86 expect(subtitleInput).toHaveValue(initialState.subtitle);87 });88 it('Altere o valor do input de subtitulo quando algo é digitado nele', () => {89 event.type(subtitleInput, 'my awesome movie subtitle');90 expect(subtitleInput).toHaveValue('my awesome movie subtitle');91 });92});93describe('10 - Renderize um input do tipo texto dentro do formulário em `<AddMovie />` para obter o caminho da imagem do novo filme', () => {94 it('Renderize um input de texto para quem usa inserir a url da imagem do filme', () => {95 expect(imageInput).toBeInTheDocument();96 });97 it('Renderize a label "Imagem" para o input de imagem', () => {98 expect(imageInputLabel).toBeInTheDocument();99 expect(imageInputLabel).toHaveTextContent('Imagem');100 });101 it('Defina o estado inicial do input de imagem como "", ou seja, uma string vazia', () => {102 expect(imageInput).toHaveValue(initialState.imagePath);103 });104 it('Altere o valor do input de imagem quando algo é digitado nele', () => {105 event.type(imageInput, 'http://localhost:3000/images/Appleseed_Alpha.jpg');106 expect(imageInput).toHaveValue('http://localhost:3000/images/Appleseed_Alpha.jpg');107 });108});109describe('11 - Renderize uma `textarea` dentro do formulário em `<AddMovie />` para obter a sinopse do novo filme', () => {110 it('Renderize um input de texto para quem usa escrever a sinopse do filme', () => {111 expect(storylineInput).toBeInTheDocument();112 });113 it('Renderize a label "Sinopse" para o input de sinopse', () => {114 expect(storylineInputLabel).toBeInTheDocument();115 expect(storylineInputLabel).toHaveTextContent('Sinopse');116 });117 it('Defina o estado inicial do input de sinopse como "", ou seja, uma string vazia', () => {118 expect(storylineInput).toHaveValue(initialState.storyline);119 });120 it('Altere o valor do input de sinopse quando algo é digitado nele', () => {121 const message = 'In the following movie, everyone dies.';122 fireEvent.change(storylineInput, { target: { value: message } });123 expect(storylineInput).toHaveValue(message);124 });125});126describe('12 - Renderize um `input` do tipo `number` dentro do formulário em `<AddMovie />` para obter a avaliação do novo filme', () => {127 it('Renderize um input de texto para quem usa escrever a avaliação do filme', () => {128 expect(ratingInput).toBeInTheDocument();129 });130 it('Renderize a label "Avaliação" para o input de avaliação', () => {131 expect(ratingInputLabel).toBeInTheDocument();132 expect(ratingInputLabel).toHaveTextContent('Avaliação');133 });134 it('Defina o estado inicial do input de avaliação é 0', () => {135 expect(ratingInput).toHaveValue(initialState.rating);136 });137 it('Altere o valor do input de avaliação quando algo é digitado nele', () => {138 const expectedValue = 1.5;139 event.type(ratingInput, '1.5');140 expect(ratingInput).toHaveValue(expectedValue);141 });142});143describe('13 - Renderize um `select` do formulário em `<AddMovie />` para selecionar o gênero do novo filme', () => {144 const options = [145 { value: 'action', text: 'Ação' },146 { value: 'comedy', text: 'Comédia' },147 { value: 'thriller', text: 'Suspense' },148 ];149 it('Renderize um select com 3 opções de genero de filme', () => {150 expect(genreInput).toBeInTheDocument();151 expect(genreOptions).toHaveLength(options.length);152 });153 it('Será validado se o component renderiza a label "Gênero" para o select de gênero', () => {154 expect(genreInputLabel).toBeInTheDocument();155 expect(genreInputLabel).toHaveTextContent('Gênero');156 });157 it('Será validado se todas as opções no select tem o texto e o valor esperados, que são, respectivamente: Ação e action, Comédia e comedy, Suspense e thriller', () => {158 genreOptions.forEach((option, index) => {159 expect(option).toHaveTextContent(options[index].text);160 expect(option).toHaveValue(options[index].value);161 });162 });163 it('Será validado se o gênero selecionado inicialmente é o "action"', () => {164 expect(genreInput).toHaveValue(initialState.genre);165 });166 it('Altere o valor do gênero quando um gênero diferente é escolhido no select', () => {167 event.selectOptions(genreInput, options[1].value);168 expect(genreInput).toHaveValue(genreOptions[1].value);169 });170});171describe('14 - Renderize um botão do formulário em `<AddMovie />` para fazer uso dos dados do novo filme, contidos no estado de `<AddMovie />`', () => {172 it('Será validado se o texto do botão é "Adicionar filme"', () => {173 expect(sendButton).toHaveTextContent('Adicionar filme');174 });175 it('Será validado se o evento onClick é chamado ao se clicar no botão.', () => {176 event.type(titleInput, movieHarryPotter);177 event.type(subtitleInput, subtitleMagical);178 fireEvent.change(storylineInput, { target: { value: `${inputStoryline}` } });179 event.type(storylineInput, inputStoryline);180 event.type(ratingInput, '3.5');181 event.click(sendButton);182 expect(onClick).toHaveBeenCalled();183 });184 it('Será validado se o estado dos inputs volta ao inicial depois que o botão de adicionar é clicado.', () => {185 const expectedRating = 3.5;186 event.type(titleInput, movieHarryPotter);187 event.type(subtitleInput, subtitleMagical);188 fireEvent.change(storylineInput, { target: { value: `${inputStoryline}` } });189 event.type(ratingInput, '3.5');190 event.selectOptions(genreInput, 'comedy');191 expect(titleInput).toHaveValue(movieHarryPotter);192 expect(subtitleInput).toHaveValue(subtitleMagical);193 expect(storylineInput).toHaveValue(inputStoryline);194 expect(ratingInput).toHaveValue(expectedRating);195 expect(genreInput).toHaveValue('comedy');196 event.click(sendButton);197 expect(titleInput).toHaveValue('');198 expect(subtitleInput).toHaveValue('');199 expect(storylineInput).toHaveValue('');200 expect(ratingInput).toHaveValue(0);201 expect(genreInput).toHaveValue('action');202 });...
to-have-value.js
Source:to-have-value.js
...5 <input type="text" value="foo" data-testid="value" />6 <input type="text" value="" data-testid="empty" />7 <input type="text" data-testid="without" />8 `)9 expect(queryByTestId('value')).toHaveValue('foo')10 expect(queryByTestId('value')).toHaveValue()11 expect(queryByTestId('value')).not.toHaveValue('bar')12 expect(queryByTestId('value')).not.toHaveValue('')13 expect(queryByTestId('empty')).toHaveValue('')14 expect(queryByTestId('empty')).not.toHaveValue()15 expect(queryByTestId('empty')).not.toHaveValue('foo')16 expect(queryByTestId('without')).toHaveValue('')17 expect(queryByTestId('without')).not.toHaveValue()18 expect(queryByTestId('without')).not.toHaveValue('foo')19 queryByTestId('without').value = 'bar'20 expect(queryByTestId('without')).toHaveValue('bar')21 })22 test('handles value of number input', () => {23 const {queryByTestId} = render(`24 <input type="number" value="5" data-testid="number" />25 <input type="number" value="" data-testid="empty" />26 <input type="number" data-testid="without" />27 `)28 expect(queryByTestId('number')).toHaveValue(5)29 expect(queryByTestId('number')).toHaveValue()30 expect(queryByTestId('number')).not.toHaveValue(4)31 expect(queryByTestId('number')).not.toHaveValue('5')32 expect(queryByTestId('empty')).toHaveValue(null)33 expect(queryByTestId('empty')).not.toHaveValue()34 expect(queryByTestId('empty')).not.toHaveValue('5')35 expect(queryByTestId('without')).toHaveValue(null)36 expect(queryByTestId('without')).not.toHaveValue()37 expect(queryByTestId('without')).not.toHaveValue('10')38 queryByTestId('without').value = 1039 expect(queryByTestId('without')).toHaveValue(10)40 })41 test('handles value of select element', () => {42 const {queryByTestId} = render(`43 <select data-testid="single">44 <option value="first">First Value</option> 45 <option value="second" selected>Second Value</option>46 <option value="third">Third Value</option>47 </select>48 49 <select data-testid="multiple" multiple>50 <option value="first">First Value</option> 51 <option value="second" selected>Second Value</option>52 <option value="third" selected>Third Value</option>53 </select>54 55 <select data-testid="not-selected" >56 <option value="" disabled selected>- Select some value - </option>57 <option value="first">First Value</option> 58 <option value="second">Second Value</option>59 <option value="third">Third Value</option>60 </select>61 `)62 expect(queryByTestId('single')).toHaveValue('second')63 expect(queryByTestId('single')).toHaveValue()64 expect(queryByTestId('multiple')).toHaveValue(['second', 'third'])65 expect(queryByTestId('multiple')).toHaveValue()66 expect(queryByTestId('not-selected')).not.toHaveValue()67 expect(queryByTestId('not-selected')).toHaveValue('')68 queryByTestId('single').children[0].setAttribute('selected', true)69 expect(queryByTestId('single')).toHaveValue('first')70 })71 test('handles value of textarea element', () => {72 const {queryByTestId} = render(`73 <textarea data-testid="textarea">text value</textarea>74 `)75 expect(queryByTestId('textarea')).toHaveValue('text value')76 })77 test('throws when passed checkbox or radio', () => {78 const {queryByTestId} = render(`79 <input data-testid="checkbox" type="checkbox" name="checkbox" value="val" checked />80 <input data-testid="radio" type="radio" name="radio" value="val" checked />81 `)82 expect(() => {83 expect(queryByTestId('checkbox')).toHaveValue('')84 }).toThrow()85 expect(() => {86 expect(queryByTestId('radio')).toHaveValue('')87 }).toThrow()88 })89 test('throws when the expected input value does not match', () => {90 const {container} = render(`<input data-testid="one" value="foo" />`)91 const input = container.firstChild92 let errorMessage93 try {94 expect(input).toHaveValue('something else')95 } catch (error) {96 errorMessage = error.message97 }98 expect(errorMessage).toMatchInlineSnapshot(`99 "<dim>expect(</><red>element</><dim>).toHaveValue(</><green>something else</><dim>)</>100 Expected the element to have value:101 <green> something else</>102 Received:103 <red> foo</>"104 `)105 })106 test('throws with type information when the expected text input value has loose equality with received value', () => {107 const {container} = render(`<input data-testid="one" value="8" />`)108 const input = container.firstChild109 let errorMessage110 try {111 expect(input).toHaveValue(8)112 } catch (error) {113 errorMessage = error.message114 }115 expect(errorMessage).toMatchInlineSnapshot(`116 "<dim>expect(</><red>element</><dim>).toHaveValue(</><green>8</><dim>)</>117 Expected the element to have value:118 <green> 8 (number)</>119 Received:120 <red> 8 (string)</>"121 `)122 })123 test('throws when using not but the expected input value does match', () => {124 const {container} = render(`<input data-testid="one" value="foo" />`)125 const input = container.firstChild126 let errorMessage127 try {128 expect(input).not.toHaveValue('foo')129 } catch (error) {130 errorMessage = error.message131 }132 expect(errorMessage).toMatchInlineSnapshot(`133 "<dim>expect(</><red>element</><dim>).not.toHaveValue(</><green>foo</><dim>)</>134 Expected the element not to have value:135 <green> foo</>136 Received:137 <red> foo</>"138 `)139 })140 test('throws when the form has no a value but a value is expected', () => {141 const {container} = render(`<input data-testid="one" />`)142 const input = container.firstChild143 let errorMessage144 try {145 expect(input).toHaveValue()146 } catch (error) {147 errorMessage = error.message148 }149 expect(errorMessage).toMatchInlineSnapshot(`150 "<dim>expect(</><red>element</><dim>).toHaveValue(</><green>expected</><dim>)</>151 Expected the element to have value:152 <green> (any)</>153 Received:154 "155 `)156 })157 test('throws when the form has a value but none is expected', () => {158 const {container} = render(`<input data-testid="one" value="foo" />`)159 const input = container.firstChild160 let errorMessage161 try {162 expect(input).not.toHaveValue()163 } catch (error) {164 errorMessage = error.message165 }166 expect(errorMessage).toMatchInlineSnapshot(`167 "<dim>expect(</><red>element</><dim>).not.toHaveValue(</><green>expected</><dim>)</>168 Expected the element not to have value:169 <green> (any)</>170 Received:171 <red> foo</>"172 `)173 })174})...
GlobalConfig-test.js
Source:GlobalConfig-test.js
...61 <AlarmsWrapper>62 <GlobalConfig {...commonProps} />63 </AlarmsWrapper>,64 );65 expect(getByTestId('resolve_timeout')).toHaveValue(66 defaultResponse.resolve_timeout,67 );68 expect(getByTestId('slack_api_url')).toHaveValue(69 defaultResponse.slack_api_url,70 );71 expect(getByTestId('pagerduty_url')).toHaveValue(72 defaultResponse.pagerduty_url,73 );74 expect(getByTestId('smtp_from')).toHaveValue(defaultResponse.smtp_from);75 expect(getByTestId('smtp_hello')).toHaveValue(defaultResponse.smtp_hello);76 expect(getByTestId('smtp_smarthost')).toHaveValue(77 defaultResponse.smtp_smarthost,78 );79 expect(getByTestId('smtp_auth_username')).toHaveValue(80 defaultResponse.smtp_auth_username,81 );82 expect(getByTestId('smtp_auth_password')).toHaveValue(83 defaultResponse.smtp_auth_password,84 );85 expect(getByTestId('smtp_auth_secret')).toHaveValue(86 defaultResponse.smtp_auth_secret,87 );88 expect(getByTestId('smtp_auth_identity')).toHaveValue(89 defaultResponse.smtp_auth_identity,90 );91 expect(getByTestId('opsgenie_api_url')).toHaveValue(92 defaultResponse.opsgenie_api_url,93 );94 expect(getByTestId('opsgenie_api_key')).toHaveValue(95 defaultResponse.opsgenie_api_key,96 );97 expect(getByTestId('hipchat_api_url')).toHaveValue(98 defaultResponse.hipchat_api_url,99 );100 expect(getByTestId('hipchat_auth_token')).toHaveValue(101 defaultResponse.hipchat_auth_token,102 );103 expect(getByTestId('wechat_api_url')).toHaveValue(104 defaultResponse.wechat_api_url,105 );106 expect(getByTestId('wechat_api_secret')).toHaveValue(107 defaultResponse.wechat_api_secret,108 );109 expect(getByTestId('wechat_api_corp_id')).toHaveValue(110 defaultResponse.wechat_api_corp_id,111 );112 expect(getByTestId('victorops_api_url')).toHaveValue(113 defaultResponse.victorops_api_url,114 );115 expect(getByTestId('victorops_api_key')).toHaveValue(116 defaultResponse.victorops_api_key,117 );118 expect(getByTestId('http_config_bearer_token')).toHaveValue(119 defaultResponse.http_config.bearer_token,120 );121 expect(getByTestId('http_config_proxy_url')).toHaveValue(122 defaultResponse.http_config?.proxy_url,123 );124 expect(getByTestId('basic_auth_username')).toHaveValue(125 defaultResponse.http_config?.basic_auth?.username,126 );127 expect(getByTestId('basic_auth_password')).toHaveValue(128 defaultResponse.http_config?.basic_auth?.password,129 );130});131test('submitting form submits updated values to backend', async () => {132 jest.spyOn(apiUtil, 'getGlobalConfig').mockReturnValue({});133 const editConfigMock = jest134 .spyOn(apiUtil, 'editGlobalConfig')135 .mockImplementationOnce(() => Promise.resolve());136 const {getByTestId} = render(137 <AlarmsWrapper>138 <GlobalConfig {...commonProps} />139 </AlarmsWrapper>,140 );141 act(() => {...
Focus.Spec.js
Source:Focus.Spec.js
...7 input.focus();8 });9 waits(20);10 then("placeholder text should be correct",function(){11 expect(input).toHaveValue('_');12 });13 and("caret position should be correct",function(){14 var caret=input.caret();15 expect(caret.begin).toEqual(0);16 expect(caret.end).toEqual(0);17 });18 });19 scenario("Mask starts with a literal",function(){20 given("a mask beginning with a literal",function(){21 input.mask("(9)");22 });23 when("focusing",function(){24 input.focus();25 });26 waits(20);27 then("placeholder text should be correct",function(){28 expect(input).toHaveValue('(_)');29 });30 and("caret position should be correct",function(){31 var caret=input.caret();32 expect(caret.begin).toEqual(1);33 expect(caret.end).toEqual(1);34 });35 });36 scenario("Mask starts with a literal that fits first placeholder",function(){37 given("a mask beginning with a literal",function(){38 input.mask("19").focus();39 });40 waits(20);41 when("blurring",function(){42 input.blur();43 });44 waits(20);45 then("input value should be correct",function(){46 expect(input).toHaveValue('');47 });48 });49 scenario("Mask starts with a literal that fits first placeholder and autoclear set to false",function(){50 given("a mask beginning with a literal",function(){51 input.mask("?19",{autoclear: false}).focus();52 });53 waits(20);54 when("blurring",function(){55 input.blur();56 });57 waits(20);58 then("input value should be correct",function(){59 expect(input).toHaveValue('');60 });61 });62 scenario("Masking a hidden input",function(){63 var error;64 $(window).on("error.test",function(err){error=err;})65 given("a mask on a hidden input",function(){66 input.hide().mask("9");67 });68 when("focusing input",function(){69 input.focus();70 });71 waits(1);72 then("should not throw an error",function(){73 expect(error).toBeUndefined();74 })75 });76 scenario("Mask contains a partial value with autoclear set to false",function(){77 given("the input has a partial value",function(){78 input.val("1");79 });80 given("a mask with two placeholders and autoclear=false",function(){81 input.mask("99", { autoclear: false });82 });83 when("focusing on the input",function(){84 input.focus();85 });86 then("the value should be partially filled out",function(){87 expect(input).toHaveValue("1_");88 });89 then("the input partial value should remain",function(){90 expect(input).toHaveValue("1_");91 });92 });93 scenario("Mask containing optional mask ?",function(){94 given("the input has a partial value",function(){95 input.val("99");96 });97 given("a optional mask on input",function(){98 input.mask("9?9");99 });100 when("focusing input",function(){101 input.focus();102 });103 waits(1);104 then("caret position should be correct",function(){105 var caret=input.caret();106 expect(caret.begin).toEqual(0);107 expect(caret.end).toEqual(2);108 });109 });110});111feature("Leaving A Masked Input",function(){112 scenario("All placeholders filled",function(){113 given("a mask with two placeholders",function(){114 input.mask("99");115 });116 when("typing two characters and blurring",function(){117 input.mashKeys("12").blur();118 });119 then("value should be correct",function(){120 expect(input).toHaveValue("12");121 });122 });123 scenario("Empty placeholders remaining",function(){124 given("a mask with two placeholders",function(){125 input.mask("99");126 });127 when("typing one character and blurring",function(){128 input.mashKeys("1").blur();129 });130 then("value should be empty",function(){131 expect(input).toHaveValue("");132 });133 });134 scenario("Mask ending in literal",function(){135 given("a mask ending in a literal",function(){136 input.mask("99!");137 });138 when("typing two characters and blurring",function(){139 input.mashKeys("12").blur();140 });141 then("value should remain",function(){142 expect(input).toHaveValue("12!");143 });144 });145 scenario("Empty placeholders remaining with autoclear set to false",function(){146 given("a mask with two placeholders",function(){147 input.mask("99", { autoclear: false });148 });149 when("typing one character and blurring",function(){150 input.caret(0);151 input.mashKeys("1")152 input.blur();153 });154 then("value should remain visible with placeholders",function(){155 expect(input).toHaveValue("1_");156 });157 });158 scenario("Shifts characters left on blur with autoclear false",function(){159 given("a mask with 10 placeholders",function(){160 input.mask("(999) 999-9999", { autoclear: false });161 });162 when("focusing input",function(){163 input.focus();164 });165 waits(20);166 when("typing characters at the end of the mask and blurring",function(){167 input.caret(12);168 input.mashKeys("44").blur();169 });170 then("characters should shift left to beginning of mask",function(){171 expect(input).toHaveValue("(44_) ___-____");172 });173 });...
useDebouncedFunction.test.js
Source:useDebouncedFunction.test.js
...34 const count = getByLabelText(/^Count$/i)35 const debouncedCount = getByLabelText(/^Debounced count$/i)36 const incrementButton = getByText(/Increment/i)37 // default values38 expect(count).toHaveValue('0')39 expect(debouncedCount).toHaveValue('0')40 // ensure no increments on first render41 jest.advanceTimersByTime(1000)42 expect(debouncedCount).toHaveValue('0')43 fireEvent.click(incrementButton)44 // immediate increment45 expect(count).toHaveValue('1')46 expect(debouncedCount).toHaveValue('0')47 jest.advanceTimersByTime(250)48 // part-way timeout49 expect(count).toHaveValue('1')50 expect(debouncedCount).toHaveValue('0')51 jest.advanceTimersByTime(250)52 // full timeout53 expect(count).toHaveValue('1')54 expect(debouncedCount).toHaveValue('1')55 // fire multiple events, should only count as 1 for debounced value56 fireEvent.click(incrementButton)57 fireEvent.click(incrementButton)58 fireEvent.click(incrementButton)59 fireEvent.click(incrementButton)60 fireEvent.click(incrementButton)61 // immediate increment62 expect(count).toHaveValue('6')63 expect(debouncedCount).toHaveValue('1')64 jest.advanceTimersByTime(250)65 // part-way timeout66 expect(count).toHaveValue('6')67 expect(debouncedCount).toHaveValue('1')68 jest.advanceTimersByTime(250)69 // full timeout70 expect(count).toHaveValue('6')71 expect(debouncedCount).toHaveValue('2')72 // ensure no more increments73 jest.advanceTimersByTime(1000)74 expect(debouncedCount).toHaveValue('2')75 })76 })...
index.test.js
Source:index.test.js
...23 const jobTitle = screen.getByTestId('jobTitle');24 const jobDescription = screen.getByTestId('jobDescription');25 const startDate = screen.getByTestId('startDate');26 const endDate = screen.getByTestId('endDate');27 expect(company).toHaveValue('');28 expect(jobTitle).toHaveValue('');29 expect(jobDescription).toHaveValue('');30 expect(startDate).toHaveValue('');31 expect(endDate).toHaveValue('');32 });33 it('should all form is filled', () => {34 const data = {35 company: 'Google',36 jobTitle: 'Software Engineer',37 jobDescription: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',38 startDate: '2020-01-01',39 endDate: 'Present',40 };41 render(<MockModal data={data} />);42 const company = screen.getByTestId('company');43 const jobTitle = screen.getByTestId('jobTitle');44 const jobDescription = screen.getByTestId('jobDescription');45 const startDate = screen.getByTestId('startDate');46 const endDate = screen.getByTestId('endDate');47 expect(company).toHaveValue(data.company);48 expect(jobTitle).toHaveValue(data.jobTitle);49 expect(jobDescription).toHaveValue(data.jobDescription);50 expect(startDate).toHaveValue(data.startDate);51 expect(endDate).toHaveValue(data.endDate);52 });53 it('should end date be present', () => {54 render(<MockModal />);55 const checkboxPresent = screen.getByTestId('checkbox-present');56 const endDate = screen.getByTestId('endDate');57 fireEvent.click(checkboxPresent);58 expect(endDate).toHaveValue('Present');59 });...
App.test.js
Source:App.test.js
...20test('Test without removing characters', () => {21 const { getByTestId } = renderApp(CORRECTIONS);22 const textarea = getByTestId(testIds.textarea);23 fireEvent.change(textarea, { target: { value: 'ax' }});24 expect(textarea).toHaveValue('ax');25 fireEvent.change(textarea, { target: { value: 'ax ' }});26 expect(textarea).toHaveValue('ax ');27 fireEvent.change(textarea, { target: { value: 'ax xy' }});28 expect(textarea).toHaveValue('ax xy');29 fireEvent.change(textarea, { target: { value: 'ax xy ' }});30 expect(textarea).toHaveValue('ax x ');31 fireEvent.change(textarea, { target: { value: 'ax x y' }});32 expect(textarea).toHaveValue('ax x y');33 fireEvent.change(textarea, { target: { value: 'ax x y ' }});34 expect(textarea).toHaveValue('ax x z ');35});36test('Test with removing characters', () => {37 const { getByTestId } = renderApp(CORRECTIONS);38 const textarea = getByTestId(testIds.textarea);39 fireEvent.change(textarea, { target: { value: 'abcd' }});40 expect(textarea).toHaveValue('abcd');41 fireEvent.change(textarea, { target: { value: 'abcd ' }});42 expect(textarea).toHaveValue('abcd ');43 fireEvent.change(textarea, { target: { value: 'abcd' }});44 expect(textarea).toHaveValue('abcd');45 fireEvent.change(textarea, { target: { value: 'abc' }});46 expect(textarea).toHaveValue('abc');47 fireEvent.change(textarea, { target: { value: 'abc ' }});48 expect(textarea).toHaveValue('bc ');...
Using AI Code Generation
1const wrapper = mount(<App />);2expect(wrapper.find('input').at(0)).toHaveValue('foo');3expect(wrapper.find('input').at(1)).toHaveValue('bar');4expect(wrapper.find('input').at(2)).toHaveValue('baz');5const wrapper = shallow(<App />);6expect(wrapper.find('input').at(0)).toHaveValue('foo');7expect(wrapper.find('input').at(1)).toHaveValue('bar');8expect(wrapper.find('input').at(2)).toHaveValue('baz');9const wrapper = render(<App />);10expect(wrapper.find('input').at(0)).toHaveValue('foo');11expect(wrapper.find('input').at(1)).toHaveValue('bar');12expect(wrapper.find('input').at(2)).toHaveValue('baz');13const wrapper = mount(<App />);14expect(wrapper.find('input').at(0)).toHaveValue('foo');15expect(wrapper.find('input').at(1)).toHaveValue('bar');16expect(wrapper.find('input').at(2)).toHaveValue('baz');17const wrapper = render(<App />);18expect(wrapper.find('input').at(0)).toHaveValue('foo');19expect(wrapper.find('input').at(1)).toHaveValue('bar');20expect(wrapper.find('input').at(2)).toHaveValue('baz');21const wrapper = mount(<App />);22expect(wrapper.find('input').at(0)).toHaveValue('foo');23expect(wrapper.find('input').at(1)).toHaveValue('bar');24expect(wrapper.find('input').at(2)).toHaveValue('baz');25const wrapper = render(<App />);26expect(wrapper.find('input').at(0)).toHaveValue('foo');27expect(wrapper.find('input').at(1)).toHaveValue('bar');28expect(wrapper.find('input').at(2)).toHaveValue('baz');29const wrapper = mount(<App />);30expect(wrapper.find('input').at(0)).toHaveValue('foo');31expect(wrapper.find('input').at(1)).toHaveValue('bar');32expect(wrapper.find('input').at(2)).toHaveValue('baz');
Using AI Code Generation
1const wrapper = mount(<MyComponent />)2expect(wrapper.find('input').get(0)).toHaveValue('foo')3const wrapper = mount(<MyComponent />)4expect(wrapper.find('input').get(1)).toHaveValue('bar')5const wrapper = mount(<MyComponent />)6expect(wrapper.find('input').get(2)).toHaveValue('baz')7const wrapper = mount(<MyComponent />)8expect(wrapper.find('input').get(3)).toHaveValue('qux')9const wrapper = mount(<MyComponent />)10expect(wrapper.find('input').get(4)).toHaveValue('quux')11const wrapper = mount(<MyComponent />)12expect(wrapper.find('input').get(5)).toHaveValue('quuz')13const wrapper = mount(<MyComponent />)14expect(wrapper.find('input').get(6)).toHaveValue('corge')15const wrapper = mount(<MyComponent />)16expect(wrapper.find('input').get(7)).toHaveValue('grault')17const wrapper = mount(<MyComponent />)18expect(wrapper.find('input').get(8)).toHaveValue('garply')19const wrapper = mount(<MyComponent />)20expect(wrapper.find('input').get(9)).toHaveValue('waldo')21const wrapper = mount(<MyComponent />)22expect(wrapper.find('input').get(10)).toHaveValue('fred')23const wrapper = mount(<MyComponent />)24expect(wrapper.find('input').get(11)).toHaveValue('plugh')25const wrapper = mount(<MyComponent />)26expect(wrapper.find('input').get(12)).toHaveValue('xyzzy')27const wrapper = mount(<MyComponent />)28expect(wrapper.find('input').get(13)).toHaveValue('thud')
Using AI Code Generation
1describe('Test', () => {2 it('should have value', () => {3 const wrapper = shallow(<Test />)4 expect(wrapper.find('input').first().props().value).toBe('test')5 })6})7describe('Test', () => {8 it('should have value', () => {9 const wrapper = shallow(<Test />)10 expect(wrapper.find('input').first().props().value).toBe('test')11 })12})13describe('Test', () => {14 it('should have value', () => {15 const wrapper = shallow(<Test />)16 expect(wrapper.find('input').first().props().value).toBe('test')17 })18})19describe('Test', () => {20 it('should have value', () => {21 const wrapper = shallow(<Test />)22 expect(wrapper.find('input').first().props().value).toBe('test')23 })24})25describe('Test', () => {26 it('should have value', () => {27 const wrapper = shallow(<Test />)28 expect(wrapper.find('input').first().props().value).toBe('test')29 })30})31describe('Test', () => {32 it('should have value', () => {33 const wrapper = shallow(<Test />)34 expect(wrapper.find('input').first().props().value).toBe('test')35 })36})37describe('Test', () => {38 it('should have value', () => {39 const wrapper = shallow(<Test />)40 expect(wrapper.find('input').first().props().value).toBe('test')41 })42})43describe('Test', () => {44 it('should have value', () => {45 const wrapper = shallow(<Test />)46 expect(wrapper.find('input').first().props().value).toBe('test')47 })48})49describe('Test', () => {50 it('should have value', () => {51 const wrapper = shallow(<Test />)52 expect(wrapper.find('input').first().props().value).toBe('test
Using AI Code Generation
1expect(wrapper.find('input').at(0)).toHaveValue('some value');2expect(wrapper.find('input').at(0).props().value).toEqual('some value');3expect(wrapper.find('input').at(0).prop('value')).toEqual('some value');4expect(wrapper.find('input').at(0).getDOMNode().value).toEqual('some value');5expect(wrapper.find('input').at(0).instance().value).toEqual('some value');6expect(wrapper.find('input').at(0).html()).toEqual('some value');7expect(wrapper.find('input').at(0).text()).toEqual('some value');8expect(wrapper.find('input').at(0).node.value).toEqual('some value');9expect(wrapper.find('input').at(0).type()).toEqual('some value');10expect(wrapper.find('input').at(0).name()).toEqual('some value');11expect(wrapper.find('input').at(0).key()).toEqual('some value');12expect(wrapper.find('input').at(0).simulate('change')).toEqual('some value');13expect(wrapper.find('input').at(0).simulate('change').value).toEqual('some value');14expect(wrapper.find('input').at(0).simulate('change').target.value).toEqual('some value');15expect(wrapper.find('input').at(0).simulate('change').target
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!!