@@ -2,37 +2,17 @@ import { render, screen, waitForElementToBeRemoved } from '@testing-library/reac
2
2
import React from 'react' ;
3
3
import PhoneBook from '../PhoneBook' ;
4
4
import { User } from '../types' ;
5
+ import axios from 'axios' ;
5
6
6
- // Ensure that the global fetch function is mocked in your setup file
7
- // before running the tests. This will ensure that the tests don't
8
- // make any actual network requests that you haven't mocked.
9
- beforeAll ( ( ) => {
10
- jest . spyOn ( global , 'fetch' ) . mockImplementation (
11
- jest . fn ( ( ) => {
12
- throw Error ( 'Only Chuck Norris is allowed to make API requests when testing ;)' ) ;
13
- } ) ,
14
- ) ;
15
- } ) ;
16
-
17
- afterAll ( ( ) => {
18
- ( global . fetch as jest . Mock ) . mockRestore ( ) ;
19
- } ) ;
7
+ jest . mock ( 'axios' ) ;
8
+ const mockedAxios = axios as jest . Mocked < typeof axios > ;
20
9
21
10
describe ( 'PhoneBook' , ( ) => {
22
- let originalFetch : typeof global . fetch ;
23
- beforeAll ( ( ) => {
24
- originalFetch = global . fetch ;
25
- global . fetch = jest . fn ( ) . mockResolvedValueOnce ( {
11
+ it ( 'fetches contacts successfully and renders in list' , async ( ) => {
12
+ ( global . fetch as jest . SpyInstance ) . mockResolvedValueOnce ( {
26
13
json : jest . fn ( ) . mockResolvedValueOnce ( DATA ) ,
27
14
} ) ;
28
- //TODO: mock axios
29
- } ) ;
30
-
31
- afterAll ( ( ) => {
32
- global . fetch = originalFetch ;
33
- } ) ;
34
-
35
- it ( 'fetches contacts successfully and renders in list' , async ( ) => {
15
+ ( mockedAxios . get as jest . Mock ) . mockResolvedValue ( { data : DATA } ) ;
36
16
render ( < PhoneBook /> ) ;
37
17
38
18
await waitForElementToBeRemoved ( ( ) => screen . getByText ( / u s e r s d a t a n o t q u i t e t h e r e y e t / i) ) ;
@@ -42,11 +22,15 @@ describe('PhoneBook', () => {
42
22
} ) ;
43
23
44
24
it ( 'fetches favorites successfully and renders in list' , async ( ) => {
25
+ ( global . fetch as jest . SpyInstance ) . mockResolvedValueOnce ( {
26
+ json : jest . fn ( ) . mockResolvedValueOnce ( DATA ) ,
27
+ } ) ;
28
+ ( mockedAxios . get as jest . Mock ) . mockResolvedValue ( { data : DATA } ) ;
45
29
render ( < PhoneBook /> ) ;
46
30
47
31
await waitForElementToBeRemoved ( ( ) => screen . getByText ( / f i g u r i n g o u t y o u r f a v o r i t e s / i) ) ;
48
32
expect ( await screen . findByText ( / m y f a v o r i t e s / i) ) . toBeOnTheScreen ( ) ;
49
- expect ( await screen . findAllByText ( / n a m e / i ) ) . toHaveLength ( 3 ) ;
33
+ expect ( await screen . findAllByLabelText ( 'favorite-contact-avatar' ) ) . toHaveLength ( 3 ) ;
50
34
} ) ;
51
35
} ) ;
52
36
0 commit comments