【问题标题】:How to Mock Module function so that it throws an exception when called from within somewhere in your code如何模拟模块函数,以便在从代码中的某个位置调用时引发异常
【发布时间】:2020-12-15 06:28:10
【问题描述】:

开玩笑,我想测试一个这样写的 express api

router.get('/api-does-something', api.middleware, async (req, res) => {
  try {
    const { destructSomeData } = req.fromValue;
    const responseData = await someModule.getSomething(destructSomeData);
    res.json(responseData);
  } catch (e) {
    errorModule.error(
      res,
      errorCodes.SERVER_ERROR,
      e
    );
  }
});

开玩笑地说,我知道如何测试 api 的 try catch 部分,但我不知道如何模拟 someModule.getSomething(destructSomeData) 以便它抛出异常,所以我可以开玩笑地测试是否抛出了异常

所以我的问题是如何模拟 someModule.getSomething(destructSomeData) 以使其在此 api 中引发异常?

【问题讨论】:

    标签: node.js unit-testing jestjs mocking


    【解决方案1】:

    你只需要在你的测试文件中模拟模块并模拟如下实现

    // test file
    const someModule = require('./pathTo/someModule')
    jest.mock('./pathTo/someModule')
    
    describe('test', ()=>{
     it('should blow up on getSomething', async () => {
      someModule.getSomething.mockImplementation(()=> Promise.reject(new Error('Blew up')))
      
      // continue with test... it should blow up!
     })
    })
    

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 2023-03-07
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多