2017-07-24 102 views
0

我正在用Jest.js測試生成器函數,但我的問題一般是關於模塊內模擬函數。Jest.js嘲笑模塊內的方法

Foo.js有: -

const Foo = { 
    callMe() { 
    return true; 
    }, 
    callMe2() { 
    return true; 
    } 
}; 
export default Foo; 

在我的玩笑測試我想Foo.callMe拋出一個錯誤,但我不能讓它與玩笑模擬工作。

import Foo from '../Foo'; 

it('fails my generator function',() => { 
    const gen = myGenFunction(); 
    expect(gen.next().value).toEqual(call(Foo.callMe)); 
}); 

發電機功能看起來是這樣的:

export function* myGenFunction(action) { 
    try { 
    const response = yield call(Foo.callMe); 
    console.log('Success'); 
    } catch(err) { 
    console.log('Error!!!'); 
    } finally { 
    // do something else 
    } 
} 

我怎樣才能讓Foo.callMe拋出一個錯誤?我已經嘗試了一些東西,但目前爲止還沒有成功。

回答

0

我已經設法通過使用REDX傳奇的throw方法來實現我想要的。

it('fails my generator function',() => { 
    const error = { message: 'Look see here, an error' }; 

    const gen = myGenFunction(); 
    ... 

    expect(gen.throw(error).value).toEqual(
     put(actions.setIsLoading(false)), // action that happens on fail 
     'gen should yield an Effect put(actions.setIsLoading(false))' 
); 
}); 

它很好地記錄在這裏:https://redux-saga.js.org/docs/basics/ErrorHandling.html