【问题标题】:Why all the async functions seem like they are not covered branches in Jest/Istanbul coverage report?为什么所有异步函数似乎都没有在 Jest/Istanbul 覆盖率报告中被覆盖?
【发布时间】:2021-02-21 13:36:11
【问题描述】:

我的应用程序中都有这个: 我有一个很好的功能,但是它在运行 Jest 测试覆盖脚本后由伊斯坦布尔生成的测试覆盖报告中的 async function 部分显示“分支未覆盖”。

这是什么意思?我怎样才能覆盖它?

我不明白这些功能没有涵盖什么。

“getPolicyStatsAPI”函数的测试示例: 其余功能的测试方式相同。我不相信答案在测试套件中。但如果需要,我可以分享剩下的。

  describe(`API Calls`, () => {
    const mockFetch = jest.fn()
    global.fetch = mockFetch
    beforeEach(() => {
      mockFetch.mockClear()
    })
    test('getPolicyStatsAPI fetches the data and returns it as expected', async () => {
      mockFetch.mockReturnValueOnce(createAPIResponse(policySearchState))

      const response = await getPolicyStatsAPI(reqBody)
      expect(fetch).toBeCalledTimes(1)
      expect(response).toEqual(policySearchState.data)
    })
    test('getPolicyStatsAPI returns error on exception', async () => {
      const error = new Error(errorMessage)
      // eslint-disable-next-line prefer-promise-reject-errors
      mockFetch.mockImplementationOnce(() => Promise.reject(errorMessage))
      await expect(getPolicyStatsAPI(reqBody)).rejects.toEqual(error)
      expect(fetch).toBeCalledTimes(1)
    })
  })

这是我收到“未覆盖分支”警告的代码: 未覆盖的分支警告出现在代码的“异步函数”部分上,并且仅在此处以黄色突出显示。

export async function getPolicyStatsAPI(reqBody: APIRequestBody) {
  const body: APIRequestBody = {
    ...reqBody,
  }
  type ExpectedResponse = { data: PolicyStats[] }
  const response = await callAPI<ExpectedResponse>({
    url: Endpoint.POLICY_STATS,
    method: 'POST',
    body,
  })
  return response.data
}

测试覆盖率报告图片:

【问题讨论】:

  • Please post code as text, not images。此外,包括完整的错误消息,可能还有你所拥有的测试样本,因为目前很难说出对你的要求。
  • 我也遇到了同样的问题,你解决了吗?
  • 不,我从来没有找到答案;也不是解决方案。对不起@EricDS

标签: javascript typescript jestjs istanbul


【解决方案1】:

在发表评论后,我自己尝试了一些其他修复,显然删除了我的 jest.config.js 中的 transform 键解决了这个问题:

module.exports = {
  ...
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.test.json',
      babelConfig: 'babel.config.js'
    },
  },

  // Removed this part:
  // transform: {
  //   '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
  //   '^.+\\.(ts|tsx)?$': 'ts-jest',
  // },

  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      'identity-obj-proxy',
  },
  ..
}

不确定是否与您的项目相同,但您可以尝试一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多