【问题标题】:Jest.js Mocking a method within a moduleJest.js 模拟模块中的方法
【发布时间】:2017-12-30 00:10:27
【问题描述】:

我正在使用 Jest.js 测试生成器函数,但我的问题通常是关于模块内的模拟函数。

Foo.js 有:-

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

在我的 Jest 测试中,我希望 Foo.callMe 抛出一个错误,但我无法让它与 Jest 模拟一起使用。

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 抛出错误?我已经尝试了一些东西,但到目前为止没有任何效果。

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    我已经通过使用 redux-saga 的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多