【问题标题】:How to mock a fetch function with jest ensuring to also capture the catch function?如何用 jest 模拟 fetch 函数确保也捕获 catch 函数?
【发布时间】:2022-01-26 17:58:14
【问题描述】:

我正在尝试模拟一个 fetch 函数,但这似乎不像最初想象的那么简单,因为我使用的代码似乎并未涵盖该函数的所有方面。

这是我试图在其上创建模拟的代码:

 useEffect(() => {
    fetch('https://connectr-swapi.herokuapp.com/', {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({query: STARSHIP_QUERY})
    })
    .then(response => {response.json()})
    .then(data => setStarships(data.data.allStarships.starships))
    .catch(error => console.log({'Error': error}))
},[])

这就是我目前想出的,但目前正在收到Error: TypeError: Cannot read property 'data' of undefined

const mockResponse = {
    data: {
        data: {
            allStarships: {
                starships: [
                    {
                        id: 1,
                        name: 'ship_1',
                        starshipClass: 'class_1',
                        maxAtmospheringSpeed: 1,
                        costInCredits: 1
                    },
                    {
                        id: 1,
                        name: 'ship_2',
                        starshipClass: 'class_2',
                        maxAtmospheringSpeed: 2,
                        costInCredits: 2
                    },
                ]
            }
        }
    }
}

beforeEach(() => {
    jest.spyOn(global, 'fetch').mockResolvedValue({
        json: jest.fn().mockResolvedValue(mockResponse)
    })
});

afterEach(() => {
    jest.resetAllMocks(); 
})

有什么建议吗?

【问题讨论】:

    标签: jestjs react-testing-library


    【解决方案1】:

    .then(response => {response.json()}) 本身的语法是错误的。

    fetch() API 首先返回一个用 Response 对象解析的承诺,该对象包含接口类型 Response 的整个 HTTP 响应的表示。可以从响应对象中提取 JSON 正文内容,该对象本身返回第二个承诺,该承诺通过将响应正文文本解析为 JSON 的结果进行解析。

    你试图返回一个简单的对象,而不是任何你正在解析为 JSON 解析数据的承诺。

    useEffect(() => {
        fetch('https://connectr-swapi.herokuapp.com/', {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({query: STARSHIP_QUERY})
        })
        .then(response => response.json()) // removed the curly braces 
        .then(data => {
           const {data: {allStarships : {starships}}} = data;
           setStarships(starships);
        }
        .catch(error => console.log({'Error': error}))
    },[])
    
    const mockResponse = {
        data: {
            data: {
                allStarships: {
                    starships: [
                        {
                            id: 1,
                            name: 'ship_1',
                            starshipClass: 'class_1',
                            maxAtmospheringSpeed: 1,
                            costInCredits: 1
                        },
                        {
                            id: 1,
                            name: 'ship_2',
                            starshipClass: 'class_2',
                            maxAtmospheringSpeed: 2,
                            costInCredits: 2
                        },
                    ]
                }
            }
        }
    }
    
    let fetchMock;
     
    beforeEach(() => {
        mockfetch = jest
                     .spyOn(global, 'fetch')
                     .mockResolvedValue({
                        json: jest.fn().mockResolvedValue(mockResponse)
                     });   
    });
    
    afterEach(() => {
        jest.restoreAllMocks(); 
    })
    

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2022-06-29
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多