Jest.js 使用API调用测试redux-saga

myzjeezk  于 2023-01-06  发布在  Jest
关注(0)|答案(1)|浏览(177)

我一直在使用这个函数来测试我的传奇故事,但在这种情况下它不起作用。
我从调度函数内部的控制台得到响应,但调度的数组没有更新。
Saga

export function* releaseCommitsSaga({ release, product } ) {
    if (release && product) {
        const response = yield fetch(`${ApiEndpoint}/ReleaseCommits?${getURLQueryParams({ product, version: release })}`);

        const releaseCommits = yield response.json()
            .catch((error) => error);

        if (response.status === 200) {
            console.log(releaseCommits);
            yield put(getReleaseCommitsSuccess(releaseCommits));
        } else {
            yield put(getReleaseCommitsFailure('release commits could not be fetched'));
        }
    } else {
        yield put({
            type: INVALID_PAGE_LOAD,
        });
    }
}

测验

it('releaseCommitsSaga success', async () => {
        const response = responses.getReleaseCommitsResponse('success');
        global.fetch = jest.fn(() => Promise.resolve({
            status: 200,
            json: () => Promise.resolve(response),
        }));
        const dispatched = [];
        await runSaga({
            dispatch: (action) => {
                console.log(action);
                dispatched.push(action);
            },
        }, releaseCommitsSaga, getReleaseCommits(release, product));
        await expect(fetch).toHaveBeenCalled();
        expect(dispatched).toEqual([getReleaseCommitsSuccess(releaseCommits)]);
        fetch.mockClear();
    });

控制台

console.log src/__tests__/sagas/release.test.js:204
      {
        type: 'GET_RELEASE_COMMITS_SUCCESS',
        releaseCommits: [
          {
            package: 'package_abc',
            id: 'long_id',
            committer: 'someone@something.com',
            message: 'commit msg'
          }
        ]
      }
ax6ht2ek

ax6ht2ek1#

您应该使用task.toPromise()runSaga()返回的任务转换为承诺,请参阅任务。然后使用async/await等待任务完成。
例如
saga.ts

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

const ApiEndpoint = 'http://localhost:3000';
const INVALID_PAGE_LOAD = 'INVALID_PAGE_LOAD';
export const getReleaseCommitsSuccess = (payload) => ({ type: 'GET_RELEASE_COMMITS_SUCCESS', payload });
export const getReleaseCommitsFailure = (payload) => ({ type: 'GET_RELEASE_COMMITS_FAILURE', payload });

export function* releaseCommitsSaga({ release, product }) {
  if (release && product) {
    const response = yield fetch(`${ApiEndpoint}/ReleaseCommits?product=${product}&version=${release}`);

    const releaseCommits = yield response.json().catch((error) => error);

    if (response.status === 200) {
      console.log(releaseCommits);
      yield put(getReleaseCommitsSuccess(releaseCommits));
    } else {
      yield put(getReleaseCommitsFailure('release commits could not be fetched'));
    }
  } else {
    yield put({
      type: INVALID_PAGE_LOAD,
    });
  }
}

saga.test.ts

import { Action } from 'redux';
import { runSaga } from 'redux-saga';
import { releaseCommitsSaga } from './saga';

describe('74999487', () => {
  it('releaseCommitsSaga success', async () => {
    const response = [
      {
        package: 'package_abc',
        id: 'long_id',
        committer: 'someone@something.com',
        message: 'commit msg',
      },
    ];
    (global as any).fetch = jest.fn(() =>
      Promise.resolve({
        status: 200,
        json: () => Promise.resolve(response),
      }),
    );
    const dispatched: Action[] = [];
    await runSaga(
      {
        dispatch: (action: Action) => {
          console.log(action);
          dispatched.push(action);
        },
      },
      releaseCommitsSaga,
      { product: 'a', release: 'v1' },
    ).toPromise();

    expect(fetch).toHaveBeenCalled();
    expect(dispatched).toEqual([{ type: 'GET_RELEASE_COMMITS_SUCCESS', payload: response }]);
    (global.fetch as jest.MockedFunction<typeof fetch>).mockClear();
  });
});

试验结果:

PASS   redux-saga-examples  packages/redux-saga-examples/src/stackoverflow/74999487/saga.test.ts
  74999487
    ✓ releaseCommitsSaga success (23 ms)

  console.log
    [
      {
        package: 'package_abc',
        id: 'long_id',
        committer: 'someone@something.com',
        message: 'commit msg'
      }
    ]

      at packages/redux-saga-examples/src/stackoverflow/74999487/saga.ts:15:15

  console.log
    {
      type: 'GET_RELEASE_COMMITS_SUCCESS',
      payload: [
        {
          package: 'package_abc',
          id: 'long_id',
          committer: 'someone@something.com',
          message: 'commit msg'
        }
      ]
    }

      at dispatch (packages/redux-saga-examples/src/stackoverflow/74999487/saga.test.ts:25:19)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   82.61 |       50 |      50 |   85.71 |                   
 saga.ts  |   82.61 |       50 |      50 |   85.71 | 18-21             
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.142 s

软件包版本:

"redux": "^4.1.0",
"redux-saga": "^1.1.3",

相关问题