Javascript 模拟在客户端传递的函数(例如redis get函数)的req和res的最佳方法是什么?下面的示例

Javascript 模拟在客户端传递的函数(例如redis get函数)的req和res的最佳方法是什么?下面的示例,javascript,reactjs,express,mocking,jestjs,Javascript,Reactjs,Express,Mocking,Jestjs,因此,我试图找出在jest中模拟函数的请求和响应的最佳方法,我见过许多方法,一些使用jest.fn(),另一些使用sinon,还有一些使用外部包 当想要返回状态、json和请求的内容时,最好的方法是什么?请参阅下面的代码 export const redisGet = (client) => async (req, res, next) => { try { const { postCode, houseNumber, } = req.p

因此,我试图找出在jest中模拟函数的请求和响应的最佳方法,我见过许多方法,一些使用
jest.fn()
,另一些使用sinon,还有一些使用外部包

当想要返回状态、json和请求的内容时,最好的方法是什么?请参阅下面的代码

export const redisGet = (client) => async (req, res, next) => {
  try {

    const {
      postCode,
      houseNumber,
    } = req.params
  
    const addressObj = {
      postCode,
      houseNumber,
    }
  
    const addressGetParams = JSON.stringify(addressObj)

    await client.get(addressGetParams, (err, data) => {
      if (data) {
        return res.status(200).send({
          error: false,
          message: `Addresses found.`,
          data: JSON.parse(data)
        })
      }
      
      if (err) {
        return res.status(400).send({
          error: err,
          message: `Bad request`,
          data: JSON.parse(data),
        })
      }

      next()
    })
  } catch (e) {
    throw Error(e)
  }
}

jestjs
sinonjs
都可以模拟/存根模块。选择其中一个就足够了。下面是一个使用
jestjs
的示例。单元测试解决方案:

index.ts

export const redisGet=(客户端)=>async(请求、恢复、下一步)=>{
试一试{
const{postCode,houseNumber}=req.params;
const addressObj={邮政编码,门牌号};
const addressGetParams=JSON.stringify(addressObj);
client.get(addressGetParams,(err,data)=>{
如果(数据){
返回资源状态(200)。发送({
错误:false,
消息:`找到地址。`,
数据:JSON.parse(数据),
});
}
如果(错误){
返回资源状态(400)。发送({
错误:呃,
消息:`Bad request`,
});
}
next();
});
}捕获(e){
投掷误差(e);
}
};
index.test.ts

从“/”导入{redisGet};
描述('63253476',()=>{
它('should found addresses',async()=>{
常量mClient={
get:jest.fn().mockImplementationOnce((参数,回调)=>{
回调(null,{“id”:1}');
}),
};
const mReq={params:{邮政编码:123,门牌号:456};
const mRes={status:jest.fn().mockReturnThis(),send:jest.fn()};
const mNext=jest.fn();
等待再贴现(mClient)(mReq、mRes、mNext);
expect(mClient.get).toBeCalledWith(JSON.stringify({postCode:123,houseNumber:456}),expect.any(Function));
预期(mRes.状态)。与(200)一起调用;
expect(mRes.send).toBeCalledWith({error:false,message:`Addresses found.`,data:{id:1}});
expect(mNext).not.toBeCalled();
});
它('应该处理错误',异步()=>{
const mErr=新错误(“超时”);
常量mClient={
get:jest.fn().mockImplementationOnce((参数,回调)=>{
回调(mErr);
}),
};
const mReq={params:{邮政编码:123,门牌号:456};
const mRes={status:jest.fn().mockReturnThis(),send:jest.fn()};
const mNext=jest.fn();
等待再贴现(mClient)(mReq、mRes、mNext);
expect(mClient.get).toBeCalledWith(JSON.stringify({postCode:123,houseNumber:456}),expect.any(Function));
期望(mRes.状态)与(400)一起调用;
expect(mRes.send).toBeCalledWith({error:mErr,message:`Bad request`});
expect(mNext).not.toBeCalled();
});
它('应该什么都不做并调用下一个中间件',async()=>{
常量mClient={
get:jest.fn().mockImplementationOnce((参数,回调)=>{
回调();
}),
};
const mReq={params:{邮政编码:123,门牌号:456};
const mRes={status:jest.fn().mockReturnThis(),send:jest.fn()};
const mNext=jest.fn();
等待再贴现(mClient)(mReq、mRes、mNext);
expect(mClient.get).toBeCalledWith(JSON.stringify({postCode:123,houseNumber:456}),expect.any(Function));
expect(mRes.status).not.toBeCalled();
expect(mRes.send).not.toBeCalled();
expect(mNext).toBeCalled();
});
});
单元测试结果和覆盖率报告:

 PASS  src/stackoverflow/63253476/index.test.ts (11.338s)
  63253476
    ✓ should found addresses (8ms)
    ✓ should handle error (2ms)
    ✓ should do nothing and call next middleware (2ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    92.86 |      100 |      100 |    91.67 |                   |
 index.ts |    92.86 |      100 |      100 |    91.67 |                26 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        13.824s