Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Express router Jest测试中模拟方法?_Javascript_Node.js_Unit Testing_Express_Jestjs - Fatal编程技术网

Javascript 如何在Express router Jest测试中模拟方法?

Javascript 如何在Express router Jest测试中模拟方法?,javascript,node.js,unit-testing,express,jestjs,Javascript,Node.js,Unit Testing,Express,Jestjs,我正在尝试使用Jest+Supertest在Node.js应用程序中测试路由器,但我的路由器正在调用服务,这将调用端点: router.post('/login',异步(req,res,next)=>{ 试一试{ const{username,password}=req.body; //我想模拟userService.getUserInfo函数,因为它正在进行POST调用 const identity=await userService.getUserInfo(用户名、密码); 如果(!iden

我正在尝试使用Jest+Supertest在Node.js应用程序中测试路由器,但我的路由器正在调用服务,这将调用端点:

router.post('/login',异步(req,res,next)=>{
试一试{
const{username,password}=req.body;
//我想模拟userService.getUserInfo函数,因为它正在进行POST调用
const identity=await userService.getUserInfo(用户名、密码);
如果(!identity.authenticated){
返回res.json({});
}
const requiredTenantId=process.env.TENANT\u ID;
const-tenant=identity.tenants.find(it=>it.id==requiredTenantId);
如果(需要租户&&!租户){
返回res.json({});
}
const userResponse={
…身份,
令牌:jwt.sign(identity,envVars.getVar(envVars.variables.AUTH_-token_-SECRET){
expiresIn:'2h',
}),
};
返回res.json(userResponse);
}捕捉(错误){
返回下一个(错误);
}
});
这是我的测试,效果很好:

test('Authorized-使用用户对象响应',async()=>{
常量响应=等待请求(应用程序)
.post('/api/user/login')
.发送(用户.授权);
expect(response.body).toHaveProperty('authenticated',true);
});
这就是
getUserInfo
函数的外观:

const getUserInfo = async (username, password) => {
  const identity = await axios.post('/user', {username, password});

  return identity;
}
但是它在路由器内部执行方法
getUserInfo
,这个方法正在进行REST调用——我想模拟这个方法,以避免对其他服务的REST调用。 如何做到这一点

我在Jest文档中发现了一个mock实现函数


但是如何在supertest测试中模拟func呢

您可以在测试的顶部使用jest的自动模拟

像这样:

jest.mock('./path/to/userService');

// and include it as well in your test
const userService = require('./path/to/userService');
它将生成整个模块的模拟,每个函数都将替换为
jest.fn()
,而不进行任何实现

然后,根据userService,如果它只是一个对象,那么它的
getUserInfo
方法将是一个jest.fn(),您可以如下设置它的返回值:

// resolved value as it should return a promise
userService.getUserInfo.mockResolvedValue(mockIdentity);
const mockIdentity = {
      authenticated: true,
      tenants: [
        {
          id: "x12",
          mockInfo: "mock-info-value"
        }
      ],
      mother: "Superwoman",
      father: "Superman"
    })
  }
mockIdentity必须看起来像这样:

// resolved value as it should return a promise
userService.getUserInfo.mockResolvedValue(mockIdentity);
const mockIdentity = {
      authenticated: true,
      tenants: [
        {
          id: "x12",
          mockInfo: "mock-info-value"
        }
      ],
      mother: "Superwoman",
      father: "Superman"
    })
  }

我猜您在这些测试之前启动了一个“真正的”api服务器,这意味着您的测试运行在不同的节点上下文(单独的进程)中,因此没有理由说测试可以模拟其中的某些内容。我说得对吗?我在描述中添加了
getUserInfo
。我想模拟这个函数,以免调用外部API。我的假设是否正确?启动API服务器并运行测试?不,“API服务器”是外部服务非常感谢!但是我应该把
userService.getUserInfo.mockResolvedValue(mockIdentity)放在哪里?我正在使用
supertest
请求及其语法:
(请求(…).post(…).send(…)
@Karen,然后启动请求
请求(…).post(…).send(…)
我收到一个错误:
expect(已接收)。toHaveProperty(路径,值)预期路径:“authenticated”接收路径:[]预期值:true收到的值:{“错误”:“无法读取未定义的属性'find'”}
将尝试修复它并让您知道结果它正在使用空对象响应,而不是
mockidentity
objI有类似的情况,除了我的
fetch
调用之外,它位于一个中间件中,该中间件最终根据响应填充请求对象。这对你有用吗@Karen