2017-07-24 97 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