error-handling - 用 Jest 捕捉错误时如何测试 Redux-Saga

标签 error-handling generator jestjs redux-saga saga

每个人。我用 jest 框架测试 saga。我可以在正常情况下测试我的传奇。但是我想测试catch()中的代码,所以我必须模拟一个错误来触发catch。我在 redux-saga 官方文档和其他 stackoverflow 答案中找到了一些解决方案。但我仍然有问题。

当我像下面的示例一样在 saga.test.js 中使用 throw() 时,它会显示“抛出错误 [对象对象]”。所以它真的不能通过这个测试。我没有看到有人问同样的问题。有人可以帮助我吗?非常感谢。

错误结果画面:

img1

api.js

const api = {
  fetchProductAPI() {
    return 'iphone';
  },
};
export default api;

传奇.js
import { call, put } from 'redux-saga/effects';
import api from './api';

export default function* fetchProduct() {
  try {
    yield call(api.fetchProductAPI);
    yield put({ type: 'PRODUCTS_RECEIVED', product: 'iphone' });
  } catch (error) {
    yield put({ type: 'PRODUCTS_REQUEST_FAILED', error });
  }
}

saga.test.js
import { put, call } from 'redux-saga/effects';
import fetchProduct from './saga';
import api from './api';

describe('fetchProduct()', () => {
  it('try', () => {
    const gen = fetchProduct();
    expect(gen.next().value).toEqual(call(api.fetchProductAPI));
    expect(gen.next().value).toEqual(put({ type: 'PRODUCTS_RECEIVED', product: 'iphone' }));
  });
  it('catch', () => {
    const error = 'product not found';
    const gen = fetchProduct();
    expect(
      gen.throw({
        error: 'product not found',
      }).value
    ).toEqual(put({ type: 'PRODUCTS_REQUEST_FAILED', error }));
  });
});

我在下面找到的相关解决方案答案:

Redux-Saga Error Handling

How to test API request failures with Redux Saga?

最佳答案

我的 friend 帮我解决了这个问题。所以我自己回答我的问题......

我需要添加 gen.next()在我扔之前。这是下面的解决方案代码。

it('catch', () => {
  const error = 'product not found';
  const gen = fetchProduct();
  gen.next(); //add gen.next() before throw
  expect(
    gen.throw('product not found').value).
    toEqual(put({ type: 'PRODUCTS_REQUEST_FAILED', error }));
  });
});

关于error-handling - 用 Jest 捕捉错误时如何测试 Redux-Saga,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444523/

相关文章:

android - React Native获取在Android上提供TypeError

python - 如何查找Python文档中出现的错误?

javascript - 无法解构函数生成器中的对象

reactjs - 如何使用 jest 和 React 测试库测试 axios api?

android - 在状态 0 下调用媒体播放器,错误 (-38,0) 错误

coffeescript - Yeoman 生成器 CoffeeScript 入口点

php - 新手问题: table to form generator in php

javascript - 如何模拟函数,即在 axios promise 的 "then"中调用的函数?

jestjs - 在 docblock 中设置自定义 Jest 环境

ruby-on-rails - 服务对象的验证和错误处理