简体   繁体   English

测试Redux-Saga的“收益率电话”

[英]Test Redux-Saga 'yield call'

I'm trying to write a unit test to the following saga : 我正在尝试对以下传奇进行单元测试:

 function * verifyCode(api){ let action = yield take(LoginTypes.VERIFY_CODE) const phoneNumber = yield select(phoneNumberSelector) try{ const response = yield call(api.verifyCode, phoneNumber, action.code) if (response.ok){ let token = response.data.token yield put(LoginActions.verifyCodeSuccess(response.data.token)) } else { yield put(LoginActions.verifyCodeFailure(response.error)) } } catch(error){ yield put(LoginActions.verifyCodeFailure(error)) } } 

All the tests pass up until the 'yield call' part, using the following (using test from 'tape'): 使用以下命令(使用来自“ tape”的测试),所有测试通过直到“ yield call”部分。

 test('verify code flow', (assert) => { let number = '0000000' let code = '00000' const gen = verifyCode(api) assert.deepEqual( gen.next({code: code}).value, take(LoginTypes.VERIFY_CODE), 'wait for verify code action from user', ) assert.deepEqual( gen.next().value, select(phoneNumberSelector), 'get phoneNumber from login state' ) assert.deepEqual( gen.next().value, call(api.verifyCode, number, code), 'call verify code' ) assert.end() }) 

The error I get for the failure of this test is 我因这次测试失败而得到的错误是

   operator: deepEqual
expected: |-
  { '@@redux-saga/IO': true, CALL: { context: null, fn: [Function: verifyCode], args: [ '0000000', '00000' ] } }
actual: |-
  { '@@redux-saga/IO': true, PUT: { channel: null, action: { type: 'VERIFY_CODE_FAILURE', error: [TypeError: Cannot read property 'code' of undefined] } } }
  1. What is the correct way to write to an api call using the 'call' effect? 使用“调用”效果写入api调用的正确方法是什么?
  2. How can I test the different possible flows depending on the ''response I get? 如何根据“收到的响应”测试不同的可能流量?
  1. This is the correct way to use the call effect on an API 这是在API上使用调用效果的正确方法
  2. To test different flows (Success | Failure) you can use the following pattern (in Jest): 要测试不同的流(成功|失败),可以使用以下模式(在Jest中):
 expect(generator.next().value.PUT.action).toMatchObject({type: types.VERIFY_CODE_SUCCESS, payload: {}, meta: { section }}); expect(generator.throw('error').value.PUT.action).toMatchObject({ type: VERIFY_CODE_FAILURE, payload: 'error'}); 

BTW: It seems that your test fails due to an error thrown when you called your API endpoint. 顺便说一句:似乎由于调用API端点时抛出错误而导致测试失败。 Make sure you get the desired response from your endpoint. 确保从端点获得所需的响应。

Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM