BSK*_*BSK 2 unit-testing reactjs jestjs react-testing-library
我正在测试一个组件,该组件使用一个useEffect
钩子从 API 获取数据,更新状态,然后构建组件。我已经使用Stack Overflow 答案作为示例成功模拟了几次测试的 API 响应。我现在正在尝试编写一个测试,在其中模拟从 API 返回的错误。我收到一条错误,TypeError: Cannot read property 'then' of undefined
指出fetch
. 我正在尝试使用相同的示例,但没有成功。
我成功地使用测试数据获取模拟如下所示:
global.fetch = jest.fn().mockImplementationOnce(() =>
Promise.resolve({
json: () => Promise.resolve(successMockData),
})
)
Run Code Online (Sandbox Code Playgroud)
我尝试的模拟错误响应当前如下所示:
global.fetch = jest.fn().mockImplementationOnce(() => {
Promise.resolve({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
})
Run Code Online (Sandbox Code Playgroud)
如果我拒绝承诺,我仍然会得到相同的错误,但也会引发抛出的异常:
global.fetch = jest.fn().mockImplementationOnce(() => {
Promise.reject({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
})
Run Code Online (Sandbox Code Playgroud)
该 API 使用 NextApiResponse ,如下所示:
try {
// Query data from database
const data = methodThatGetsDataFromDatabase()
return res.status(200).json({ success: true, data: data })
} catch (error) {
return res.status(400).json({ success: false, error: error.message })
}
Run Code Online (Sandbox Code Playgroud)
我已经在这方面工作了很长时间,并在谷歌上寻找答案。我只是不明白为什么fetch
未定义而不是返回承诺。任何帮助是极大的赞赏!
我发现的区别在于,您成功的 fetch 模拟实际上返回了 Promise。
但是失败的 fetch 模拟并没有返回——请注意在 Promise 周围添加了微妙的花括号。你能在没有大括号的情况下检查这个吗?
global.fetch = jest.fn().mockImplementationOnce(() =>
Promise.resolve({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4748 次 |
最近记录: |