【问题标题】:istanbul ignore if not working - Server side test伊斯坦布尔忽略如果不工作 - 服务器端测试
【发布时间】:2020-11-23 08:03:34
【问题描述】:

我想跳过第二个 if 语句
在测试时,我不会通过任何“用户 ID”,因此我想跳过第二个 if。

async update(id: string, userid: string, input: UpdateNotificationInput) {
    const items = await this.model.query('id').eq(id).exec();
    if (items.length === 1) {
      /* istanbul ignore if */
      if (items[0].userId !== userid) {
        throw new BadRequestException();
      }
      const { appTargetId, createDate } = items[0];
      return await this.model.update({ appTargetId, createDate }, input);
    } else {
      throw new BadRequestException();
    }
  }


下面的 if 不应该被访问。

if (items[0].userId !== userid) {
        throw new BadRequestException();
      }

我的“istanbul ignore if”或“istanbul ignore next”似乎不起作用。
当我运行我的测试覆盖率时,访问了 if 语句并出现错误。
我是否以正确的方式使用它?

【问题讨论】:

标签: javascript typescript jestjs istanbul


【解决方案1】:

如果我理解正确,您永远不会在测试中传递 userId,因此if (items[0].userId !== userid) 条件始终为真,您的测试将失败。

/* istanbul ignore if */ 注释仅在覆盖率报告中禁用此行。它不会阻止您的测试运行程序执行该行。

如果您想忽略测试中的行,则应使其以测试环境为条件。例如,在节点中,您可以使用:

      if (process.env.NODE_ENV != 'test' && items[0].userId !== userid) {
        throw new BadRequestException();
      }

然后使用 NODE_ENV=test 环境变量集运行您的测试(这是大多数设置中的默认设置)。

更好的方法是在您的测试中实际传递正确的 userId。然后istanbul ignore if 注释将使 if 语句的内容不计入测试覆盖率,因此您不必为错误的请求条件编写额外的测试。

我个人只是编写这样的测试,以确保在这种情况下我实际上返回了正确的错误。

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2016-04-05
    相关资源
    最近更新 更多