2016-09-10 2 views
0

if文の中の関数をテストするか、try/catchを試しますか?例えば、if文内でredux-sagaをテストし、実際の値を使用

export function* onFetchMessages(channel) { 
    yield put(requestMessages()) 
    const channel_name = channel.payload 
    try { 
     const response = yield call(fetch,'/api/messages/'+channel_name) 

     if(response.ok){ 
      const res = yield response.json(); 

      const date = moment().format('lll'); 
      yield put(receiveMessages(res,channel.payload,date)) 
     } 


    } catch (error){ 
     yield put(rejectMessages(error)) 
    } 
} 

は、私はそれ以外の場合はエラーがスローされます、入力それが実行に従う利回りのための有効な応答を返すようにするために、実際にデータベースに存在し、実際のチャンネル名にする必要があります。さらに、エラーメッセージが表示され、未定義のプロパティjsonを読み取ることができないため、このエラーメッセージのためにその後のyieldに到達できません。 私の最初の問題は 'if(response.ok)'ですが、削除してもresponse.json()はエラーを返します。 誰かが私にこれらのテスト方法を教えてもらえれば、非常に感謝します。

答えて

2

これが役に立てば幸い、私はこのようにそれを行うだろう、前の実行に応答オブジェクトをパスし、条件付きテスト:

export function* onFetchMessages(channel) { 
try { 
    yield put(requestMessages()) 
    const channel_name = channel.payload 
    const response = yield call(fetch,'/api/messages/'+channel_name) 

    if(response.ok){ 
     const res = yield response.json(); 

     const date = moment().format('lll'); 
     yield put(receiveMessages(res,channel.payload,date)) 
    } 

    } catch (error){ 
     yield put(rejectMessages(error)) 
    } 
} 

describe('onFetchMessages Saga',() => { 
let output = null; 
const saga = onFetchMessages(channel); //mock channel somewhere... 

it('should put request messages',() => { 
    output = saga.next().value; 
    let expected = put(requestMessages()); //make sure you import this dependency 
    expect(output).toEqual(expected); 
}); 

it('should call fetch...blabla',()=> { 
    output = saga.next(channel_name).value; //include channel_name so it is avaiable on the next iteration 
    let expected = call(fetch,'/api/messages/'+channel_name); //do all the mock you ned for this 
    expect(output).toEqual(expected); 
}); 

/*here comes you answer*/ 
it('should take response.ok into the if statemenet',()=> { 
    //your json yield is out the redux-saga context so I dont assert it 
    saga.next(response).value; //same as before, mock it with a ok property, so it is available 
    output = saga.next(res).value; //assert the put effect 
    let expected = put(receiveMessages(res,channel.payload,date)); //channel should be mock from previous test 
    expect(output).toEqual(expected); 
}); 

}); 

はあなたのコードに注目してくださいおそらくより私は認識していないんだもの、しかし、これを行います少なくともあなたの問題を解決するためにいくつかの行にuを入れてください。

+0

ありがとう、mocking okプロパティの応答は計画のようですが、どうすればいいでしょうか?最後のセクションをコード化することができれば、それは素晴らしいでしょう(実際に重要な部分です) – mtangula

+1

は、saga.next : 本当の価値 – andresmijares25

0

redux-saga-testingのように、ヘルパーライブラリを使用したい場合があります。

免責事項:

  • :私は冗談を使用して、あなたの具体例についてその正確に同じ問題

    を解決するために、このライブラリを書いた(ただし、モカのために同じことを動作します)、私は2つのことをするだろうまず、私は別の機能にAPI呼び出しを分けるだろう

  • それから私は、同期方法であなたのロジックをテストするために再来 - 佐賀・テストを使用します。
ここ

コードです:

import sagaHelper from 'redux-saga-testing'; 
import { call, put } from 'redux-saga/effects'; 
import { requestMessages, receiveMessages, rejectMessages } from './my-actions'; 

const api = url => fetch(url).then(response => { 
    if (response.ok) { 
     return response.json(); 
    } else { 
     throw new Error(response.status); // for example 
    } 
}); 

function* onFetchMessages(channel) { 
    try { 
     yield put(requestMessages()) 
     const channel_name = channel.payload 
     const res = yield call(api, '/api/messages/'+channel_name) 
     const date = moment().format('lll'); 

     yield put(receiveMessages(res,channel.payload,date)) 
    } catch (error){ 
     yield put(rejectMessages(error)) 
    } 
} 


describe('When testing a Saga that throws an error',() => { 
    const it = sagaHelper(onFetchMessages({ type: 'foo', payload: 'chan1'})); 

    it('should have called the API first, which will throw an exception', result => { 
     expect(result).toEqual(call(api, '/api/messages/chan1')); 
     return new Error('Something went wrong'); 
    }); 

    it('and then trigger an error action with the error message', result => { 
     expect(result).toEqual(put(rejectMessages('Something went wrong'))); 
    }); 
}); 

describe('When testing a Saga and it works fine',() => { 
    const it = sagaHelper(onFetchMessages({ type: 'foo', payload: 'chan2'})); 

    it('should have called the API first, which will return some data', result => { 
     expect(result).toEqual(call(api, '/api/messages/chan2')); 
     return 'some data'; 
    }); 

    it('and then call the success action with the data returned by the API', result => { 
     expect(result).toEqual(put(receiveMessages('some data', 'chan2', 'some date'))); 
     // you'll have to find a way to mock the date here' 
    }); 
}); 

あなたはproject's GitHub.

0

上の他の例(より複雑なもの)をたくさん見つけることができますここでは、関連する質問です:redux-sagaドキュメントでは、彼らはtakeがある例を持っています複数のアクションをリッスンします。私はこれが反だとは思わない

function* mySaga() { 
    while (true) { 
     const initialAction = yield take (['AUTH__LOGIN','AUTH__LOGOUT']); 
     if (initialAction.type === 'AUTH__LOGIN') { 
      const authTask = yield fork(doLogin); 
      const action = yield take(['AUTH__LOGOUT', 'AUTH__LOGIN_FAIL']); 
      if (action.type === 'AUTH__LOGOUT') { 
       yield cancel(authTask); 
       yield call (unauthorizeWithRemoteServer) 
      } 
     } else { 
      yield call (unauthorizeWithRemoteServer) 
     } 
    } 
} 

:これに基づき、私はあなたがこのredux-sagaドキュメントからの例の修正版であることを認識することができる(多かれ少なかれ、このようになります認証サガを書きました-patternはSagasを扱うときにテスト環境(Jest)の外で期待どおりに動作しますが、if文を扱う方法はありません。どのようにすればいいでしょうか?

関連する問題