测试sagas:从通话效果中抽出响应

时间:2018-07-12 20:26:34

标签: javascript reactjs redux redux-saga

我有以下传说:

export function* getPosts() {
  try {
    const response = yield call(apiCall);
    yield put({ type: "API_CALL_SUCCESS", response });
  } catch(e) {
    // ...
  }

以及以下规范:

describe('GetPosts', () => { 
  beforeEach(() => {
    sinon.stub(api, 'apiCall').returns(Promise.resolve({some:'value'}));
  });


  const generator = getPosts();
  it('should yield call', () => {
    expect(generator.next().value).toEqual(call(api.apiCall));
  });

  it('should yield put', () => {
    expect(generator.next().value).toEqual(put({ type: "API_CALL_SUCCESS", response: { some: 'value' } }));
  });
});

第一个测试通过,但是第二个测试失败,因为它期望响应等于{some: 'value'},但实际上它是undefined,即使存根被设置为返回值为{{1}的已解决的promise }。

这是为什么?测试此代码的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

解决了这个问题。应该使用动作创建者代替:

export function* getPosts() {
  try {
    const res = yield call(someCall);
    yield put(actions.receive(res));
  } catch(e) {
    // ...
  }

经过如下测试:

it('should yield put', () => {
    const data = {}
    expect(gen.next(thing).value).toEqual(put(actions.receive(data)));
  });