我试图用玩笑来嘲弄他,结果碰壁了。
我试过两种方法:
方法1:手动执行它,如下所示:
const pokemon = {
id: 1,
name: 'fake1',
sprites: {other: {'official-artwork': {front_default: 'picture'}}},
types: ['earth']
}
const fakePokemons = JSON.stringify([pokemon, pokemon])
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve(fakePokemons),
})
);
fetchData([1, 4, 7]) // this is the actual funciton call我得到的错误是:
TypeError: Cannot read property 'other' of undefined它与函数未能提取的sprites.other.etc...属性有关。我不明白为什么明明在那里。
jest-fetch-mock方法2:使用代码:
fetch.mockResponseOnce(JSON.stringify(fakePokemons));
fetchData([1, 4, 7])在这种情况下,我被困在:
FetchError: invalid json response body at reason: Unexpected end of JSON input我试着用和不带JSON.stringify() -没有运气。我在跟踪本教程,这两种方法似乎都很有效
我遗漏了什么?
发布于 2020-11-13 18:02:28
你搞错了玩笑到底在做什么。Jest只是将本机fetch替换为函数,该函数将返回一个简单的解析承诺,其中包含一个带有json属性的对象,然后包含一个已解析的承诺,并将fakePokemons作为字符串,并将其封装在模拟实用程序中以监视调用。
您不应该对fakePokemons进行字符串化,因为fetch.json调用的预期输出是对象本身,而不是字符串形式:
const pokemon = {
id: 1,
name: 'fake1',
sprites: {other: {'official-artwork': {front_default: 'picture'}}},
types: ['earth']
}
const fakePokemons = [pokemon, pokemon] // HERE
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve(fakePokemons),
})
);您还可以在每次测试后使用fetch.mockClear()删除所有模拟。
见Jest模拟文档为您提供更多信息。
在第二种方法中,fakePokemons确实被压缩了两次,并导致一个错误。
发布于 2020-11-16 04:02:38
我最近在spyOn和mockResolvedValue方面取得了成功。试试看:
// somewhere global like outside of any describe or test blocks
jest.spyOn(global, 'fetch');
// ...
// for me, it made sense to include this in beforeEach
global.fetch.mockResolvedValue({
ok: true,
json: () => pokemon // note no stringify, just the data
});这是受一篇文章的启发,这篇文章为停止嘲弄做了一个案例。
https://stackoverflow.com/questions/64823842
复制相似问题