我正在尝试为以下传奇写一个单元测试:
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))
}
}
所有测试都通过'yield call'部分,使用以下内容(使用'tape'中的测试):
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()
})
我为此测试失败而得到的错误是
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] } } }
答案 0 :(得分:0)
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'});
顺便说一句:似乎由于调用API端点时引发的错误,导致测试失败。确保从端点获得所需的响应。
祝你好运!