如何测试 fetch 调用以获得 100% 的测试覆盖率

时间:2021-07-14 11:53:29

标签: javascript unit-testing jestjs

给定具有单个函数的文件:

export const fetchGetCard = (lang, word) => {
    return fetch("/getCard", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ lang: lang, word: word })
    }).then(response => response.text())
}

如何使用 Jest 创建测试以使该文件具有 100% 的代码覆盖率?或者完全忽略测试是否值得?

1 个答案:

答案 0 :(得分:1)

  1. fetch()创建一个模拟
  2. 从它返回解决了Promise
  3. 从它返回失败 Promise(错误/抛出/等)
  4. 检查 fetchGetCard() 的返回值
  5. 断言底层对象中的预期参数和值

如果您使用 require(),您可以通过多种方式轻松模拟 fetch()

  • 为导入创建一个函数
  • 使用 require.cache[require.resolve("fetch")].exports = <your mock> 访问缓存
  • 使用 SinonJS 进行模拟,在测试中先导入 fetch() myfetch = require("fetch"),调用 const stub = sinon.stub(require.cache[require.resolve("fetch")], "exports"),执行操作,然后使用 stub.restore() 恢复它