【发布时间】: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