带有响应图像的Jest Redux Saga API调用

发布于 2025-02-04 17:39:15 字数 641 浏览 4 评论 0原文

我正在尝试测试以图像的可读流响应的提取,但我不确定如何处理这种特定情况。 是否有一种简单,简单的方法来嘲笑通话的响应?

任何帮助都将不胜感激: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

错爱 2025-02-11 17:39:15

您可以使用测试saga生成器功能步骤方法。

在测试SAGA Generator函数之前,您需要了解这些内容:

  1. jsdom不支持fetch,请参见问题#1724

  2. jsdom不支持url.createobjectUrl api,请参阅问题#1721

  3. 默认情况下,jestjs使用jsdom作为测试环境模拟类似浏览器的环境。

因此,我将使用iSomorphic-fetch用于fetch的polyfill,以及模拟url.createobjectUrl() api及其返回值。此外,您还可以使用 wendesp> wenspy> wenspy> wendesp> /code>构造函数创建您自己的自定义响应对象:

const response = new Response();

我们将使用此自定义响应对象作为fetch的模拟返回值。

测试将是:

index.ts

import { call, put } from 'redux-saga/effects';

export const getImageSuccess = (payload) => ({ type: 'GET_IMAGE_SUCCESS', payload });
export const getImageError = (payload) => ({ type: 'GET_IMAGE_ERROR', payload });
export const GET_IMAGE_API = 'http://localhost:3000/api/image';

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));
  }
}

index.test.ts

import { call, put } from 'redux-saga/effects';
import { getImageSaga } from './';

describe('72521882', () => {
  test('should get image success', () => {
    const objectUrl = 'blob:https://yari-demos.prod.mdn.mozit.cloud/8b065c5a-fd18-44d8-9ff5-5c29407a88b7';
    Object.defineProperty(window.URL, 'createObjectURL', { value: () => objectUrl });

    const gen = getImageSaga();

    expect(gen.next().value).toEqual(
      call(fetch, 'http://localhost:3000/api/image', {
        headers: {
          Accept: 'image/jpeg',
        },
        method: 'GET',
      }),
    );
    const mResponse = new Response();
    gen.next(mResponse);

    expect(gen.next().value).toEqual(put({ type: 'GET_IMAGE_SUCCESS', payload: objectUrl }));
  });
});

测试结果:

 PASS   redux-saga-examples  packages/redux-saga-examples/src/stackoverflow/72521882/index.test.ts
  72521882
    ✓ should get image success (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |      100 |   66.67 |   91.67 |                   
 index.ts |   88.89 |      100 |   66.67 |   91.67 | 22                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.648 s

jest.setup.js

import 'isomorphic-fetch';

jest.setTimeout(10 * 1000);

jest。 config.js

{
  setupFilesAfterEnv: ['./jest.setup.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:

  1. jsdom doesn't support fetch yet, see issue#1724

  2. jsdom doesn't support URL.createObjectURL API yet, see issue#1721

  3. By default, jestjs uses jsdom as a test environment to simulate the browser-like environment.

So I will use isomorphic-fetch polyfill for fetch, and mock URL.createObjectURL() API and its return value. Besides, you can also use the Response() constructor to create your own custom Response object:

const response = new Response();

We will use this custom response object as the mock return value of fetch.

The test will be:

index.ts:

import { call, put } from 'redux-saga/effects';

export const getImageSuccess = (payload) => ({ type: 'GET_IMAGE_SUCCESS', payload });
export const getImageError = (payload) => ({ type: 'GET_IMAGE_ERROR', payload });
export const GET_IMAGE_API = 'http://localhost:3000/api/image';

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));
  }
}

index.test.ts:

import { call, put } from 'redux-saga/effects';
import { getImageSaga } from './';

describe('72521882', () => {
  test('should get image success', () => {
    const objectUrl = 'blob:https://yari-demos.prod.mdn.mozit.cloud/8b065c5a-fd18-44d8-9ff5-5c29407a88b7';
    Object.defineProperty(window.URL, 'createObjectURL', { value: () => objectUrl });

    const gen = getImageSaga();

    expect(gen.next().value).toEqual(
      call(fetch, 'http://localhost:3000/api/image', {
        headers: {
          Accept: 'image/jpeg',
        },
        method: 'GET',
      }),
    );
    const mResponse = new Response();
    gen.next(mResponse);

    expect(gen.next().value).toEqual(put({ type: 'GET_IMAGE_SUCCESS', payload: objectUrl }));
  });
});

Test result:

 PASS   redux-saga-examples  packages/redux-saga-examples/src/stackoverflow/72521882/index.test.ts
  72521882
    ✓ should get image success (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |      100 |   66.67 |   91.67 |                   
 index.ts |   88.89 |      100 |   66.67 |   91.67 | 22                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.648 s

jest.setup.js:

import 'isomorphic-fetch';

jest.setTimeout(10 * 1000);

jest.config.js:

{
  setupFilesAfterEnv: ['./jest.setup.js']
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文