带有响应图像的Jest Redux Saga API调用
我正在尝试测试以图像的可读流响应的提取,但我不确定如何处理这种特定情况。 是否有一种简单,简单的方法来嘲笑通话的响应?
任何帮助都将不胜感激:D
发电机函数看起来如下:
export function* getImageSaga () {
try {
const headers = {
Accept: 'image/jpeg',
};
const options = {
headers,
method: 'GET',
};
const response = yield call(fetch, GET_IMAGE_API, options);
const blob = yield response.blob();
const url = URL.createObjectURL(blob);
yield put(getImageSuccess(url));
} catch (error) {
yield put(getImageError(error));
}
}
I'm trying to test a fetch that responds with a readable stream for an image, but I'm stuck and not sure how to approach this specific case.
Is there a simple, easy way to mock the call's response?
Any help would be appreciated :D
The generator function looks like the following:
export function* getImageSaga () {
try {
const headers = {
Accept: 'image/jpeg',
};
const options = {
headers,
method: 'GET',
};
const response = yield call(fetch, GET_IMAGE_API, options);
const blob = yield response.blob();
const url = URL.createObjectURL(blob);
yield put(getImageSuccess(url));
} catch (error) {
yield put(getImageError(error));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用测试saga生成器功能步骤方法。
在测试SAGA Generator函数之前,您需要了解这些内容:
jsdom
不支持fetch
,请参见问题#1724jsdom
不支持url.createobjectUrl
api,请参阅问题#1721默认情况下,
jestjs
使用jsdom
作为测试环境模拟类似浏览器的环境。因此,我将使用
iSomorphic-fetch
用于fetch
的polyfill,以及模拟url.createobjectUrl()
api及其返回值。此外,您还可以使用wendesp> wenspy> wenspy> wendesp> /code>
构造函数创建您自己的自定义响应对象:
我们将使用此自定义响应对象作为
fetch
的模拟返回值。测试将是:
index.ts
:index.test.ts
:测试结果:
jest.setup.js
:jest。 config.js
:You can use testing the saga generator function step-by-step approach.
Before testing the saga generator function, you need to be aware of these things:
jsdom
doesn't supportfetch
yet, see issue#1724jsdom
doesn't supportURL.createObjectURL
API yet, see issue#1721By default,
jestjs
usesjsdom
as a test environment to simulate the browser-like environment.So I will use
isomorphic-fetch
polyfill forfetch
, and mockURL.createObjectURL()
API and its return value. Besides, you can also use theResponse()
constructor to create your own custom Response object:We will use this custom response object as the mock return value of
fetch
.The test will be:
index.ts
:index.test.ts
:Test result:
jest.setup.js
:jest.config.js
: