2017-08-14 31 views
1

我有一個傳奇如何使用API​​調用測試傳奇?

export function* mysaga(api, action) { 
    const response = yield call(api.service, action); 
    yield put(NavActions.goTo('Page', { success: response.ok })); 
} 

這調用API,並返回值導航到通過API調用的結果(response.ok)另一個屏幕。

it('test',() => { 
    // ... 

    const gen = mysaga(api, action); 
    const step =() => gen.next().value; 

    // doesn't actually run the api 
    const response = call(api.service, {}); 

    expect(step()).toMatchObject(response); // ok 

    // error, Cannot read property 'ok' of undefined 
    expect(step()).toMatchObject(
    put(NavActions.goTo('Page', { success: response.ok })) 
); 
}); 

因爲它不是實際運行的API調用response沒有得到確定。

我不知道該怎麼做才能測試這種情況。

我如何測試我的傳奇的第二步?

回答

3

默認情況下,yield表達式解析爲它生成的任何內容。但是,您可以將另一個值傳遞給gen.next方法,然後將yield表達式解析爲您在那裏傳遞的內容。

所以這應該做的伎倆(未經測試):

const gen = rootSaga(api, action); 
const step = (val) => gen.next(val).value; 

const mockResponse = { ok: true }; 
const response = call(api.service, {}); 

expect(step(mockResponse)).toMatchObject(response); // ok 

expect(step()).toMatchObject(
    put(NavActions.goTo('Page', { success: true })) 
);