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

时间:2020-04-02 14:45:41

标签: javascript node.js unit-testing express jestjs

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

router.post('/login', async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // I WANT TO MOCK userService.getUserInfo FUNCTION, BECAUSE IT IS MAKING A POST CALL
    const identity = await userService.getUserInfo(username, password);

    if (!identity.authenticated) {
      return res.json({});
    }

    const requiredTenantId = process.env.TENANT_ID;
    const tenant = identity.tenants.find(it => it.id === requiredTenantId);

    if (requiredTenantId && !tenant) {
      return res.json({});
    }

    const userResponse = {
      ...identity,
      token: jwt.sign(identity, envVars.getVar(envVars.variables.AUTH_TOKEN_SECRET), {
        expiresIn: '2h',
      }),
    };

    return res.json(userResponse);
  } catch (err) {
    return next(err);
  }
});

这是我的测试,效果很好:

test('Authorized - respond with user object', async () => {
  const response = await request(app)
    .post('/api/user/login')
    .send(users.authorized);
  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文档https://jestjs.io/docs/en/mock-function-api.html#mockfnmockimplementationfn

中找到了 mockImplementation 函数

但是如何在超级测试中模拟func?

1 个答案:

答案 0 :(得分:1)

您可以在测试的顶部使用玩笑的自动嘲笑

像这样:

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time (&rawtime);
  timeinfo = localtime (&rawtime);
  printf ("Current local time and date: %s", asctime(timeinfo));

  return 0;
}

它将生成整个模块的模型,并且每个函数都将替换为jest.mock('./path/to/userService'); // and include it as well in your test const userService = require('./path/to/userService'); ,而无需实现

,然后取决于userService(如果它只是一个对象),它的jest.fn()方法将是jest.fn(),您可以这样设置它的返回值:

getUserInfo

和模拟身份必须看起来像这样:

// resolved value as it should return a promise
userService.getUserInfo.mockResolvedValue(mockIdentity);
相关问题